video.novtt.js 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643
  1. /**
  2. * @license
  3. * Video.js 8.3.0 <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 = "8.3.0";
  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. const hooks_ = {};
  25. /**
  26. * Get a list of hooks for a specific lifecycle
  27. *
  28. * @param {string} type
  29. * the lifecycle 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. const hooks = function (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. const hook = function (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. const removeHook = function (type, fn) {
  69. const 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. const hookOnce = function (type, fn) {
  87. hooks(type, [].concat(fn).map(original => {
  88. const wrapper = (...args) => {
  89. removeHook(type, wrapper);
  90. return original(...args);
  91. };
  92. return wrapper;
  93. }));
  94. };
  95. /**
  96. * @file fullscreen-api.js
  97. * @module fullscreen-api
  98. */
  99. /**
  100. * Store the browser-specific methods for the fullscreen API.
  101. *
  102. * @type {Object}
  103. * @see [Specification]{@link https://fullscreen.spec.whatwg.org}
  104. * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}
  105. */
  106. const FullscreenApi = {
  107. prefixed: true
  108. };
  109. // browser API methods
  110. const apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror', 'fullscreen'],
  111. // WebKit
  112. ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror', '-webkit-full-screen'],
  113. // Mozilla
  114. ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror', '-moz-full-screen'],
  115. // Microsoft
  116. ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError', '-ms-fullscreen']];
  117. const specApi = apiMap[0];
  118. let browserApi;
  119. // determine the supported set of functions
  120. for (let i = 0; i < apiMap.length; i++) {
  121. // check for exitFullscreen function
  122. if (apiMap[i][1] in document) {
  123. browserApi = apiMap[i];
  124. break;
  125. }
  126. }
  127. // map the browser API names to the spec API names
  128. if (browserApi) {
  129. for (let i = 0; i < browserApi.length; i++) {
  130. FullscreenApi[specApi[i]] = browserApi[i];
  131. }
  132. FullscreenApi.prefixed = browserApi[0] !== specApi[0];
  133. }
  134. /**
  135. * @file create-logger.js
  136. * @module create-logger
  137. */
  138. // This is the private tracking variable for the logging history.
  139. let history = [];
  140. /**
  141. * Log messages to the console and history based on the type of message
  142. *
  143. * @private
  144. * @param {string} type
  145. * The name of the console method to use.
  146. *
  147. * @param {Array} args
  148. * The arguments to be passed to the matching console method.
  149. */
  150. const LogByTypeFactory = (name, log) => (type, level, args) => {
  151. const lvl = log.levels[level];
  152. const lvlRegExp = new RegExp(`^(${lvl})$`);
  153. if (type !== 'log') {
  154. // Add the type to the front of the message when it's not "log".
  155. args.unshift(type.toUpperCase() + ':');
  156. }
  157. // Add console prefix after adding to history.
  158. args.unshift(name + ':');
  159. // Add a clone of the args at this point to history.
  160. if (history) {
  161. history.push([].concat(args));
  162. // only store 1000 history entries
  163. const splice = history.length - 1000;
  164. history.splice(0, splice > 0 ? splice : 0);
  165. }
  166. // If there's no console then don't try to output messages, but they will
  167. // still be stored in history.
  168. if (!window.console) {
  169. return;
  170. }
  171. // Was setting these once outside of this function, but containing them
  172. // in the function makes it easier to test cases where console doesn't exist
  173. // when the module is executed.
  174. let fn = window.console[type];
  175. if (!fn && type === 'debug') {
  176. // Certain browsers don't have support for console.debug. For those, we
  177. // should default to the closest comparable log.
  178. fn = window.console.info || window.console.log;
  179. }
  180. // Bail out if there's no console or if this type is not allowed by the
  181. // current logging level.
  182. if (!fn || !lvl || !lvlRegExp.test(type)) {
  183. return;
  184. }
  185. fn[Array.isArray(args) ? 'apply' : 'call'](window.console, args);
  186. };
  187. function createLogger$1(name) {
  188. // This is the private tracking variable for logging level.
  189. let level = 'info';
  190. // the curried logByType bound to the specific log and history
  191. let logByType;
  192. /**
  193. * Logs plain debug messages. Similar to `console.log`.
  194. *
  195. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  196. * of our JSDoc template, we cannot properly document this as both a function
  197. * and a namespace, so its function signature is documented here.
  198. *
  199. * #### Arguments
  200. * ##### *args
  201. * *[]
  202. *
  203. * Any combination of values that could be passed to `console.log()`.
  204. *
  205. * #### Return Value
  206. *
  207. * `undefined`
  208. *
  209. * @namespace
  210. * @param {...*} args
  211. * One or more messages or objects that should be logged.
  212. */
  213. const log = function (...args) {
  214. logByType('log', level, args);
  215. };
  216. // This is the logByType helper that the logging methods below use
  217. logByType = LogByTypeFactory(name, log);
  218. /**
  219. * Create a new sublogger which chains the old name to the new name.
  220. *
  221. * For example, doing `videojs.log.createLogger('player')` and then using that logger will log the following:
  222. * ```js
  223. * mylogger('foo');
  224. * // > VIDEOJS: player: foo
  225. * ```
  226. *
  227. * @param {string} name
  228. * The name to add call the new logger
  229. * @return {Object}
  230. */
  231. log.createLogger = subname => createLogger$1(name + ': ' + subname);
  232. /**
  233. * Enumeration of available logging levels, where the keys are the level names
  234. * and the values are `|`-separated strings containing logging methods allowed
  235. * in that logging level. These strings are used to create a regular expression
  236. * matching the function name being called.
  237. *
  238. * Levels provided by Video.js are:
  239. *
  240. * - `off`: Matches no calls. Any value that can be cast to `false` will have
  241. * this effect. The most restrictive.
  242. * - `all`: Matches only Video.js-provided functions (`debug`, `log`,
  243. * `log.warn`, and `log.error`).
  244. * - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls.
  245. * - `info` (default): Matches `log`, `log.warn`, and `log.error` calls.
  246. * - `warn`: Matches `log.warn` and `log.error` calls.
  247. * - `error`: Matches only `log.error` calls.
  248. *
  249. * @type {Object}
  250. */
  251. log.levels = {
  252. all: 'debug|log|warn|error',
  253. off: '',
  254. debug: 'debug|log|warn|error',
  255. info: 'log|warn|error',
  256. warn: 'warn|error',
  257. error: 'error',
  258. DEFAULT: level
  259. };
  260. /**
  261. * Get or set the current logging level.
  262. *
  263. * If a string matching a key from {@link module:log.levels} is provided, acts
  264. * as a setter.
  265. *
  266. * @param {string} [lvl]
  267. * Pass a valid level to set a new logging level.
  268. *
  269. * @return {string}
  270. * The current logging level.
  271. */
  272. log.level = lvl => {
  273. if (typeof lvl === 'string') {
  274. if (!log.levels.hasOwnProperty(lvl)) {
  275. throw new Error(`"${lvl}" in not a valid log level`);
  276. }
  277. level = lvl;
  278. }
  279. return level;
  280. };
  281. /**
  282. * Returns an array containing everything that has been logged to the history.
  283. *
  284. * This array is a shallow clone of the internal history record. However, its
  285. * contents are _not_ cloned; so, mutating objects inside this array will
  286. * mutate them in history.
  287. *
  288. * @return {Array}
  289. */
  290. log.history = () => history ? [].concat(history) : [];
  291. /**
  292. * Allows you to filter the history by the given logger name
  293. *
  294. * @param {string} fname
  295. * The name to filter by
  296. *
  297. * @return {Array}
  298. * The filtered list to return
  299. */
  300. log.history.filter = fname => {
  301. return (history || []).filter(historyItem => {
  302. // if the first item in each historyItem includes `fname`, then it's a match
  303. return new RegExp(`.*${fname}.*`).test(historyItem[0]);
  304. });
  305. };
  306. /**
  307. * Clears the internal history tracking, but does not prevent further history
  308. * tracking.
  309. */
  310. log.history.clear = () => {
  311. if (history) {
  312. history.length = 0;
  313. }
  314. };
  315. /**
  316. * Disable history tracking if it is currently enabled.
  317. */
  318. log.history.disable = () => {
  319. if (history !== null) {
  320. history.length = 0;
  321. history = null;
  322. }
  323. };
  324. /**
  325. * Enable history tracking if it is currently disabled.
  326. */
  327. log.history.enable = () => {
  328. if (history === null) {
  329. history = [];
  330. }
  331. };
  332. /**
  333. * Logs error messages. Similar to `console.error`.
  334. *
  335. * @param {...*} args
  336. * One or more messages or objects that should be logged as an error
  337. */
  338. log.error = (...args) => logByType('error', level, args);
  339. /**
  340. * Logs warning messages. Similar to `console.warn`.
  341. *
  342. * @param {...*} args
  343. * One or more messages or objects that should be logged as a warning.
  344. */
  345. log.warn = (...args) => logByType('warn', level, args);
  346. /**
  347. * Logs debug messages. Similar to `console.debug`, but may also act as a comparable
  348. * log if `console.debug` is not available
  349. *
  350. * @param {...*} args
  351. * One or more messages or objects that should be logged as debug.
  352. */
  353. log.debug = (...args) => logByType('debug', level, args);
  354. return log;
  355. }
  356. /**
  357. * @file log.js
  358. * @module log
  359. */
  360. const log$1 = createLogger$1('VIDEOJS');
  361. const createLogger = log$1.createLogger;
  362. /**
  363. * @file obj.js
  364. * @module obj
  365. */
  366. /**
  367. * @callback obj:EachCallback
  368. *
  369. * @param {*} value
  370. * The current key for the object that is being iterated over.
  371. *
  372. * @param {string} key
  373. * The current key-value for object that is being iterated over
  374. */
  375. /**
  376. * @callback obj:ReduceCallback
  377. *
  378. * @param {*} accum
  379. * The value that is accumulating over the reduce loop.
  380. *
  381. * @param {*} value
  382. * The current key for the object that is being iterated over.
  383. *
  384. * @param {string} key
  385. * The current key-value for object that is being iterated over
  386. *
  387. * @return {*}
  388. * The new accumulated value.
  389. */
  390. const toString$1 = Object.prototype.toString;
  391. /**
  392. * Get the keys of an Object
  393. *
  394. * @param {Object}
  395. * The Object to get the keys from
  396. *
  397. * @return {string[]}
  398. * An array of the keys from the object. Returns an empty array if the
  399. * object passed in was invalid or had no keys.
  400. *
  401. * @private
  402. */
  403. const keys = function (object) {
  404. return isObject$1(object) ? Object.keys(object) : [];
  405. };
  406. /**
  407. * Array-like iteration for objects.
  408. *
  409. * @param {Object} object
  410. * The object to iterate over
  411. *
  412. * @param {obj:EachCallback} fn
  413. * The callback function which is called for each key in the object.
  414. */
  415. function each(object, fn) {
  416. keys(object).forEach(key => fn(object[key], key));
  417. }
  418. /**
  419. * Array-like reduce for objects.
  420. *
  421. * @param {Object} object
  422. * The Object that you want to reduce.
  423. *
  424. * @param {Function} fn
  425. * A callback function which is called for each key in the object. It
  426. * receives the accumulated value and the per-iteration value and key
  427. * as arguments.
  428. *
  429. * @param {*} [initial = 0]
  430. * Starting value
  431. *
  432. * @return {*}
  433. * The final accumulated value.
  434. */
  435. function reduce(object, fn, initial = 0) {
  436. return keys(object).reduce((accum, key) => fn(accum, object[key], key), initial);
  437. }
  438. /**
  439. * Returns whether a value is an object of any kind - including DOM nodes,
  440. * arrays, regular expressions, etc. Not functions, though.
  441. *
  442. * This avoids the gotcha where using `typeof` on a `null` value
  443. * results in `'object'`.
  444. *
  445. * @param {Object} value
  446. * @return {boolean}
  447. */
  448. function isObject$1(value) {
  449. return !!value && typeof value === 'object';
  450. }
  451. /**
  452. * Returns whether an object appears to be a "plain" object - that is, a
  453. * direct instance of `Object`.
  454. *
  455. * @param {Object} value
  456. * @return {boolean}
  457. */
  458. function isPlain(value) {
  459. return isObject$1(value) && toString$1.call(value) === '[object Object]' && value.constructor === Object;
  460. }
  461. /**
  462. * Merge two objects recursively.
  463. *
  464. * Performs a deep merge like
  465. * {@link https://lodash.com/docs/4.17.10#merge|lodash.merge}, but only merges
  466. * plain objects (not arrays, elements, or anything else).
  467. *
  468. * Non-plain object values will be copied directly from the right-most
  469. * argument.
  470. *
  471. * @param {Object[]} sources
  472. * One or more objects to merge into a new object.
  473. *
  474. * @return {Object}
  475. * A new object that is the merged result of all sources.
  476. */
  477. function merge$2(...sources) {
  478. const result = {};
  479. sources.forEach(source => {
  480. if (!source) {
  481. return;
  482. }
  483. each(source, (value, key) => {
  484. if (!isPlain(value)) {
  485. result[key] = value;
  486. return;
  487. }
  488. if (!isPlain(result[key])) {
  489. result[key] = {};
  490. }
  491. result[key] = merge$2(result[key], value);
  492. });
  493. });
  494. return result;
  495. }
  496. /**
  497. * Object.defineProperty but "lazy", which means that the value is only set after
  498. * it is retrieved the first time, rather than being set right away.
  499. *
  500. * @param {Object} obj the object to set the property on
  501. * @param {string} key the key for the property to set
  502. * @param {Function} getValue the function used to get the value when it is needed.
  503. * @param {boolean} setter whether a setter should be allowed or not
  504. */
  505. function defineLazyProperty(obj, key, getValue, setter = true) {
  506. const set = value => Object.defineProperty(obj, key, {
  507. value,
  508. enumerable: true,
  509. writable: true
  510. });
  511. const options = {
  512. configurable: true,
  513. enumerable: true,
  514. get() {
  515. const value = getValue();
  516. set(value);
  517. return value;
  518. }
  519. };
  520. if (setter) {
  521. options.set = set;
  522. }
  523. return Object.defineProperty(obj, key, options);
  524. }
  525. var Obj = /*#__PURE__*/Object.freeze({
  526. __proto__: null,
  527. each: each,
  528. reduce: reduce,
  529. isObject: isObject$1,
  530. isPlain: isPlain,
  531. merge: merge$2,
  532. defineLazyProperty: defineLazyProperty
  533. });
  534. /**
  535. * @file browser.js
  536. * @module browser
  537. */
  538. /**
  539. * Whether or not this device is an iPod.
  540. *
  541. * @static
  542. * @type {Boolean}
  543. */
  544. let IS_IPOD = false;
  545. /**
  546. * The detected iOS version - or `null`.
  547. *
  548. * @static
  549. * @type {string|null}
  550. */
  551. let IOS_VERSION = null;
  552. /**
  553. * Whether or not this is an Android device.
  554. *
  555. * @static
  556. * @type {Boolean}
  557. */
  558. let IS_ANDROID = false;
  559. /**
  560. * The detected Android version - or `null` if not Android or indeterminable.
  561. *
  562. * @static
  563. * @type {number|string|null}
  564. */
  565. let ANDROID_VERSION;
  566. /**
  567. * Whether or not this is Mozilla Firefox.
  568. *
  569. * @static
  570. * @type {Boolean}
  571. */
  572. let IS_FIREFOX = false;
  573. /**
  574. * Whether or not this is Microsoft Edge.
  575. *
  576. * @static
  577. * @type {Boolean}
  578. */
  579. let IS_EDGE = false;
  580. /**
  581. * Whether or not this is any Chromium Browser
  582. *
  583. * @static
  584. * @type {Boolean}
  585. */
  586. let IS_CHROMIUM = false;
  587. /**
  588. * Whether or not this is any Chromium browser that is not Edge.
  589. *
  590. * This will also be `true` for Chrome on iOS, which will have different support
  591. * as it is actually Safari under the hood.
  592. *
  593. * Deprecated, as the behaviour to not match Edge was to prevent Legacy Edge's UA matching.
  594. * IS_CHROMIUM should be used instead.
  595. * "Chromium but not Edge" could be explicitly tested with IS_CHROMIUM && !IS_EDGE
  596. *
  597. * @static
  598. * @deprecated
  599. * @type {Boolean}
  600. */
  601. let IS_CHROME = false;
  602. /**
  603. * The detected Chromium version - or `null`.
  604. *
  605. * @static
  606. * @type {number|null}
  607. */
  608. let CHROMIUM_VERSION = null;
  609. /**
  610. * The detected Google Chrome version - or `null`.
  611. * This has always been the _Chromium_ version, i.e. would return on Chromium Edge.
  612. * Deprecated, use CHROMIUM_VERSION instead.
  613. *
  614. * @static
  615. * @deprecated
  616. * @type {number|null}
  617. */
  618. let CHROME_VERSION = null;
  619. /**
  620. * The detected Internet Explorer version - or `null`.
  621. *
  622. * @static
  623. * @deprecated
  624. * @type {number|null}
  625. */
  626. let IE_VERSION = null;
  627. /**
  628. * Whether or not this is desktop Safari.
  629. *
  630. * @static
  631. * @type {Boolean}
  632. */
  633. let IS_SAFARI = false;
  634. /**
  635. * Whether or not this is a Windows machine.
  636. *
  637. * @static
  638. * @type {Boolean}
  639. */
  640. let IS_WINDOWS = false;
  641. /**
  642. * Whether or not this device is an iPad.
  643. *
  644. * @static
  645. * @type {Boolean}
  646. */
  647. let IS_IPAD = false;
  648. /**
  649. * Whether or not this device is an iPhone.
  650. *
  651. * @static
  652. * @type {Boolean}
  653. */
  654. // The Facebook app's UIWebView identifies as both an iPhone and iPad, so
  655. // to identify iPhones, we need to exclude iPads.
  656. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
  657. let IS_IPHONE = false;
  658. /**
  659. * Whether or not this device is touch-enabled.
  660. *
  661. * @static
  662. * @const
  663. * @type {Boolean}
  664. */
  665. const TOUCH_ENABLED = Boolean(isReal() && ('ontouchstart' in window || window.navigator.maxTouchPoints || window.DocumentTouch && window.document instanceof window.DocumentTouch));
  666. const UAD = window.navigator && window.navigator.userAgentData;
  667. if (UAD) {
  668. // If userAgentData is present, use it instead of userAgent to avoid warnings
  669. // Currently only implemented on Chromium
  670. // userAgentData does not expose Android version, so ANDROID_VERSION remains `null`
  671. IS_ANDROID = UAD.platform === 'Android';
  672. IS_EDGE = Boolean(UAD.brands.find(b => b.brand === 'Microsoft Edge'));
  673. IS_CHROMIUM = Boolean(UAD.brands.find(b => b.brand === 'Chromium'));
  674. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  675. CHROMIUM_VERSION = CHROME_VERSION = (UAD.brands.find(b => b.brand === 'Chromium') || {}).version || null;
  676. IS_WINDOWS = UAD.platform === 'Windows';
  677. }
  678. // If the browser is not Chromium, either userAgentData is not present which could be an old Chromium browser,
  679. // or it's a browser that has added userAgentData since that we don't have tests for yet. In either case,
  680. // the checks need to be made agiainst the regular userAgent string.
  681. if (!IS_CHROMIUM) {
  682. const USER_AGENT = window.navigator && window.navigator.userAgent || '';
  683. IS_IPOD = /iPod/i.test(USER_AGENT);
  684. IOS_VERSION = function () {
  685. const match = USER_AGENT.match(/OS (\d+)_/i);
  686. if (match && match[1]) {
  687. return match[1];
  688. }
  689. return null;
  690. }();
  691. IS_ANDROID = /Android/i.test(USER_AGENT);
  692. ANDROID_VERSION = function () {
  693. // This matches Android Major.Minor.Patch versions
  694. // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
  695. const match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
  696. if (!match) {
  697. return null;
  698. }
  699. const major = match[1] && parseFloat(match[1]);
  700. const minor = match[2] && parseFloat(match[2]);
  701. if (major && minor) {
  702. return parseFloat(match[1] + '.' + match[2]);
  703. } else if (major) {
  704. return major;
  705. }
  706. return null;
  707. }();
  708. IS_FIREFOX = /Firefox/i.test(USER_AGENT);
  709. IS_EDGE = /Edg/i.test(USER_AGENT);
  710. IS_CHROMIUM = /Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT);
  711. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  712. CHROMIUM_VERSION = CHROME_VERSION = function () {
  713. const match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
  714. if (match && match[2]) {
  715. return parseFloat(match[2]);
  716. }
  717. return null;
  718. }();
  719. IE_VERSION = function () {
  720. const result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT);
  721. let version = result && parseFloat(result[1]);
  722. if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) {
  723. // IE 11 has a different user agent string than other IE versions
  724. version = 11.0;
  725. }
  726. return version;
  727. }();
  728. IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE;
  729. IS_WINDOWS = /Windows/i.test(USER_AGENT);
  730. IS_IPAD = /iPad/i.test(USER_AGENT) || IS_SAFARI && TOUCH_ENABLED && !/iPhone/i.test(USER_AGENT);
  731. IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD;
  732. }
  733. /**
  734. * Whether or not this is an iOS device.
  735. *
  736. * @static
  737. * @const
  738. * @type {Boolean}
  739. */
  740. const IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
  741. /**
  742. * Whether or not this is any flavor of Safari - including iOS.
  743. *
  744. * @static
  745. * @const
  746. * @type {Boolean}
  747. */
  748. const IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;
  749. var browser = /*#__PURE__*/Object.freeze({
  750. __proto__: null,
  751. get IS_IPOD () { return IS_IPOD; },
  752. get IOS_VERSION () { return IOS_VERSION; },
  753. get IS_ANDROID () { return IS_ANDROID; },
  754. get ANDROID_VERSION () { return ANDROID_VERSION; },
  755. get IS_FIREFOX () { return IS_FIREFOX; },
  756. get IS_EDGE () { return IS_EDGE; },
  757. get IS_CHROMIUM () { return IS_CHROMIUM; },
  758. get IS_CHROME () { return IS_CHROME; },
  759. get CHROMIUM_VERSION () { return CHROMIUM_VERSION; },
  760. get CHROME_VERSION () { return CHROME_VERSION; },
  761. get IE_VERSION () { return IE_VERSION; },
  762. get IS_SAFARI () { return IS_SAFARI; },
  763. get IS_WINDOWS () { return IS_WINDOWS; },
  764. get IS_IPAD () { return IS_IPAD; },
  765. get IS_IPHONE () { return IS_IPHONE; },
  766. TOUCH_ENABLED: TOUCH_ENABLED,
  767. IS_IOS: IS_IOS,
  768. IS_ANY_SAFARI: IS_ANY_SAFARI
  769. });
  770. /**
  771. * @file dom.js
  772. * @module dom
  773. */
  774. /**
  775. * Detect if a value is a string with any non-whitespace characters.
  776. *
  777. * @private
  778. * @param {string} str
  779. * The string to check
  780. *
  781. * @return {boolean}
  782. * Will be `true` if the string is non-blank, `false` otherwise.
  783. *
  784. */
  785. function isNonBlankString(str) {
  786. // we use str.trim as it will trim any whitespace characters
  787. // from the front or back of non-whitespace characters. aka
  788. // Any string that contains non-whitespace characters will
  789. // still contain them after `trim` but whitespace only strings
  790. // will have a length of 0, failing this check.
  791. return typeof str === 'string' && Boolean(str.trim());
  792. }
  793. /**
  794. * Throws an error if the passed string has whitespace. This is used by
  795. * class methods to be relatively consistent with the classList API.
  796. *
  797. * @private
  798. * @param {string} str
  799. * The string to check for whitespace.
  800. *
  801. * @throws {Error}
  802. * Throws an error if there is whitespace in the string.
  803. */
  804. function throwIfWhitespace(str) {
  805. // str.indexOf instead of regex because str.indexOf is faster performance wise.
  806. if (str.indexOf(' ') >= 0) {
  807. throw new Error('class has illegal whitespace characters');
  808. }
  809. }
  810. /**
  811. * Whether the current DOM interface appears to be real (i.e. not simulated).
  812. *
  813. * @return {boolean}
  814. * Will be `true` if the DOM appears to be real, `false` otherwise.
  815. */
  816. function isReal() {
  817. // Both document and window will never be undefined thanks to `global`.
  818. return document === window.document;
  819. }
  820. /**
  821. * Determines, via duck typing, whether or not a value is a DOM element.
  822. *
  823. * @param {*} value
  824. * The value to check.
  825. *
  826. * @return {boolean}
  827. * Will be `true` if the value is a DOM element, `false` otherwise.
  828. */
  829. function isEl(value) {
  830. return isObject$1(value) && value.nodeType === 1;
  831. }
  832. /**
  833. * Determines if the current DOM is embedded in an iframe.
  834. *
  835. * @return {boolean}
  836. * Will be `true` if the DOM is embedded in an iframe, `false`
  837. * otherwise.
  838. */
  839. function isInFrame() {
  840. // We need a try/catch here because Safari will throw errors when attempting
  841. // to get either `parent` or `self`
  842. try {
  843. return window.parent !== window.self;
  844. } catch (x) {
  845. return true;
  846. }
  847. }
  848. /**
  849. * Creates functions to query the DOM using a given method.
  850. *
  851. * @private
  852. * @param {string} method
  853. * The method to create the query with.
  854. *
  855. * @return {Function}
  856. * The query method
  857. */
  858. function createQuerier(method) {
  859. return function (selector, context) {
  860. if (!isNonBlankString(selector)) {
  861. return document[method](null);
  862. }
  863. if (isNonBlankString(context)) {
  864. context = document.querySelector(context);
  865. }
  866. const ctx = isEl(context) ? context : document;
  867. return ctx[method] && ctx[method](selector);
  868. };
  869. }
  870. /**
  871. * Creates an element and applies properties, attributes, and inserts content.
  872. *
  873. * @param {string} [tagName='div']
  874. * Name of tag to be created.
  875. *
  876. * @param {Object} [properties={}]
  877. * Element properties to be applied.
  878. *
  879. * @param {Object} [attributes={}]
  880. * Element attributes to be applied.
  881. *
  882. * @param {ContentDescriptor} [content]
  883. * A content descriptor object.
  884. *
  885. * @return {Element}
  886. * The element that was created.
  887. */
  888. function createEl(tagName = 'div', properties = {}, attributes = {}, content) {
  889. const el = document.createElement(tagName);
  890. Object.getOwnPropertyNames(properties).forEach(function (propName) {
  891. const val = properties[propName];
  892. // Handle textContent since it's not supported everywhere and we have a
  893. // method for it.
  894. if (propName === 'textContent') {
  895. textContent(el, val);
  896. } else if (el[propName] !== val || propName === 'tabIndex') {
  897. el[propName] = val;
  898. }
  899. });
  900. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  901. el.setAttribute(attrName, attributes[attrName]);
  902. });
  903. if (content) {
  904. appendContent(el, content);
  905. }
  906. return el;
  907. }
  908. /**
  909. * Injects text into an element, replacing any existing contents entirely.
  910. *
  911. * @param {Element} el
  912. * The element to add text content into
  913. *
  914. * @param {string} text
  915. * The text content to add.
  916. *
  917. * @return {Element}
  918. * The element with added text content.
  919. */
  920. function textContent(el, text) {
  921. if (typeof el.textContent === 'undefined') {
  922. el.innerText = text;
  923. } else {
  924. el.textContent = text;
  925. }
  926. return el;
  927. }
  928. /**
  929. * Insert an element as the first child node of another
  930. *
  931. * @param {Element} child
  932. * Element to insert
  933. *
  934. * @param {Element} parent
  935. * Element to insert child into
  936. */
  937. function prependTo(child, parent) {
  938. if (parent.firstChild) {
  939. parent.insertBefore(child, parent.firstChild);
  940. } else {
  941. parent.appendChild(child);
  942. }
  943. }
  944. /**
  945. * Check if an element has a class name.
  946. *
  947. * @param {Element} element
  948. * Element to check
  949. *
  950. * @param {string} classToCheck
  951. * Class name to check for
  952. *
  953. * @return {boolean}
  954. * Will be `true` if the element has a class, `false` otherwise.
  955. *
  956. * @throws {Error}
  957. * Throws an error if `classToCheck` has white space.
  958. */
  959. function hasClass(element, classToCheck) {
  960. throwIfWhitespace(classToCheck);
  961. return element.classList.contains(classToCheck);
  962. }
  963. /**
  964. * Add a class name to an element.
  965. *
  966. * @param {Element} element
  967. * Element to add class name to.
  968. *
  969. * @param {...string} classesToAdd
  970. * One or more class name to add.
  971. *
  972. * @return {Element}
  973. * The DOM element with the added class name.
  974. */
  975. function addClass(element, ...classesToAdd) {
  976. element.classList.add(...classesToAdd.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  977. return element;
  978. }
  979. /**
  980. * Remove a class name from an element.
  981. *
  982. * @param {Element} element
  983. * Element to remove a class name from.
  984. *
  985. * @param {...string} classesToRemove
  986. * One or more class name to remove.
  987. *
  988. * @return {Element}
  989. * The DOM element with class name removed.
  990. */
  991. function removeClass(element, ...classesToRemove) {
  992. // Protect in case the player gets disposed
  993. if (!element) {
  994. log$1.warn("removeClass was called with an element that doesn't exist");
  995. return null;
  996. }
  997. element.classList.remove(...classesToRemove.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  998. return element;
  999. }
  1000. /**
  1001. * The callback definition for toggleClass.
  1002. *
  1003. * @callback module:dom~PredicateCallback
  1004. * @param {Element} element
  1005. * The DOM element of the Component.
  1006. *
  1007. * @param {string} classToToggle
  1008. * The `className` that wants to be toggled
  1009. *
  1010. * @return {boolean|undefined}
  1011. * If `true` is returned, the `classToToggle` will be added to the
  1012. * `element`. If `false`, the `classToToggle` will be removed from
  1013. * the `element`. If `undefined`, the callback will be ignored.
  1014. */
  1015. /**
  1016. * Adds or removes a class name to/from an element depending on an optional
  1017. * condition or the presence/absence of the class name.
  1018. *
  1019. * @param {Element} element
  1020. * The element to toggle a class name on.
  1021. *
  1022. * @param {string} classToToggle
  1023. * The class that should be toggled.
  1024. *
  1025. * @param {boolean|module:dom~PredicateCallback} [predicate]
  1026. * See the return value for {@link module:dom~PredicateCallback}
  1027. *
  1028. * @return {Element}
  1029. * The element with a class that has been toggled.
  1030. */
  1031. function toggleClass(element, classToToggle, predicate) {
  1032. if (typeof predicate === 'function') {
  1033. predicate = predicate(element, classToToggle);
  1034. }
  1035. if (typeof predicate !== 'boolean') {
  1036. predicate = undefined;
  1037. }
  1038. classToToggle.split(/\s+/).forEach(className => element.classList.toggle(className, predicate));
  1039. return element;
  1040. }
  1041. /**
  1042. * Apply attributes to an HTML element.
  1043. *
  1044. * @param {Element} el
  1045. * Element to add attributes to.
  1046. *
  1047. * @param {Object} [attributes]
  1048. * Attributes to be applied.
  1049. */
  1050. function setAttributes(el, attributes) {
  1051. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  1052. const attrValue = attributes[attrName];
  1053. if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
  1054. el.removeAttribute(attrName);
  1055. } else {
  1056. el.setAttribute(attrName, attrValue === true ? '' : attrValue);
  1057. }
  1058. });
  1059. }
  1060. /**
  1061. * Get an element's attribute values, as defined on the HTML tag.
  1062. *
  1063. * Attributes are not the same as properties. They're defined on the tag
  1064. * or with setAttribute.
  1065. *
  1066. * @param {Element} tag
  1067. * Element from which to get tag attributes.
  1068. *
  1069. * @return {Object}
  1070. * All attributes of the element. Boolean attributes will be `true` or
  1071. * `false`, others will be strings.
  1072. */
  1073. function getAttributes(tag) {
  1074. const obj = {};
  1075. // known boolean attributes
  1076. // we can check for matching boolean properties, but not all browsers
  1077. // and not all tags know about these attributes, so, we still want to check them manually
  1078. const knownBooleans = ',' + 'autoplay,controls,playsinline,loop,muted,default,defaultMuted' + ',';
  1079. if (tag && tag.attributes && tag.attributes.length > 0) {
  1080. const attrs = tag.attributes;
  1081. for (let i = attrs.length - 1; i >= 0; i--) {
  1082. const attrName = attrs[i].name;
  1083. let attrVal = attrs[i].value;
  1084. // check for known booleans
  1085. // the matching element property will return a value for typeof
  1086. if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) {
  1087. // the value of an included boolean attribute is typically an empty
  1088. // string ('') which would equal false if we just check for a false value.
  1089. // we also don't want support bad code like autoplay='false'
  1090. attrVal = attrVal !== null ? true : false;
  1091. }
  1092. obj[attrName] = attrVal;
  1093. }
  1094. }
  1095. return obj;
  1096. }
  1097. /**
  1098. * Get the value of an element's attribute.
  1099. *
  1100. * @param {Element} el
  1101. * A DOM element.
  1102. *
  1103. * @param {string} attribute
  1104. * Attribute to get the value of.
  1105. *
  1106. * @return {string}
  1107. * The value of the attribute.
  1108. */
  1109. function getAttribute(el, attribute) {
  1110. return el.getAttribute(attribute);
  1111. }
  1112. /**
  1113. * Set the value of an element's attribute.
  1114. *
  1115. * @param {Element} el
  1116. * A DOM element.
  1117. *
  1118. * @param {string} attribute
  1119. * Attribute to set.
  1120. *
  1121. * @param {string} value
  1122. * Value to set the attribute to.
  1123. */
  1124. function setAttribute(el, attribute, value) {
  1125. el.setAttribute(attribute, value);
  1126. }
  1127. /**
  1128. * Remove an element's attribute.
  1129. *
  1130. * @param {Element} el
  1131. * A DOM element.
  1132. *
  1133. * @param {string} attribute
  1134. * Attribute to remove.
  1135. */
  1136. function removeAttribute(el, attribute) {
  1137. el.removeAttribute(attribute);
  1138. }
  1139. /**
  1140. * Attempt to block the ability to select text.
  1141. */
  1142. function blockTextSelection() {
  1143. document.body.focus();
  1144. document.onselectstart = function () {
  1145. return false;
  1146. };
  1147. }
  1148. /**
  1149. * Turn off text selection blocking.
  1150. */
  1151. function unblockTextSelection() {
  1152. document.onselectstart = function () {
  1153. return true;
  1154. };
  1155. }
  1156. /**
  1157. * Identical to the native `getBoundingClientRect` function, but ensures that
  1158. * the method is supported at all (it is in all browsers we claim to support)
  1159. * and that the element is in the DOM before continuing.
  1160. *
  1161. * This wrapper function also shims properties which are not provided by some
  1162. * older browsers (namely, IE8).
  1163. *
  1164. * Additionally, some browsers do not support adding properties to a
  1165. * `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard
  1166. * properties (except `x` and `y` which are not widely supported). This helps
  1167. * avoid implementations where keys are non-enumerable.
  1168. *
  1169. * @param {Element} el
  1170. * Element whose `ClientRect` we want to calculate.
  1171. *
  1172. * @return {Object|undefined}
  1173. * Always returns a plain object - or `undefined` if it cannot.
  1174. */
  1175. function getBoundingClientRect(el) {
  1176. if (el && el.getBoundingClientRect && el.parentNode) {
  1177. const rect = el.getBoundingClientRect();
  1178. const result = {};
  1179. ['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(k => {
  1180. if (rect[k] !== undefined) {
  1181. result[k] = rect[k];
  1182. }
  1183. });
  1184. if (!result.height) {
  1185. result.height = parseFloat(computedStyle(el, 'height'));
  1186. }
  1187. if (!result.width) {
  1188. result.width = parseFloat(computedStyle(el, 'width'));
  1189. }
  1190. return result;
  1191. }
  1192. }
  1193. /**
  1194. * Represents the position of a DOM element on the page.
  1195. *
  1196. * @typedef {Object} module:dom~Position
  1197. *
  1198. * @property {number} left
  1199. * Pixels to the left.
  1200. *
  1201. * @property {number} top
  1202. * Pixels from the top.
  1203. */
  1204. /**
  1205. * Get the position of an element in the DOM.
  1206. *
  1207. * Uses `getBoundingClientRect` technique from John Resig.
  1208. *
  1209. * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/
  1210. *
  1211. * @param {Element} el
  1212. * Element from which to get offset.
  1213. *
  1214. * @return {module:dom~Position}
  1215. * The position of the element that was passed in.
  1216. */
  1217. function findPosition(el) {
  1218. if (!el || el && !el.offsetParent) {
  1219. return {
  1220. left: 0,
  1221. top: 0,
  1222. width: 0,
  1223. height: 0
  1224. };
  1225. }
  1226. const width = el.offsetWidth;
  1227. const height = el.offsetHeight;
  1228. let left = 0;
  1229. let top = 0;
  1230. while (el.offsetParent && el !== document[FullscreenApi.fullscreenElement]) {
  1231. left += el.offsetLeft;
  1232. top += el.offsetTop;
  1233. el = el.offsetParent;
  1234. }
  1235. return {
  1236. left,
  1237. top,
  1238. width,
  1239. height
  1240. };
  1241. }
  1242. /**
  1243. * Represents x and y coordinates for a DOM element or mouse pointer.
  1244. *
  1245. * @typedef {Object} module:dom~Coordinates
  1246. *
  1247. * @property {number} x
  1248. * x coordinate in pixels
  1249. *
  1250. * @property {number} y
  1251. * y coordinate in pixels
  1252. */
  1253. /**
  1254. * Get the pointer position within an element.
  1255. *
  1256. * The base on the coordinates are the bottom left of the element.
  1257. *
  1258. * @param {Element} el
  1259. * Element on which to get the pointer position on.
  1260. *
  1261. * @param {Event} event
  1262. * Event object.
  1263. *
  1264. * @return {module:dom~Coordinates}
  1265. * A coordinates object corresponding to the mouse position.
  1266. *
  1267. */
  1268. function getPointerPosition(el, event) {
  1269. const translated = {
  1270. x: 0,
  1271. y: 0
  1272. };
  1273. if (IS_IOS) {
  1274. let item = el;
  1275. while (item && item.nodeName.toLowerCase() !== 'html') {
  1276. const transform = computedStyle(item, 'transform');
  1277. if (/^matrix/.test(transform)) {
  1278. const values = transform.slice(7, -1).split(/,\s/).map(Number);
  1279. translated.x += values[4];
  1280. translated.y += values[5];
  1281. } else if (/^matrix3d/.test(transform)) {
  1282. const values = transform.slice(9, -1).split(/,\s/).map(Number);
  1283. translated.x += values[12];
  1284. translated.y += values[13];
  1285. }
  1286. item = item.parentNode;
  1287. }
  1288. }
  1289. const position = {};
  1290. const boxTarget = findPosition(event.target);
  1291. const box = findPosition(el);
  1292. const boxW = box.width;
  1293. const boxH = box.height;
  1294. let offsetY = event.offsetY - (box.top - boxTarget.top);
  1295. let offsetX = event.offsetX - (box.left - boxTarget.left);
  1296. if (event.changedTouches) {
  1297. offsetX = event.changedTouches[0].pageX - box.left;
  1298. offsetY = event.changedTouches[0].pageY + box.top;
  1299. if (IS_IOS) {
  1300. offsetX -= translated.x;
  1301. offsetY -= translated.y;
  1302. }
  1303. }
  1304. position.y = 1 - Math.max(0, Math.min(1, offsetY / boxH));
  1305. position.x = Math.max(0, Math.min(1, offsetX / boxW));
  1306. return position;
  1307. }
  1308. /**
  1309. * Determines, via duck typing, whether or not a value is a text node.
  1310. *
  1311. * @param {*} value
  1312. * Check if this value is a text node.
  1313. *
  1314. * @return {boolean}
  1315. * Will be `true` if the value is a text node, `false` otherwise.
  1316. */
  1317. function isTextNode$1(value) {
  1318. return isObject$1(value) && value.nodeType === 3;
  1319. }
  1320. /**
  1321. * Empties the contents of an element.
  1322. *
  1323. * @param {Element} el
  1324. * The element to empty children from
  1325. *
  1326. * @return {Element}
  1327. * The element with no children
  1328. */
  1329. function emptyEl(el) {
  1330. while (el.firstChild) {
  1331. el.removeChild(el.firstChild);
  1332. }
  1333. return el;
  1334. }
  1335. /**
  1336. * This is a mixed value that describes content to be injected into the DOM
  1337. * via some method. It can be of the following types:
  1338. *
  1339. * Type | Description
  1340. * -----------|-------------
  1341. * `string` | The value will be normalized into a text node.
  1342. * `Element` | The value will be accepted as-is.
  1343. * `Text` | A TextNode. The value will be accepted as-is.
  1344. * `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).
  1345. * `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.
  1346. *
  1347. * @typedef {string|Element|Text|Array|Function} ContentDescriptor
  1348. */
  1349. /**
  1350. * Normalizes content for eventual insertion into the DOM.
  1351. *
  1352. * This allows a wide range of content definition methods, but helps protect
  1353. * from falling into the trap of simply writing to `innerHTML`, which could
  1354. * be an XSS concern.
  1355. *
  1356. * The content for an element can be passed in multiple types and
  1357. * combinations, whose behavior is as follows:
  1358. *
  1359. * @param {ContentDescriptor} content
  1360. * A content descriptor value.
  1361. *
  1362. * @return {Array}
  1363. * All of the content that was passed in, normalized to an array of
  1364. * elements or text nodes.
  1365. */
  1366. function normalizeContent(content) {
  1367. // First, invoke content if it is a function. If it produces an array,
  1368. // that needs to happen before normalization.
  1369. if (typeof content === 'function') {
  1370. content = content();
  1371. }
  1372. // Next up, normalize to an array, so one or many items can be normalized,
  1373. // filtered, and returned.
  1374. return (Array.isArray(content) ? content : [content]).map(value => {
  1375. // First, invoke value if it is a function to produce a new value,
  1376. // which will be subsequently normalized to a Node of some kind.
  1377. if (typeof value === 'function') {
  1378. value = value();
  1379. }
  1380. if (isEl(value) || isTextNode$1(value)) {
  1381. return value;
  1382. }
  1383. if (typeof value === 'string' && /\S/.test(value)) {
  1384. return document.createTextNode(value);
  1385. }
  1386. }).filter(value => value);
  1387. }
  1388. /**
  1389. * Normalizes and appends content to an element.
  1390. *
  1391. * @param {Element} el
  1392. * Element to append normalized content to.
  1393. *
  1394. * @param {ContentDescriptor} content
  1395. * A content descriptor value.
  1396. *
  1397. * @return {Element}
  1398. * The element with appended normalized content.
  1399. */
  1400. function appendContent(el, content) {
  1401. normalizeContent(content).forEach(node => el.appendChild(node));
  1402. return el;
  1403. }
  1404. /**
  1405. * Normalizes and inserts content into an element; this is identical to
  1406. * `appendContent()`, except it empties the element first.
  1407. *
  1408. * @param {Element} el
  1409. * Element to insert normalized content into.
  1410. *
  1411. * @param {ContentDescriptor} content
  1412. * A content descriptor value.
  1413. *
  1414. * @return {Element}
  1415. * The element with inserted normalized content.
  1416. */
  1417. function insertContent(el, content) {
  1418. return appendContent(emptyEl(el), content);
  1419. }
  1420. /**
  1421. * Check if an event was a single left click.
  1422. *
  1423. * @param {Event} event
  1424. * Event object.
  1425. *
  1426. * @return {boolean}
  1427. * Will be `true` if a single left click, `false` otherwise.
  1428. */
  1429. function isSingleLeftClick(event) {
  1430. // Note: if you create something draggable, be sure to
  1431. // call it on both `mousedown` and `mousemove` event,
  1432. // otherwise `mousedown` should be enough for a button
  1433. if (event.button === undefined && event.buttons === undefined) {
  1434. // Why do we need `buttons` ?
  1435. // Because, middle mouse sometimes have this:
  1436. // e.button === 0 and e.buttons === 4
  1437. // Furthermore, we want to prevent combination click, something like
  1438. // HOLD middlemouse then left click, that would be
  1439. // e.button === 0, e.buttons === 5
  1440. // just `button` is not gonna work
  1441. // Alright, then what this block does ?
  1442. // this is for chrome `simulate mobile devices`
  1443. // I want to support this as well
  1444. return true;
  1445. }
  1446. if (event.button === 0 && event.buttons === undefined) {
  1447. // Touch screen, sometimes on some specific device, `buttons`
  1448. // doesn't have anything (safari on ios, blackberry...)
  1449. return true;
  1450. }
  1451. // `mouseup` event on a single left click has
  1452. // `button` and `buttons` equal to 0
  1453. if (event.type === 'mouseup' && event.button === 0 && event.buttons === 0) {
  1454. return true;
  1455. }
  1456. if (event.button !== 0 || event.buttons !== 1) {
  1457. // This is the reason we have those if else block above
  1458. // if any special case we can catch and let it slide
  1459. // we do it above, when get to here, this definitely
  1460. // is-not-left-click
  1461. return false;
  1462. }
  1463. return true;
  1464. }
  1465. /**
  1466. * Finds a single DOM element matching `selector` within the optional
  1467. * `context` of another DOM element (defaulting to `document`).
  1468. *
  1469. * @param {string} selector
  1470. * A valid CSS selector, which will be passed to `querySelector`.
  1471. *
  1472. * @param {Element|String} [context=document]
  1473. * A DOM element within which to query. Can also be a selector
  1474. * string in which case the first matching element will be used
  1475. * as context. If missing (or no element matches selector), falls
  1476. * back to `document`.
  1477. *
  1478. * @return {Element|null}
  1479. * The element that was found or null.
  1480. */
  1481. const $ = createQuerier('querySelector');
  1482. /**
  1483. * Finds a all DOM elements matching `selector` within the optional
  1484. * `context` of another DOM element (defaulting to `document`).
  1485. *
  1486. * @param {string} selector
  1487. * A valid CSS selector, which will be passed to `querySelectorAll`.
  1488. *
  1489. * @param {Element|String} [context=document]
  1490. * A DOM element within which to query. Can also be a selector
  1491. * string in which case the first matching element will be used
  1492. * as context. If missing (or no element matches selector), falls
  1493. * back to `document`.
  1494. *
  1495. * @return {NodeList}
  1496. * A element list of elements that were found. Will be empty if none
  1497. * were found.
  1498. *
  1499. */
  1500. const $$ = createQuerier('querySelectorAll');
  1501. /**
  1502. * A safe getComputedStyle.
  1503. *
  1504. * This is needed because in Firefox, if the player is loaded in an iframe with
  1505. * `display:none`, then `getComputedStyle` returns `null`, so, we do a
  1506. * null-check to make sure that the player doesn't break in these cases.
  1507. *
  1508. * @param {Element} el
  1509. * The element you want the computed style of
  1510. *
  1511. * @param {string} prop
  1512. * The property name you want
  1513. *
  1514. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  1515. */
  1516. function computedStyle(el, prop) {
  1517. if (!el || !prop) {
  1518. return '';
  1519. }
  1520. if (typeof window.getComputedStyle === 'function') {
  1521. let computedStyleValue;
  1522. try {
  1523. computedStyleValue = window.getComputedStyle(el);
  1524. } catch (e) {
  1525. return '';
  1526. }
  1527. return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : '';
  1528. }
  1529. return '';
  1530. }
  1531. var Dom = /*#__PURE__*/Object.freeze({
  1532. __proto__: null,
  1533. isReal: isReal,
  1534. isEl: isEl,
  1535. isInFrame: isInFrame,
  1536. createEl: createEl,
  1537. textContent: textContent,
  1538. prependTo: prependTo,
  1539. hasClass: hasClass,
  1540. addClass: addClass,
  1541. removeClass: removeClass,
  1542. toggleClass: toggleClass,
  1543. setAttributes: setAttributes,
  1544. getAttributes: getAttributes,
  1545. getAttribute: getAttribute,
  1546. setAttribute: setAttribute,
  1547. removeAttribute: removeAttribute,
  1548. blockTextSelection: blockTextSelection,
  1549. unblockTextSelection: unblockTextSelection,
  1550. getBoundingClientRect: getBoundingClientRect,
  1551. findPosition: findPosition,
  1552. getPointerPosition: getPointerPosition,
  1553. isTextNode: isTextNode$1,
  1554. emptyEl: emptyEl,
  1555. normalizeContent: normalizeContent,
  1556. appendContent: appendContent,
  1557. insertContent: insertContent,
  1558. isSingleLeftClick: isSingleLeftClick,
  1559. $: $,
  1560. $$: $$,
  1561. computedStyle: computedStyle
  1562. });
  1563. /**
  1564. * @file setup.js - Functions for setting up a player without
  1565. * user interaction based on the data-setup `attribute` of the video tag.
  1566. *
  1567. * @module setup
  1568. */
  1569. let _windowLoaded = false;
  1570. let videojs$1;
  1571. /**
  1572. * Set up any tags that have a data-setup `attribute` when the player is started.
  1573. */
  1574. const autoSetup = function () {
  1575. if (videojs$1.options.autoSetup === false) {
  1576. return;
  1577. }
  1578. const vids = Array.prototype.slice.call(document.getElementsByTagName('video'));
  1579. const audios = Array.prototype.slice.call(document.getElementsByTagName('audio'));
  1580. const divs = Array.prototype.slice.call(document.getElementsByTagName('video-js'));
  1581. const mediaEls = vids.concat(audios, divs);
  1582. // Check if any media elements exist
  1583. if (mediaEls && mediaEls.length > 0) {
  1584. for (let i = 0, e = mediaEls.length; i < e; i++) {
  1585. const mediaEl = mediaEls[i];
  1586. // Check if element exists, has getAttribute func.
  1587. if (mediaEl && mediaEl.getAttribute) {
  1588. // Make sure this player hasn't already been set up.
  1589. if (mediaEl.player === undefined) {
  1590. const options = mediaEl.getAttribute('data-setup');
  1591. // Check if data-setup attr exists.
  1592. // We only auto-setup if they've added the data-setup attr.
  1593. if (options !== null) {
  1594. // Create new video.js instance.
  1595. videojs$1(mediaEl);
  1596. }
  1597. }
  1598. // If getAttribute isn't defined, we need to wait for the DOM.
  1599. } else {
  1600. autoSetupTimeout(1);
  1601. break;
  1602. }
  1603. }
  1604. // No videos were found, so keep looping unless page is finished loading.
  1605. } else if (!_windowLoaded) {
  1606. autoSetupTimeout(1);
  1607. }
  1608. };
  1609. /**
  1610. * Wait until the page is loaded before running autoSetup. This will be called in
  1611. * autoSetup if `hasLoaded` returns false.
  1612. *
  1613. * @param {number} wait
  1614. * How long to wait in ms
  1615. *
  1616. * @param {module:videojs} [vjs]
  1617. * The videojs library function
  1618. */
  1619. function autoSetupTimeout(wait, vjs) {
  1620. // Protect against breakage in non-browser environments
  1621. if (!isReal()) {
  1622. return;
  1623. }
  1624. if (vjs) {
  1625. videojs$1 = vjs;
  1626. }
  1627. window.setTimeout(autoSetup, wait);
  1628. }
  1629. /**
  1630. * Used to set the internal tracking of window loaded state to true.
  1631. *
  1632. * @private
  1633. */
  1634. function setWindowLoaded() {
  1635. _windowLoaded = true;
  1636. window.removeEventListener('load', setWindowLoaded);
  1637. }
  1638. if (isReal()) {
  1639. if (document.readyState === 'complete') {
  1640. setWindowLoaded();
  1641. } else {
  1642. /**
  1643. * Listen for the load event on window, and set _windowLoaded to true.
  1644. *
  1645. * We use a standard event listener here to avoid incrementing the GUID
  1646. * before any players are created.
  1647. *
  1648. * @listens load
  1649. */
  1650. window.addEventListener('load', setWindowLoaded);
  1651. }
  1652. }
  1653. /**
  1654. * @file stylesheet.js
  1655. * @module stylesheet
  1656. */
  1657. /**
  1658. * Create a DOM style element given a className for it.
  1659. *
  1660. * @param {string} className
  1661. * The className to add to the created style element.
  1662. *
  1663. * @return {Element}
  1664. * The element that was created.
  1665. */
  1666. const createStyleElement = function (className) {
  1667. const style = document.createElement('style');
  1668. style.className = className;
  1669. return style;
  1670. };
  1671. /**
  1672. * Add text to a DOM element.
  1673. *
  1674. * @param {Element} el
  1675. * The Element to add text content to.
  1676. *
  1677. * @param {string} content
  1678. * The text to add to the element.
  1679. */
  1680. const setTextContent = function (el, content) {
  1681. if (el.styleSheet) {
  1682. el.styleSheet.cssText = content;
  1683. } else {
  1684. el.textContent = content;
  1685. }
  1686. };
  1687. /**
  1688. * @file dom-data.js
  1689. * @module dom-data
  1690. */
  1691. /**
  1692. * Element Data Store.
  1693. *
  1694. * Allows for binding data to an element without putting it directly on the
  1695. * element. Ex. Event listeners are stored here.
  1696. * (also from jsninja.com, slightly modified and updated for closure compiler)
  1697. *
  1698. * @type {Object}
  1699. * @private
  1700. */
  1701. var DomData = new WeakMap();
  1702. /**
  1703. * @file guid.js
  1704. * @module guid
  1705. */
  1706. // Default value for GUIDs. This allows us to reset the GUID counter in tests.
  1707. //
  1708. // The initial GUID is 3 because some users have come to rely on the first
  1709. // default player ID ending up as `vjs_video_3`.
  1710. //
  1711. // See: https://github.com/videojs/video.js/pull/6216
  1712. const _initialGuid = 3;
  1713. /**
  1714. * Unique ID for an element or function
  1715. *
  1716. * @type {Number}
  1717. */
  1718. let _guid = _initialGuid;
  1719. /**
  1720. * Get a unique auto-incrementing ID by number that has not been returned before.
  1721. *
  1722. * @return {number}
  1723. * A new unique ID.
  1724. */
  1725. function newGUID() {
  1726. return _guid++;
  1727. }
  1728. /**
  1729. * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
  1730. * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
  1731. * This should work very similarly to jQuery's events, however it's based off the book version which isn't as
  1732. * robust as jquery's, so there's probably some differences.
  1733. *
  1734. * @file events.js
  1735. * @module events
  1736. */
  1737. /**
  1738. * Clean up the listener cache and dispatchers
  1739. *
  1740. * @param {Element|Object} elem
  1741. * Element to clean up
  1742. *
  1743. * @param {string} type
  1744. * Type of event to clean up
  1745. */
  1746. function _cleanUpEvents(elem, type) {
  1747. if (!DomData.has(elem)) {
  1748. return;
  1749. }
  1750. const data = DomData.get(elem);
  1751. // Remove the events of a particular type if there are none left
  1752. if (data.handlers[type].length === 0) {
  1753. delete data.handlers[type];
  1754. // data.handlers[type] = null;
  1755. // Setting to null was causing an error with data.handlers
  1756. // Remove the meta-handler from the element
  1757. if (elem.removeEventListener) {
  1758. elem.removeEventListener(type, data.dispatcher, false);
  1759. } else if (elem.detachEvent) {
  1760. elem.detachEvent('on' + type, data.dispatcher);
  1761. }
  1762. }
  1763. // Remove the events object if there are no types left
  1764. if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
  1765. delete data.handlers;
  1766. delete data.dispatcher;
  1767. delete data.disabled;
  1768. }
  1769. // Finally remove the element data if there is no data left
  1770. if (Object.getOwnPropertyNames(data).length === 0) {
  1771. DomData.delete(elem);
  1772. }
  1773. }
  1774. /**
  1775. * Loops through an array of event types and calls the requested method for each type.
  1776. *
  1777. * @param {Function} fn
  1778. * The event method we want to use.
  1779. *
  1780. * @param {Element|Object} elem
  1781. * Element or object to bind listeners to
  1782. *
  1783. * @param {string} type
  1784. * Type of event to bind to.
  1785. *
  1786. * @param {Function} callback
  1787. * Event listener.
  1788. */
  1789. function _handleMultipleEvents(fn, elem, types, callback) {
  1790. types.forEach(function (type) {
  1791. // Call the event method for each one of the types
  1792. fn(elem, type, callback);
  1793. });
  1794. }
  1795. /**
  1796. * Fix a native event to have standard property values
  1797. *
  1798. * @param {Object} event
  1799. * Event object to fix.
  1800. *
  1801. * @return {Object}
  1802. * Fixed event object.
  1803. */
  1804. function fixEvent(event) {
  1805. if (event.fixed_) {
  1806. return event;
  1807. }
  1808. function returnTrue() {
  1809. return true;
  1810. }
  1811. function returnFalse() {
  1812. return false;
  1813. }
  1814. // Test if fixing up is needed
  1815. // Used to check if !event.stopPropagation instead of isPropagationStopped
  1816. // But native events return true for stopPropagation, but don't have
  1817. // other expected methods like isPropagationStopped. Seems to be a problem
  1818. // with the Javascript Ninja code. So we're just overriding all events now.
  1819. if (!event || !event.isPropagationStopped || !event.isImmediatePropagationStopped) {
  1820. const old = event || window.event;
  1821. event = {};
  1822. // Clone the old object so that we can modify the values event = {};
  1823. // IE8 Doesn't like when you mess with native event properties
  1824. // Firefox returns false for event.hasOwnProperty('type') and other props
  1825. // which makes copying more difficult.
  1826. // TODO: Probably best to create a whitelist of event props
  1827. for (const key in old) {
  1828. // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
  1829. // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
  1830. // and webkitMovementX/Y
  1831. // Lighthouse complains if Event.path is copied
  1832. if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY' && key !== 'path') {
  1833. // Chrome 32+ warns if you try to copy deprecated returnValue, but
  1834. // we still want to if preventDefault isn't supported (IE8).
  1835. if (!(key === 'returnValue' && old.preventDefault)) {
  1836. event[key] = old[key];
  1837. }
  1838. }
  1839. }
  1840. // The event occurred on this element
  1841. if (!event.target) {
  1842. event.target = event.srcElement || document;
  1843. }
  1844. // Handle which other element the event is related to
  1845. if (!event.relatedTarget) {
  1846. event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
  1847. }
  1848. // Stop the default browser action
  1849. event.preventDefault = function () {
  1850. if (old.preventDefault) {
  1851. old.preventDefault();
  1852. }
  1853. event.returnValue = false;
  1854. old.returnValue = false;
  1855. event.defaultPrevented = true;
  1856. };
  1857. event.defaultPrevented = false;
  1858. // Stop the event from bubbling
  1859. event.stopPropagation = function () {
  1860. if (old.stopPropagation) {
  1861. old.stopPropagation();
  1862. }
  1863. event.cancelBubble = true;
  1864. old.cancelBubble = true;
  1865. event.isPropagationStopped = returnTrue;
  1866. };
  1867. event.isPropagationStopped = returnFalse;
  1868. // Stop the event from bubbling and executing other handlers
  1869. event.stopImmediatePropagation = function () {
  1870. if (old.stopImmediatePropagation) {
  1871. old.stopImmediatePropagation();
  1872. }
  1873. event.isImmediatePropagationStopped = returnTrue;
  1874. event.stopPropagation();
  1875. };
  1876. event.isImmediatePropagationStopped = returnFalse;
  1877. // Handle mouse position
  1878. if (event.clientX !== null && event.clientX !== undefined) {
  1879. const doc = document.documentElement;
  1880. const body = document.body;
  1881. event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  1882. event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  1883. }
  1884. // Handle key presses
  1885. event.which = event.charCode || event.keyCode;
  1886. // Fix button for mouse clicks:
  1887. // 0 == left; 1 == middle; 2 == right
  1888. if (event.button !== null && event.button !== undefined) {
  1889. // The following is disabled because it does not pass videojs-standard
  1890. // and... yikes.
  1891. /* eslint-disable */
  1892. event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
  1893. /* eslint-enable */
  1894. }
  1895. }
  1896. event.fixed_ = true;
  1897. // Returns fixed-up instance
  1898. return event;
  1899. }
  1900. /**
  1901. * Whether passive event listeners are supported
  1902. */
  1903. let _supportsPassive;
  1904. const supportsPassive = function () {
  1905. if (typeof _supportsPassive !== 'boolean') {
  1906. _supportsPassive = false;
  1907. try {
  1908. const opts = Object.defineProperty({}, 'passive', {
  1909. get() {
  1910. _supportsPassive = true;
  1911. }
  1912. });
  1913. window.addEventListener('test', null, opts);
  1914. window.removeEventListener('test', null, opts);
  1915. } catch (e) {
  1916. // disregard
  1917. }
  1918. }
  1919. return _supportsPassive;
  1920. };
  1921. /**
  1922. * Touch events Chrome expects to be passive
  1923. */
  1924. const passiveEvents = ['touchstart', 'touchmove'];
  1925. /**
  1926. * Add an event listener to element
  1927. * It stores the handler function in a separate cache object
  1928. * and adds a generic handler to the element's event,
  1929. * along with a unique id (guid) to the element.
  1930. *
  1931. * @param {Element|Object} elem
  1932. * Element or object to bind listeners to
  1933. *
  1934. * @param {string|string[]} type
  1935. * Type of event to bind to.
  1936. *
  1937. * @param {Function} fn
  1938. * Event listener.
  1939. */
  1940. function on(elem, type, fn) {
  1941. if (Array.isArray(type)) {
  1942. return _handleMultipleEvents(on, elem, type, fn);
  1943. }
  1944. if (!DomData.has(elem)) {
  1945. DomData.set(elem, {});
  1946. }
  1947. const data = DomData.get(elem);
  1948. // We need a place to store all our handler data
  1949. if (!data.handlers) {
  1950. data.handlers = {};
  1951. }
  1952. if (!data.handlers[type]) {
  1953. data.handlers[type] = [];
  1954. }
  1955. if (!fn.guid) {
  1956. fn.guid = newGUID();
  1957. }
  1958. data.handlers[type].push(fn);
  1959. if (!data.dispatcher) {
  1960. data.disabled = false;
  1961. data.dispatcher = function (event, hash) {
  1962. if (data.disabled) {
  1963. return;
  1964. }
  1965. event = fixEvent(event);
  1966. const handlers = data.handlers[event.type];
  1967. if (handlers) {
  1968. // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
  1969. const handlersCopy = handlers.slice(0);
  1970. for (let m = 0, n = handlersCopy.length; m < n; m++) {
  1971. if (event.isImmediatePropagationStopped()) {
  1972. break;
  1973. } else {
  1974. try {
  1975. handlersCopy[m].call(elem, event, hash);
  1976. } catch (e) {
  1977. log$1.error(e);
  1978. }
  1979. }
  1980. }
  1981. }
  1982. };
  1983. }
  1984. if (data.handlers[type].length === 1) {
  1985. if (elem.addEventListener) {
  1986. let options = false;
  1987. if (supportsPassive() && passiveEvents.indexOf(type) > -1) {
  1988. options = {
  1989. passive: true
  1990. };
  1991. }
  1992. elem.addEventListener(type, data.dispatcher, options);
  1993. } else if (elem.attachEvent) {
  1994. elem.attachEvent('on' + type, data.dispatcher);
  1995. }
  1996. }
  1997. }
  1998. /**
  1999. * Removes event listeners from an element
  2000. *
  2001. * @param {Element|Object} elem
  2002. * Object to remove listeners from.
  2003. *
  2004. * @param {string|string[]} [type]
  2005. * Type of listener to remove. Don't include to remove all events from element.
  2006. *
  2007. * @param {Function} [fn]
  2008. * Specific listener to remove. Don't include to remove listeners for an event
  2009. * type.
  2010. */
  2011. function off(elem, type, fn) {
  2012. // Don't want to add a cache object through getElData if not needed
  2013. if (!DomData.has(elem)) {
  2014. return;
  2015. }
  2016. const data = DomData.get(elem);
  2017. // If no events exist, nothing to unbind
  2018. if (!data.handlers) {
  2019. return;
  2020. }
  2021. if (Array.isArray(type)) {
  2022. return _handleMultipleEvents(off, elem, type, fn);
  2023. }
  2024. // Utility function
  2025. const removeType = function (el, t) {
  2026. data.handlers[t] = [];
  2027. _cleanUpEvents(el, t);
  2028. };
  2029. // Are we removing all bound events?
  2030. if (type === undefined) {
  2031. for (const t in data.handlers) {
  2032. if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t)) {
  2033. removeType(elem, t);
  2034. }
  2035. }
  2036. return;
  2037. }
  2038. const handlers = data.handlers[type];
  2039. // If no handlers exist, nothing to unbind
  2040. if (!handlers) {
  2041. return;
  2042. }
  2043. // If no listener was provided, remove all listeners for type
  2044. if (!fn) {
  2045. removeType(elem, type);
  2046. return;
  2047. }
  2048. // We're only removing a single handler
  2049. if (fn.guid) {
  2050. for (let n = 0; n < handlers.length; n++) {
  2051. if (handlers[n].guid === fn.guid) {
  2052. handlers.splice(n--, 1);
  2053. }
  2054. }
  2055. }
  2056. _cleanUpEvents(elem, type);
  2057. }
  2058. /**
  2059. * Trigger an event for an element
  2060. *
  2061. * @param {Element|Object} elem
  2062. * Element to trigger an event on
  2063. *
  2064. * @param {EventTarget~Event|string} event
  2065. * A string (the type) or an event object with a type attribute
  2066. *
  2067. * @param {Object} [hash]
  2068. * data hash to pass along with the event
  2069. *
  2070. * @return {boolean|undefined}
  2071. * Returns the opposite of `defaultPrevented` if default was
  2072. * prevented. Otherwise, returns `undefined`
  2073. */
  2074. function trigger(elem, event, hash) {
  2075. // Fetches element data and a reference to the parent (for bubbling).
  2076. // Don't want to add a data object to cache for every parent,
  2077. // so checking hasElData first.
  2078. const elemData = DomData.has(elem) ? DomData.get(elem) : {};
  2079. const parent = elem.parentNode || elem.ownerDocument;
  2080. // type = event.type || event,
  2081. // handler;
  2082. // If an event name was passed as a string, creates an event out of it
  2083. if (typeof event === 'string') {
  2084. event = {
  2085. type: event,
  2086. target: elem
  2087. };
  2088. } else if (!event.target) {
  2089. event.target = elem;
  2090. }
  2091. // Normalizes the event properties.
  2092. event = fixEvent(event);
  2093. // If the passed element has a dispatcher, executes the established handlers.
  2094. if (elemData.dispatcher) {
  2095. elemData.dispatcher.call(elem, event, hash);
  2096. }
  2097. // Unless explicitly stopped or the event does not bubble (e.g. media events)
  2098. // recursively calls this function to bubble the event up the DOM.
  2099. if (parent && !event.isPropagationStopped() && event.bubbles === true) {
  2100. trigger.call(null, parent, event, hash);
  2101. // If at the top of the DOM, triggers the default action unless disabled.
  2102. } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) {
  2103. if (!DomData.has(event.target)) {
  2104. DomData.set(event.target, {});
  2105. }
  2106. const targetData = DomData.get(event.target);
  2107. // Checks if the target has a default action for this event.
  2108. if (event.target[event.type]) {
  2109. // Temporarily disables event dispatching on the target as we have already executed the handler.
  2110. targetData.disabled = true;
  2111. // Executes the default action.
  2112. if (typeof event.target[event.type] === 'function') {
  2113. event.target[event.type]();
  2114. }
  2115. // Re-enables event dispatching.
  2116. targetData.disabled = false;
  2117. }
  2118. }
  2119. // Inform the triggerer if the default was prevented by returning false
  2120. return !event.defaultPrevented;
  2121. }
  2122. /**
  2123. * Trigger a listener only once for an event.
  2124. *
  2125. * @param {Element|Object} elem
  2126. * Element or object to bind to.
  2127. *
  2128. * @param {string|string[]} type
  2129. * Name/type of event
  2130. *
  2131. * @param {Event~EventListener} fn
  2132. * Event listener function
  2133. */
  2134. function one(elem, type, fn) {
  2135. if (Array.isArray(type)) {
  2136. return _handleMultipleEvents(one, elem, type, fn);
  2137. }
  2138. const func = function () {
  2139. off(elem, type, func);
  2140. fn.apply(this, arguments);
  2141. };
  2142. // copy the guid to the new function so it can removed using the original function's ID
  2143. func.guid = fn.guid = fn.guid || newGUID();
  2144. on(elem, type, func);
  2145. }
  2146. /**
  2147. * Trigger a listener only once and then turn if off for all
  2148. * configured events
  2149. *
  2150. * @param {Element|Object} elem
  2151. * Element or object to bind to.
  2152. *
  2153. * @param {string|string[]} type
  2154. * Name/type of event
  2155. *
  2156. * @param {Event~EventListener} fn
  2157. * Event listener function
  2158. */
  2159. function any(elem, type, fn) {
  2160. const func = function () {
  2161. off(elem, type, func);
  2162. fn.apply(this, arguments);
  2163. };
  2164. // copy the guid to the new function so it can removed using the original function's ID
  2165. func.guid = fn.guid = fn.guid || newGUID();
  2166. // multiple ons, but one off for everything
  2167. on(elem, type, func);
  2168. }
  2169. var Events = /*#__PURE__*/Object.freeze({
  2170. __proto__: null,
  2171. fixEvent: fixEvent,
  2172. on: on,
  2173. off: off,
  2174. trigger: trigger,
  2175. one: one,
  2176. any: any
  2177. });
  2178. /**
  2179. * @file fn.js
  2180. * @module fn
  2181. */
  2182. const UPDATE_REFRESH_INTERVAL = 30;
  2183. /**
  2184. * A private, internal-only function for changing the context of a function.
  2185. *
  2186. * It also stores a unique id on the function so it can be easily removed from
  2187. * events.
  2188. *
  2189. * @private
  2190. * @function
  2191. * @param {*} context
  2192. * The object to bind as scope.
  2193. *
  2194. * @param {Function} fn
  2195. * The function to be bound to a scope.
  2196. *
  2197. * @param {number} [uid]
  2198. * An optional unique ID for the function to be set
  2199. *
  2200. * @return {Function}
  2201. * The new function that will be bound into the context given
  2202. */
  2203. const bind_ = function (context, fn, uid) {
  2204. // Make sure the function has a unique ID
  2205. if (!fn.guid) {
  2206. fn.guid = newGUID();
  2207. }
  2208. // Create the new function that changes the context
  2209. const bound = fn.bind(context);
  2210. // Allow for the ability to individualize this function
  2211. // Needed in the case where multiple objects might share the same prototype
  2212. // IF both items add an event listener with the same function, then you try to remove just one
  2213. // it will remove both because they both have the same guid.
  2214. // when using this, you need to use the bind method when you remove the listener as well.
  2215. // currently used in text tracks
  2216. bound.guid = uid ? uid + '_' + fn.guid : fn.guid;
  2217. return bound;
  2218. };
  2219. /**
  2220. * Wraps the given function, `fn`, with a new function that only invokes `fn`
  2221. * at most once per every `wait` milliseconds.
  2222. *
  2223. * @function
  2224. * @param {Function} fn
  2225. * The function to be throttled.
  2226. *
  2227. * @param {number} wait
  2228. * The number of milliseconds by which to throttle.
  2229. *
  2230. * @return {Function}
  2231. */
  2232. const throttle = function (fn, wait) {
  2233. let last = window.performance.now();
  2234. const throttled = function (...args) {
  2235. const now = window.performance.now();
  2236. if (now - last >= wait) {
  2237. fn(...args);
  2238. last = now;
  2239. }
  2240. };
  2241. return throttled;
  2242. };
  2243. /**
  2244. * Creates a debounced function that delays invoking `func` until after `wait`
  2245. * milliseconds have elapsed since the last time the debounced function was
  2246. * invoked.
  2247. *
  2248. * Inspired by lodash and underscore implementations.
  2249. *
  2250. * @function
  2251. * @param {Function} func
  2252. * The function to wrap with debounce behavior.
  2253. *
  2254. * @param {number} wait
  2255. * The number of milliseconds to wait after the last invocation.
  2256. *
  2257. * @param {boolean} [immediate]
  2258. * Whether or not to invoke the function immediately upon creation.
  2259. *
  2260. * @param {Object} [context=window]
  2261. * The "context" in which the debounced function should debounce. For
  2262. * example, if this function should be tied to a Video.js player,
  2263. * the player can be passed here. Alternatively, defaults to the
  2264. * global `window` object.
  2265. *
  2266. * @return {Function}
  2267. * A debounced function.
  2268. */
  2269. const debounce = function (func, wait, immediate, context = window) {
  2270. let timeout;
  2271. const cancel = () => {
  2272. context.clearTimeout(timeout);
  2273. timeout = null;
  2274. };
  2275. /* eslint-disable consistent-this */
  2276. const debounced = function () {
  2277. const self = this;
  2278. const args = arguments;
  2279. let later = function () {
  2280. timeout = null;
  2281. later = null;
  2282. if (!immediate) {
  2283. func.apply(self, args);
  2284. }
  2285. };
  2286. if (!timeout && immediate) {
  2287. func.apply(self, args);
  2288. }
  2289. context.clearTimeout(timeout);
  2290. timeout = context.setTimeout(later, wait);
  2291. };
  2292. /* eslint-enable consistent-this */
  2293. debounced.cancel = cancel;
  2294. return debounced;
  2295. };
  2296. var Fn = /*#__PURE__*/Object.freeze({
  2297. __proto__: null,
  2298. UPDATE_REFRESH_INTERVAL: UPDATE_REFRESH_INTERVAL,
  2299. bind_: bind_,
  2300. throttle: throttle,
  2301. debounce: debounce
  2302. });
  2303. /**
  2304. * @file src/js/event-target.js
  2305. */
  2306. let EVENT_MAP;
  2307. /**
  2308. * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It
  2309. * adds shorthand functions that wrap around lengthy functions. For example:
  2310. * the `on` function is a wrapper around `addEventListener`.
  2311. *
  2312. * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget}
  2313. * @class EventTarget
  2314. */
  2315. class EventTarget$2 {
  2316. /**
  2317. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  2318. * function that will get called when an event with a certain name gets triggered.
  2319. *
  2320. * @param {string|string[]} type
  2321. * An event name or an array of event names.
  2322. *
  2323. * @param {Function} fn
  2324. * The function to call with `EventTarget`s
  2325. */
  2326. on(type, fn) {
  2327. // Remove the addEventListener alias before calling Events.on
  2328. // so we don't get into an infinite type loop
  2329. const ael = this.addEventListener;
  2330. this.addEventListener = () => {};
  2331. on(this, type, fn);
  2332. this.addEventListener = ael;
  2333. }
  2334. /**
  2335. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  2336. * This makes it so that the `event listener` will no longer get called when the
  2337. * named event happens.
  2338. *
  2339. * @param {string|string[]} type
  2340. * An event name or an array of event names.
  2341. *
  2342. * @param {Function} fn
  2343. * The function to remove.
  2344. */
  2345. off(type, fn) {
  2346. off(this, type, fn);
  2347. }
  2348. /**
  2349. * This function will add an `event listener` that gets triggered only once. After the
  2350. * first trigger it will get removed. This is like adding an `event listener`
  2351. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  2352. *
  2353. * @param {string|string[]} type
  2354. * An event name or an array of event names.
  2355. *
  2356. * @param {Function} fn
  2357. * The function to be called once for each event name.
  2358. */
  2359. one(type, fn) {
  2360. // Remove the addEventListener aliasing Events.on
  2361. // so we don't get into an infinite type loop
  2362. const ael = this.addEventListener;
  2363. this.addEventListener = () => {};
  2364. one(this, type, fn);
  2365. this.addEventListener = ael;
  2366. }
  2367. /**
  2368. * This function will add an `event listener` that gets triggered only once and is
  2369. * removed from all events. This is like adding an array of `event listener`s
  2370. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  2371. * first time it is triggered.
  2372. *
  2373. * @param {string|string[]} type
  2374. * An event name or an array of event names.
  2375. *
  2376. * @param {Function} fn
  2377. * The function to be called once for each event name.
  2378. */
  2379. any(type, fn) {
  2380. // Remove the addEventListener aliasing Events.on
  2381. // so we don't get into an infinite type loop
  2382. const ael = this.addEventListener;
  2383. this.addEventListener = () => {};
  2384. any(this, type, fn);
  2385. this.addEventListener = ael;
  2386. }
  2387. /**
  2388. * This function causes an event to happen. This will then cause any `event listeners`
  2389. * that are waiting for that event, to get called. If there are no `event listeners`
  2390. * for an event then nothing will happen.
  2391. *
  2392. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  2393. * Trigger will also call the `on` + `uppercaseEventName` function.
  2394. *
  2395. * Example:
  2396. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  2397. * `onClick` if it exists.
  2398. *
  2399. * @param {string|EventTarget~Event|Object} event
  2400. * The name of the event, an `Event`, or an object with a key of type set to
  2401. * an event name.
  2402. */
  2403. trigger(event) {
  2404. const type = event.type || event;
  2405. // deprecation
  2406. // In a future version we should default target to `this`
  2407. // similar to how we default the target to `elem` in
  2408. // `Events.trigger`. Right now the default `target` will be
  2409. // `document` due to the `Event.fixEvent` call.
  2410. if (typeof event === 'string') {
  2411. event = {
  2412. type
  2413. };
  2414. }
  2415. event = fixEvent(event);
  2416. if (this.allowedEvents_[type] && this['on' + type]) {
  2417. this['on' + type](event);
  2418. }
  2419. trigger(this, event);
  2420. }
  2421. queueTrigger(event) {
  2422. // only set up EVENT_MAP if it'll be used
  2423. if (!EVENT_MAP) {
  2424. EVENT_MAP = new Map();
  2425. }
  2426. const type = event.type || event;
  2427. let map = EVENT_MAP.get(this);
  2428. if (!map) {
  2429. map = new Map();
  2430. EVENT_MAP.set(this, map);
  2431. }
  2432. const oldTimeout = map.get(type);
  2433. map.delete(type);
  2434. window.clearTimeout(oldTimeout);
  2435. const timeout = window.setTimeout(() => {
  2436. map.delete(type);
  2437. // if we cleared out all timeouts for the current target, delete its map
  2438. if (map.size === 0) {
  2439. map = null;
  2440. EVENT_MAP.delete(this);
  2441. }
  2442. this.trigger(event);
  2443. }, 0);
  2444. map.set(type, timeout);
  2445. }
  2446. }
  2447. /**
  2448. * A Custom DOM event.
  2449. *
  2450. * @typedef {CustomEvent} Event
  2451. * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent}
  2452. */
  2453. /**
  2454. * All event listeners should follow the following format.
  2455. *
  2456. * @callback EventTarget~EventListener
  2457. * @this {EventTarget}
  2458. *
  2459. * @param {Event} event
  2460. * the event that triggered this function
  2461. *
  2462. * @param {Object} [hash]
  2463. * hash of data sent during the event
  2464. */
  2465. /**
  2466. * An object containing event names as keys and booleans as values.
  2467. *
  2468. * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger}
  2469. * will have extra functionality. See that function for more information.
  2470. *
  2471. * @property EventTarget.prototype.allowedEvents_
  2472. * @private
  2473. */
  2474. EventTarget$2.prototype.allowedEvents_ = {};
  2475. /**
  2476. * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic
  2477. * the standard DOM API.
  2478. *
  2479. * @function
  2480. * @see {@link EventTarget#on}
  2481. */
  2482. EventTarget$2.prototype.addEventListener = EventTarget$2.prototype.on;
  2483. /**
  2484. * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic
  2485. * the standard DOM API.
  2486. *
  2487. * @function
  2488. * @see {@link EventTarget#off}
  2489. */
  2490. EventTarget$2.prototype.removeEventListener = EventTarget$2.prototype.off;
  2491. /**
  2492. * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic
  2493. * the standard DOM API.
  2494. *
  2495. * @function
  2496. * @see {@link EventTarget#trigger}
  2497. */
  2498. EventTarget$2.prototype.dispatchEvent = EventTarget$2.prototype.trigger;
  2499. /**
  2500. * @file mixins/evented.js
  2501. * @module evented
  2502. */
  2503. const objName = obj => {
  2504. if (typeof obj.name === 'function') {
  2505. return obj.name();
  2506. }
  2507. if (typeof obj.name === 'string') {
  2508. return obj.name;
  2509. }
  2510. if (obj.name_) {
  2511. return obj.name_;
  2512. }
  2513. if (obj.constructor && obj.constructor.name) {
  2514. return obj.constructor.name;
  2515. }
  2516. return typeof obj;
  2517. };
  2518. /**
  2519. * Returns whether or not an object has had the evented mixin applied.
  2520. *
  2521. * @param {Object} object
  2522. * An object to test.
  2523. *
  2524. * @return {boolean}
  2525. * Whether or not the object appears to be evented.
  2526. */
  2527. const isEvented = object => object instanceof EventTarget$2 || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(k => typeof object[k] === 'function');
  2528. /**
  2529. * Adds a callback to run after the evented mixin applied.
  2530. *
  2531. * @param {Object} object
  2532. * An object to Add
  2533. * @param {Function} callback
  2534. * The callback to run.
  2535. */
  2536. const addEventedCallback = (target, callback) => {
  2537. if (isEvented(target)) {
  2538. callback();
  2539. } else {
  2540. if (!target.eventedCallbacks) {
  2541. target.eventedCallbacks = [];
  2542. }
  2543. target.eventedCallbacks.push(callback);
  2544. }
  2545. };
  2546. /**
  2547. * Whether a value is a valid event type - non-empty string or array.
  2548. *
  2549. * @private
  2550. * @param {string|Array} type
  2551. * The type value to test.
  2552. *
  2553. * @return {boolean}
  2554. * Whether or not the type is a valid event type.
  2555. */
  2556. const isValidEventType = type =>
  2557. // The regex here verifies that the `type` contains at least one non-
  2558. // whitespace character.
  2559. typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length;
  2560. /**
  2561. * Validates a value to determine if it is a valid event target. Throws if not.
  2562. *
  2563. * @private
  2564. * @throws {Error}
  2565. * If the target does not appear to be a valid event target.
  2566. *
  2567. * @param {Object} target
  2568. * The object to test.
  2569. *
  2570. * @param {Object} obj
  2571. * The evented object we are validating for
  2572. *
  2573. * @param {string} fnName
  2574. * The name of the evented mixin function that called this.
  2575. */
  2576. const validateTarget = (target, obj, fnName) => {
  2577. if (!target || !target.nodeName && !isEvented(target)) {
  2578. throw new Error(`Invalid target for ${objName(obj)}#${fnName}; must be a DOM node or evented object.`);
  2579. }
  2580. };
  2581. /**
  2582. * Validates a value to determine if it is a valid event target. Throws if not.
  2583. *
  2584. * @private
  2585. * @throws {Error}
  2586. * If the type does not appear to be a valid event type.
  2587. *
  2588. * @param {string|Array} type
  2589. * The type to test.
  2590. *
  2591. * @param {Object} obj
  2592. * The evented object we are validating for
  2593. *
  2594. * @param {string} fnName
  2595. * The name of the evented mixin function that called this.
  2596. */
  2597. const validateEventType = (type, obj, fnName) => {
  2598. if (!isValidEventType(type)) {
  2599. throw new Error(`Invalid event type for ${objName(obj)}#${fnName}; must be a non-empty string or array.`);
  2600. }
  2601. };
  2602. /**
  2603. * Validates a value to determine if it is a valid listener. Throws if not.
  2604. *
  2605. * @private
  2606. * @throws {Error}
  2607. * If the listener is not a function.
  2608. *
  2609. * @param {Function} listener
  2610. * The listener to test.
  2611. *
  2612. * @param {Object} obj
  2613. * The evented object we are validating for
  2614. *
  2615. * @param {string} fnName
  2616. * The name of the evented mixin function that called this.
  2617. */
  2618. const validateListener = (listener, obj, fnName) => {
  2619. if (typeof listener !== 'function') {
  2620. throw new Error(`Invalid listener for ${objName(obj)}#${fnName}; must be a function.`);
  2621. }
  2622. };
  2623. /**
  2624. * Takes an array of arguments given to `on()` or `one()`, validates them, and
  2625. * normalizes them into an object.
  2626. *
  2627. * @private
  2628. * @param {Object} self
  2629. * The evented object on which `on()` or `one()` was called. This
  2630. * object will be bound as the `this` value for the listener.
  2631. *
  2632. * @param {Array} args
  2633. * An array of arguments passed to `on()` or `one()`.
  2634. *
  2635. * @param {string} fnName
  2636. * The name of the evented mixin function that called this.
  2637. *
  2638. * @return {Object}
  2639. * An object containing useful values for `on()` or `one()` calls.
  2640. */
  2641. const normalizeListenArgs = (self, args, fnName) => {
  2642. // If the number of arguments is less than 3, the target is always the
  2643. // evented object itself.
  2644. const isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_;
  2645. let target;
  2646. let type;
  2647. let listener;
  2648. if (isTargetingSelf) {
  2649. target = self.eventBusEl_;
  2650. // 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, listener] = args;
  2656. } else {
  2657. [target, type, listener] = args;
  2658. }
  2659. validateTarget(target, self, fnName);
  2660. validateEventType(type, self, fnName);
  2661. validateListener(listener, self, fnName);
  2662. listener = bind_(self, listener);
  2663. return {
  2664. isTargetingSelf,
  2665. target,
  2666. type,
  2667. listener
  2668. };
  2669. };
  2670. /**
  2671. * Adds the listener to the event type(s) on the target, normalizing for
  2672. * the type of target.
  2673. *
  2674. * @private
  2675. * @param {Element|Object} target
  2676. * A DOM node or evented object.
  2677. *
  2678. * @param {string} method
  2679. * The event binding method to use ("on" or "one").
  2680. *
  2681. * @param {string|Array} type
  2682. * One or more event type(s).
  2683. *
  2684. * @param {Function} listener
  2685. * A listener function.
  2686. */
  2687. const listen = (target, method, type, listener) => {
  2688. validateTarget(target, target, method);
  2689. if (target.nodeName) {
  2690. Events[method](target, type, listener);
  2691. } else {
  2692. target[method](type, listener);
  2693. }
  2694. };
  2695. /**
  2696. * Contains methods that provide event capabilities to an object which is passed
  2697. * to {@link module:evented|evented}.
  2698. *
  2699. * @mixin EventedMixin
  2700. */
  2701. const EventedMixin = {
  2702. /**
  2703. * Add a listener to an event (or events) on this object or another evented
  2704. * object.
  2705. *
  2706. * @param {string|Array|Element|Object} targetOrType
  2707. * If this is a string or array, it represents the event type(s)
  2708. * that will trigger the listener.
  2709. *
  2710. * Another evented object can be passed here instead, which will
  2711. * cause the listener to listen for events on _that_ object.
  2712. *
  2713. * In either case, the listener's `this` value will be bound to
  2714. * this object.
  2715. *
  2716. * @param {string|Array|Function} typeOrListener
  2717. * If the first argument was a string or array, this should be the
  2718. * listener function. Otherwise, this is a string or array of event
  2719. * type(s).
  2720. *
  2721. * @param {Function} [listener]
  2722. * If the first argument was another evented object, this will be
  2723. * the listener function.
  2724. */
  2725. on(...args) {
  2726. const {
  2727. isTargetingSelf,
  2728. target,
  2729. type,
  2730. listener
  2731. } = normalizeListenArgs(this, args, 'on');
  2732. listen(target, 'on', type, listener);
  2733. // If this object is listening to another evented object.
  2734. if (!isTargetingSelf) {
  2735. // If this object is disposed, remove the listener.
  2736. const removeListenerOnDispose = () => this.off(target, type, listener);
  2737. // Use the same function ID as the listener so we can remove it later it
  2738. // using the ID of the original listener.
  2739. removeListenerOnDispose.guid = listener.guid;
  2740. // Add a listener to the target's dispose event as well. This ensures
  2741. // that if the target is disposed BEFORE this object, we remove the
  2742. // removal listener that was just added. Otherwise, we create a memory leak.
  2743. const removeRemoverOnTargetDispose = () => this.off('dispose', removeListenerOnDispose);
  2744. // Use the same function ID as the listener so we can remove it later
  2745. // it using the ID of the original listener.
  2746. removeRemoverOnTargetDispose.guid = listener.guid;
  2747. listen(this, 'on', 'dispose', removeListenerOnDispose);
  2748. listen(target, 'on', 'dispose', removeRemoverOnTargetDispose);
  2749. }
  2750. },
  2751. /**
  2752. * Add a listener to an event (or events) on this object or another evented
  2753. * object. The listener will be called once per event and then removed.
  2754. *
  2755. * @param {string|Array|Element|Object} targetOrType
  2756. * If this is a string or array, it represents the event type(s)
  2757. * that will trigger the listener.
  2758. *
  2759. * Another evented object can be passed here instead, which will
  2760. * cause the listener to listen for events on _that_ object.
  2761. *
  2762. * In either case, the listener's `this` value will be bound to
  2763. * this object.
  2764. *
  2765. * @param {string|Array|Function} typeOrListener
  2766. * If the first argument was a string or array, this should be the
  2767. * listener function. Otherwise, this is a string or array of event
  2768. * type(s).
  2769. *
  2770. * @param {Function} [listener]
  2771. * If the first argument was another evented object, this will be
  2772. * the listener function.
  2773. */
  2774. one(...args) {
  2775. const {
  2776. isTargetingSelf,
  2777. target,
  2778. type,
  2779. listener
  2780. } = normalizeListenArgs(this, args, 'one');
  2781. // Targeting this evented object.
  2782. if (isTargetingSelf) {
  2783. listen(target, 'one', type, listener);
  2784. // Targeting another evented object.
  2785. } else {
  2786. // TODO: This wrapper is incorrect! It should only
  2787. // remove the wrapper for the event type that called it.
  2788. // Instead all listeners are removed on the first trigger!
  2789. // see https://github.com/videojs/video.js/issues/5962
  2790. const wrapper = (...largs) => {
  2791. this.off(target, type, wrapper);
  2792. listener.apply(null, largs);
  2793. };
  2794. // Use the same function ID as the listener so we can remove it later
  2795. // it using the ID of the original listener.
  2796. wrapper.guid = listener.guid;
  2797. listen(target, 'one', type, wrapper);
  2798. }
  2799. },
  2800. /**
  2801. * Add a listener to an event (or events) on this object or another evented
  2802. * object. The listener will only be called once for the first event that is triggered
  2803. * then removed.
  2804. *
  2805. * @param {string|Array|Element|Object} targetOrType
  2806. * If this is a string or array, it represents the event type(s)
  2807. * that will trigger the listener.
  2808. *
  2809. * Another evented object can be passed here instead, which will
  2810. * cause the listener to listen for events on _that_ object.
  2811. *
  2812. * In either case, the listener's `this` value will be bound to
  2813. * this object.
  2814. *
  2815. * @param {string|Array|Function} typeOrListener
  2816. * If the first argument was a string or array, this should be the
  2817. * listener function. Otherwise, this is a string or array of event
  2818. * type(s).
  2819. *
  2820. * @param {Function} [listener]
  2821. * If the first argument was another evented object, this will be
  2822. * the listener function.
  2823. */
  2824. any(...args) {
  2825. const {
  2826. isTargetingSelf,
  2827. target,
  2828. type,
  2829. listener
  2830. } = normalizeListenArgs(this, args, 'any');
  2831. // Targeting this evented object.
  2832. if (isTargetingSelf) {
  2833. listen(target, 'any', type, listener);
  2834. // Targeting another evented object.
  2835. } else {
  2836. const wrapper = (...largs) => {
  2837. this.off(target, type, wrapper);
  2838. listener.apply(null, largs);
  2839. };
  2840. // Use the same function ID as the listener so we can remove it later
  2841. // it using the ID of the original listener.
  2842. wrapper.guid = listener.guid;
  2843. listen(target, 'any', type, wrapper);
  2844. }
  2845. },
  2846. /**
  2847. * Removes listener(s) from event(s) on an evented object.
  2848. *
  2849. * @param {string|Array|Element|Object} [targetOrType]
  2850. * If this is a string or array, it represents the event type(s).
  2851. *
  2852. * Another evented object can be passed here instead, in which case
  2853. * ALL 3 arguments are _required_.
  2854. *
  2855. * @param {string|Array|Function} [typeOrListener]
  2856. * If the first argument was a string or array, this may be the
  2857. * listener function. Otherwise, this is a string or array of event
  2858. * type(s).
  2859. *
  2860. * @param {Function} [listener]
  2861. * If the first argument was another evented object, this will be
  2862. * the listener function; otherwise, _all_ listeners bound to the
  2863. * event type(s) will be removed.
  2864. */
  2865. off(targetOrType, typeOrListener, listener) {
  2866. // Targeting this evented object.
  2867. if (!targetOrType || isValidEventType(targetOrType)) {
  2868. off(this.eventBusEl_, targetOrType, typeOrListener);
  2869. // Targeting another evented object.
  2870. } else {
  2871. const target = targetOrType;
  2872. const type = typeOrListener;
  2873. // Fail fast and in a meaningful way!
  2874. validateTarget(target, this, 'off');
  2875. validateEventType(type, this, 'off');
  2876. validateListener(listener, this, 'off');
  2877. // Ensure there's at least a guid, even if the function hasn't been used
  2878. listener = bind_(this, listener);
  2879. // Remove the dispose listener on this evented object, which was given
  2880. // the same guid as the event listener in on().
  2881. this.off('dispose', listener);
  2882. if (target.nodeName) {
  2883. off(target, type, listener);
  2884. off(target, 'dispose', listener);
  2885. } else if (isEvented(target)) {
  2886. target.off(type, listener);
  2887. target.off('dispose', listener);
  2888. }
  2889. }
  2890. },
  2891. /**
  2892. * Fire an event on this evented object, causing its listeners to be called.
  2893. *
  2894. * @param {string|Object} event
  2895. * An event type or an object with a type property.
  2896. *
  2897. * @param {Object} [hash]
  2898. * An additional object to pass along to listeners.
  2899. *
  2900. * @return {boolean}
  2901. * Whether or not the default behavior was prevented.
  2902. */
  2903. trigger(event, hash) {
  2904. validateTarget(this.eventBusEl_, this, 'trigger');
  2905. const type = event && typeof event !== 'string' ? event.type : event;
  2906. if (!isValidEventType(type)) {
  2907. throw new 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.');
  2908. }
  2909. return trigger(this.eventBusEl_, event, hash);
  2910. }
  2911. };
  2912. /**
  2913. * Applies {@link module:evented~EventedMixin|EventedMixin} to a target object.
  2914. *
  2915. * @param {Object} target
  2916. * The object to which to add event methods.
  2917. *
  2918. * @param {Object} [options={}]
  2919. * Options for customizing the mixin behavior.
  2920. *
  2921. * @param {string} [options.eventBusKey]
  2922. * By default, adds a `eventBusEl_` DOM element to the target object,
  2923. * which is used as an event bus. If the target object already has a
  2924. * DOM element that should be used, pass its key here.
  2925. *
  2926. * @return {Object}
  2927. * The target object.
  2928. */
  2929. function evented(target, options = {}) {
  2930. const {
  2931. eventBusKey
  2932. } = options;
  2933. // Set or create the eventBusEl_.
  2934. if (eventBusKey) {
  2935. if (!target[eventBusKey].nodeName) {
  2936. throw new Error(`The eventBusKey "${eventBusKey}" does not refer to an element.`);
  2937. }
  2938. target.eventBusEl_ = target[eventBusKey];
  2939. } else {
  2940. target.eventBusEl_ = createEl('span', {
  2941. className: 'vjs-event-bus'
  2942. });
  2943. }
  2944. Object.assign(target, EventedMixin);
  2945. if (target.eventedCallbacks) {
  2946. target.eventedCallbacks.forEach(callback => {
  2947. callback();
  2948. });
  2949. }
  2950. // When any evented object is disposed, it removes all its listeners.
  2951. target.on('dispose', () => {
  2952. target.off();
  2953. [target, target.el_, target.eventBusEl_].forEach(function (val) {
  2954. if (val && DomData.has(val)) {
  2955. DomData.delete(val);
  2956. }
  2957. });
  2958. window.setTimeout(() => {
  2959. target.eventBusEl_ = null;
  2960. }, 0);
  2961. });
  2962. return target;
  2963. }
  2964. /**
  2965. * @file mixins/stateful.js
  2966. * @module stateful
  2967. */
  2968. /**
  2969. * Contains methods that provide statefulness to an object which is passed
  2970. * to {@link module:stateful}.
  2971. *
  2972. * @mixin StatefulMixin
  2973. */
  2974. const StatefulMixin = {
  2975. /**
  2976. * A hash containing arbitrary keys and values representing the state of
  2977. * the object.
  2978. *
  2979. * @type {Object}
  2980. */
  2981. state: {},
  2982. /**
  2983. * Set the state of an object by mutating its
  2984. * {@link module:stateful~StatefulMixin.state|state} object in place.
  2985. *
  2986. * @fires module:stateful~StatefulMixin#statechanged
  2987. * @param {Object|Function} stateUpdates
  2988. * A new set of properties to shallow-merge into the plugin state.
  2989. * Can be a plain object or a function returning a plain object.
  2990. *
  2991. * @return {Object|undefined}
  2992. * An object containing changes that occurred. If no changes
  2993. * occurred, returns `undefined`.
  2994. */
  2995. setState(stateUpdates) {
  2996. // Support providing the `stateUpdates` state as a function.
  2997. if (typeof stateUpdates === 'function') {
  2998. stateUpdates = stateUpdates();
  2999. }
  3000. let changes;
  3001. each(stateUpdates, (value, key) => {
  3002. // Record the change if the value is different from what's in the
  3003. // current state.
  3004. if (this.state[key] !== value) {
  3005. changes = changes || {};
  3006. changes[key] = {
  3007. from: this.state[key],
  3008. to: value
  3009. };
  3010. }
  3011. this.state[key] = value;
  3012. });
  3013. // Only trigger "statechange" if there were changes AND we have a trigger
  3014. // function. This allows us to not require that the target object be an
  3015. // evented object.
  3016. if (changes && isEvented(this)) {
  3017. /**
  3018. * An event triggered on an object that is both
  3019. * {@link module:stateful|stateful} and {@link module:evented|evented}
  3020. * indicating that its state has changed.
  3021. *
  3022. * @event module:stateful~StatefulMixin#statechanged
  3023. * @type {Object}
  3024. * @property {Object} changes
  3025. * A hash containing the properties that were changed and
  3026. * the values they were changed `from` and `to`.
  3027. */
  3028. this.trigger({
  3029. changes,
  3030. type: 'statechanged'
  3031. });
  3032. }
  3033. return changes;
  3034. }
  3035. };
  3036. /**
  3037. * Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target
  3038. * object.
  3039. *
  3040. * If the target object is {@link module:evented|evented} and has a
  3041. * `handleStateChanged` method, that method will be automatically bound to the
  3042. * `statechanged` event on itself.
  3043. *
  3044. * @param {Object} target
  3045. * The object to be made stateful.
  3046. *
  3047. * @param {Object} [defaultState]
  3048. * A default set of properties to populate the newly-stateful object's
  3049. * `state` property.
  3050. *
  3051. * @return {Object}
  3052. * Returns the `target`.
  3053. */
  3054. function stateful(target, defaultState) {
  3055. Object.assign(target, StatefulMixin);
  3056. // This happens after the mixing-in because we need to replace the `state`
  3057. // added in that step.
  3058. target.state = Object.assign({}, target.state, defaultState);
  3059. // Auto-bind the `handleStateChanged` method of the target object if it exists.
  3060. if (typeof target.handleStateChanged === 'function' && isEvented(target)) {
  3061. target.on('statechanged', target.handleStateChanged);
  3062. }
  3063. return target;
  3064. }
  3065. /**
  3066. * @file str.js
  3067. * @module to-lower-case
  3068. */
  3069. /**
  3070. * Lowercase the first letter of a string.
  3071. *
  3072. * @param {string} string
  3073. * String to be lowercased
  3074. *
  3075. * @return {string}
  3076. * The string with a lowercased first letter
  3077. */
  3078. const toLowerCase = function (string) {
  3079. if (typeof string !== 'string') {
  3080. return string;
  3081. }
  3082. return string.replace(/./, w => w.toLowerCase());
  3083. };
  3084. /**
  3085. * Uppercase the first letter of a string.
  3086. *
  3087. * @param {string} string
  3088. * String to be uppercased
  3089. *
  3090. * @return {string}
  3091. * The string with an uppercased first letter
  3092. */
  3093. const toTitleCase$1 = function (string) {
  3094. if (typeof string !== 'string') {
  3095. return string;
  3096. }
  3097. return string.replace(/./, w => w.toUpperCase());
  3098. };
  3099. /**
  3100. * Compares the TitleCase versions of the two strings for equality.
  3101. *
  3102. * @param {string} str1
  3103. * The first string to compare
  3104. *
  3105. * @param {string} str2
  3106. * The second string to compare
  3107. *
  3108. * @return {boolean}
  3109. * Whether the TitleCase versions of the strings are equal
  3110. */
  3111. const titleCaseEquals = function (str1, str2) {
  3112. return toTitleCase$1(str1) === toTitleCase$1(str2);
  3113. };
  3114. var Str = /*#__PURE__*/Object.freeze({
  3115. __proto__: null,
  3116. toLowerCase: toLowerCase,
  3117. toTitleCase: toTitleCase$1,
  3118. titleCaseEquals: titleCaseEquals
  3119. });
  3120. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  3121. function unwrapExports (x) {
  3122. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  3123. }
  3124. function createCommonjsModule(fn, module) {
  3125. return module = { exports: {} }, fn(module, module.exports), module.exports;
  3126. }
  3127. var keycode = createCommonjsModule(function (module, exports) {
  3128. // Source: http://jsfiddle.net/vWx8V/
  3129. // http://stackoverflow.com/questions/5603195/full-list-of-javascript-keycodes
  3130. /**
  3131. * Conenience method returns corresponding value for given keyName or keyCode.
  3132. *
  3133. * @param {Mixed} keyCode {Number} or keyName {String}
  3134. * @return {Mixed}
  3135. * @api public
  3136. */
  3137. function keyCode(searchInput) {
  3138. // Keyboard Events
  3139. if (searchInput && 'object' === typeof searchInput) {
  3140. var hasKeyCode = searchInput.which || searchInput.keyCode || searchInput.charCode;
  3141. if (hasKeyCode) searchInput = hasKeyCode;
  3142. }
  3143. // Numbers
  3144. if ('number' === typeof searchInput) return names[searchInput];
  3145. // Everything else (cast to string)
  3146. var search = String(searchInput);
  3147. // check codes
  3148. var foundNamedKey = codes[search.toLowerCase()];
  3149. if (foundNamedKey) return foundNamedKey;
  3150. // check aliases
  3151. var foundNamedKey = aliases[search.toLowerCase()];
  3152. if (foundNamedKey) return foundNamedKey;
  3153. // weird character?
  3154. if (search.length === 1) return search.charCodeAt(0);
  3155. return undefined;
  3156. }
  3157. /**
  3158. * Compares a keyboard event with a given keyCode or keyName.
  3159. *
  3160. * @param {Event} event Keyboard event that should be tested
  3161. * @param {Mixed} keyCode {Number} or keyName {String}
  3162. * @return {Boolean}
  3163. * @api public
  3164. */
  3165. keyCode.isEventKey = function isEventKey(event, nameOrCode) {
  3166. if (event && 'object' === typeof event) {
  3167. var keyCode = event.which || event.keyCode || event.charCode;
  3168. if (keyCode === null || keyCode === undefined) {
  3169. return false;
  3170. }
  3171. if (typeof nameOrCode === 'string') {
  3172. // check codes
  3173. var foundNamedKey = codes[nameOrCode.toLowerCase()];
  3174. if (foundNamedKey) {
  3175. return foundNamedKey === keyCode;
  3176. }
  3177. // check aliases
  3178. var foundNamedKey = aliases[nameOrCode.toLowerCase()];
  3179. if (foundNamedKey) {
  3180. return foundNamedKey === keyCode;
  3181. }
  3182. } else if (typeof nameOrCode === 'number') {
  3183. return nameOrCode === keyCode;
  3184. }
  3185. return false;
  3186. }
  3187. };
  3188. exports = module.exports = keyCode;
  3189. /**
  3190. * Get by name
  3191. *
  3192. * exports.code['enter'] // => 13
  3193. */
  3194. var codes = exports.code = exports.codes = {
  3195. 'backspace': 8,
  3196. 'tab': 9,
  3197. 'enter': 13,
  3198. 'shift': 16,
  3199. 'ctrl': 17,
  3200. 'alt': 18,
  3201. 'pause/break': 19,
  3202. 'caps lock': 20,
  3203. 'esc': 27,
  3204. 'space': 32,
  3205. 'page up': 33,
  3206. 'page down': 34,
  3207. 'end': 35,
  3208. 'home': 36,
  3209. 'left': 37,
  3210. 'up': 38,
  3211. 'right': 39,
  3212. 'down': 40,
  3213. 'insert': 45,
  3214. 'delete': 46,
  3215. 'command': 91,
  3216. 'left command': 91,
  3217. 'right command': 93,
  3218. 'numpad *': 106,
  3219. 'numpad +': 107,
  3220. 'numpad -': 109,
  3221. 'numpad .': 110,
  3222. 'numpad /': 111,
  3223. 'num lock': 144,
  3224. 'scroll lock': 145,
  3225. 'my computer': 182,
  3226. 'my calculator': 183,
  3227. ';': 186,
  3228. '=': 187,
  3229. ',': 188,
  3230. '-': 189,
  3231. '.': 190,
  3232. '/': 191,
  3233. '`': 192,
  3234. '[': 219,
  3235. '\\': 220,
  3236. ']': 221,
  3237. "'": 222
  3238. };
  3239. // Helper aliases
  3240. var aliases = exports.aliases = {
  3241. 'windows': 91,
  3242. '⇧': 16,
  3243. '⌥': 18,
  3244. '⌃': 17,
  3245. '⌘': 91,
  3246. 'ctl': 17,
  3247. 'control': 17,
  3248. 'option': 18,
  3249. 'pause': 19,
  3250. 'break': 19,
  3251. 'caps': 20,
  3252. 'return': 13,
  3253. 'escape': 27,
  3254. 'spc': 32,
  3255. 'spacebar': 32,
  3256. 'pgup': 33,
  3257. 'pgdn': 34,
  3258. 'ins': 45,
  3259. 'del': 46,
  3260. 'cmd': 91
  3261. };
  3262. /*!
  3263. * Programatically add the following
  3264. */
  3265. // lower case chars
  3266. for (i = 97; i < 123; i++) codes[String.fromCharCode(i)] = i - 32;
  3267. // numbers
  3268. for (var i = 48; i < 58; i++) codes[i - 48] = i;
  3269. // function keys
  3270. for (i = 1; i < 13; i++) codes['f' + i] = i + 111;
  3271. // numpad keys
  3272. for (i = 0; i < 10; i++) codes['numpad ' + i] = i + 96;
  3273. /**
  3274. * Get by code
  3275. *
  3276. * exports.name[13] // => 'Enter'
  3277. */
  3278. var names = exports.names = exports.title = {}; // title for backward compat
  3279. // Create reverse mapping
  3280. for (i in codes) names[codes[i]] = i;
  3281. // Add aliases
  3282. for (var alias in aliases) {
  3283. codes[alias] = aliases[alias];
  3284. }
  3285. });
  3286. keycode.code;
  3287. keycode.codes;
  3288. keycode.aliases;
  3289. keycode.names;
  3290. keycode.title;
  3291. /**
  3292. * Player Component - Base class for all UI objects
  3293. *
  3294. * @file component.js
  3295. */
  3296. /**
  3297. * Base class for all UI Components.
  3298. * Components are UI objects which represent both a javascript object and an element
  3299. * in the DOM. They can be children of other components, and can have
  3300. * children themselves.
  3301. *
  3302. * Components can also use methods from {@link EventTarget}
  3303. */
  3304. class Component$1 {
  3305. /**
  3306. * A callback that is called when a component is ready. Does not have any
  3307. * parameters and any callback value will be ignored.
  3308. *
  3309. * @callback ReadyCallback
  3310. * @this Component
  3311. */
  3312. /**
  3313. * Creates an instance of this class.
  3314. *
  3315. * @param { import('./player').default } player
  3316. * The `Player` that this class should be attached to.
  3317. *
  3318. * @param {Object} [options]
  3319. * The key/value store of component options.
  3320. *
  3321. * @param {Object[]} [options.children]
  3322. * An array of children objects to initialize this component with. Children objects have
  3323. * a name property that will be used if more than one component of the same type needs to be
  3324. * added.
  3325. *
  3326. * @param {string} [options.className]
  3327. * A class or space separated list of classes to add the component
  3328. *
  3329. * @param {ReadyCallback} [ready]
  3330. * Function that gets called when the `Component` is ready.
  3331. */
  3332. constructor(player, options, ready) {
  3333. // The component might be the player itself and we can't pass `this` to super
  3334. if (!player && this.play) {
  3335. this.player_ = player = this; // eslint-disable-line
  3336. } else {
  3337. this.player_ = player;
  3338. }
  3339. this.isDisposed_ = false;
  3340. // Hold the reference to the parent component via `addChild` method
  3341. this.parentComponent_ = null;
  3342. // Make a copy of prototype.options_ to protect against overriding defaults
  3343. this.options_ = merge$2({}, this.options_);
  3344. // Updated options with supplied options
  3345. options = this.options_ = merge$2(this.options_, options);
  3346. // Get ID from options or options element if one is supplied
  3347. this.id_ = options.id || options.el && options.el.id;
  3348. // If there was no ID from the options, generate one
  3349. if (!this.id_) {
  3350. // Don't require the player ID function in the case of mock players
  3351. const id = player && player.id && player.id() || 'no_player';
  3352. this.id_ = `${id}_component_${newGUID()}`;
  3353. }
  3354. this.name_ = options.name || null;
  3355. // Create element if one wasn't provided in options
  3356. if (options.el) {
  3357. this.el_ = options.el;
  3358. } else if (options.createEl !== false) {
  3359. this.el_ = this.createEl();
  3360. }
  3361. if (options.className && this.el_) {
  3362. options.className.split(' ').forEach(c => this.addClass(c));
  3363. }
  3364. // Remove the placeholder event methods. If the component is evented, the
  3365. // real methods are added next
  3366. ['on', 'off', 'one', 'any', 'trigger'].forEach(fn => {
  3367. this[fn] = undefined;
  3368. });
  3369. // if evented is anything except false, we want to mixin in evented
  3370. if (options.evented !== false) {
  3371. // Make this an evented object and use `el_`, if available, as its event bus
  3372. evented(this, {
  3373. eventBusKey: this.el_ ? 'el_' : null
  3374. });
  3375. this.handleLanguagechange = this.handleLanguagechange.bind(this);
  3376. this.on(this.player_, 'languagechange', this.handleLanguagechange);
  3377. }
  3378. stateful(this, this.constructor.defaultState);
  3379. this.children_ = [];
  3380. this.childIndex_ = {};
  3381. this.childNameIndex_ = {};
  3382. this.setTimeoutIds_ = new Set();
  3383. this.setIntervalIds_ = new Set();
  3384. this.rafIds_ = new Set();
  3385. this.namedRafs_ = new Map();
  3386. this.clearingTimersOnDispose_ = false;
  3387. // Add any child components in options
  3388. if (options.initChildren !== false) {
  3389. this.initChildren();
  3390. }
  3391. // Don't want to trigger ready here or it will go before init is actually
  3392. // finished for all children that run this constructor
  3393. this.ready(ready);
  3394. if (options.reportTouchActivity !== false) {
  3395. this.enableTouchActivity();
  3396. }
  3397. }
  3398. // `on`, `off`, `one`, `any` and `trigger` are here so tsc includes them in definitions.
  3399. // They are replaced or removed in the constructor
  3400. /**
  3401. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  3402. * function that will get called when an event with a certain name gets triggered.
  3403. *
  3404. * @param {string|string[]} type
  3405. * An event name or an array of event names.
  3406. *
  3407. * @param {Function} fn
  3408. * The function to call with `EventTarget`s
  3409. */
  3410. on(type, fn) {}
  3411. /**
  3412. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  3413. * This makes it so that the `event listener` will no longer get called when the
  3414. * named event happens.
  3415. *
  3416. * @param {string|string[]} type
  3417. * An event name or an array of event names.
  3418. *
  3419. * @param {Function} fn
  3420. * The function to remove.
  3421. */
  3422. off(type, fn) {}
  3423. /**
  3424. * This function will add an `event listener` that gets triggered only once. After the
  3425. * first trigger it will get removed. This is like adding an `event listener`
  3426. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  3427. *
  3428. * @param {string|string[]} type
  3429. * An event name or an array of event names.
  3430. *
  3431. * @param {Function} fn
  3432. * The function to be called once for each event name.
  3433. */
  3434. one(type, fn) {}
  3435. /**
  3436. * This function will add an `event listener` that gets triggered only once and is
  3437. * removed from all events. This is like adding an array of `event listener`s
  3438. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  3439. * first time it is triggered.
  3440. *
  3441. * @param {string|string[]} type
  3442. * An event name or an array of event names.
  3443. *
  3444. * @param {Function} fn
  3445. * The function to be called once for each event name.
  3446. */
  3447. any(type, fn) {}
  3448. /**
  3449. * This function causes an event to happen. This will then cause any `event listeners`
  3450. * that are waiting for that event, to get called. If there are no `event listeners`
  3451. * for an event then nothing will happen.
  3452. *
  3453. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  3454. * Trigger will also call the `on` + `uppercaseEventName` function.
  3455. *
  3456. * Example:
  3457. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  3458. * `onClick` if it exists.
  3459. *
  3460. * @param {string|Event|Object} event
  3461. * The name of the event, an `Event`, or an object with a key of type set to
  3462. * an event name.
  3463. */
  3464. trigger(event) {}
  3465. /**
  3466. * Dispose of the `Component` and all child components.
  3467. *
  3468. * @fires Component#dispose
  3469. *
  3470. * @param {Object} options
  3471. * @param {Element} options.originalEl element with which to replace player element
  3472. */
  3473. dispose(options = {}) {
  3474. // Bail out if the component has already been disposed.
  3475. if (this.isDisposed_) {
  3476. return;
  3477. }
  3478. if (this.readyQueue_) {
  3479. this.readyQueue_.length = 0;
  3480. }
  3481. /**
  3482. * Triggered when a `Component` is disposed.
  3483. *
  3484. * @event Component#dispose
  3485. * @type {Event}
  3486. *
  3487. * @property {boolean} [bubbles=false]
  3488. * set to false so that the dispose event does not
  3489. * bubble up
  3490. */
  3491. this.trigger({
  3492. type: 'dispose',
  3493. bubbles: false
  3494. });
  3495. this.isDisposed_ = true;
  3496. // Dispose all children.
  3497. if (this.children_) {
  3498. for (let i = this.children_.length - 1; i >= 0; i--) {
  3499. if (this.children_[i].dispose) {
  3500. this.children_[i].dispose();
  3501. }
  3502. }
  3503. }
  3504. // Delete child references
  3505. this.children_ = null;
  3506. this.childIndex_ = null;
  3507. this.childNameIndex_ = null;
  3508. this.parentComponent_ = null;
  3509. if (this.el_) {
  3510. // Remove element from DOM
  3511. if (this.el_.parentNode) {
  3512. if (options.restoreEl) {
  3513. this.el_.parentNode.replaceChild(options.restoreEl, this.el_);
  3514. } else {
  3515. this.el_.parentNode.removeChild(this.el_);
  3516. }
  3517. }
  3518. this.el_ = null;
  3519. }
  3520. // remove reference to the player after disposing of the element
  3521. this.player_ = null;
  3522. }
  3523. /**
  3524. * Determine whether or not this component has been disposed.
  3525. *
  3526. * @return {boolean}
  3527. * If the component has been disposed, will be `true`. Otherwise, `false`.
  3528. */
  3529. isDisposed() {
  3530. return Boolean(this.isDisposed_);
  3531. }
  3532. /**
  3533. * Return the {@link Player} that the `Component` has attached to.
  3534. *
  3535. * @return { import('./player').default }
  3536. * The player that this `Component` has attached to.
  3537. */
  3538. player() {
  3539. return this.player_;
  3540. }
  3541. /**
  3542. * Deep merge of options objects with new options.
  3543. * > Note: When both `obj` and `options` contain properties whose values are objects.
  3544. * The two properties get merged using {@link module:obj.merge}
  3545. *
  3546. * @param {Object} obj
  3547. * The object that contains new options.
  3548. *
  3549. * @return {Object}
  3550. * A new object of `this.options_` and `obj` merged together.
  3551. */
  3552. options(obj) {
  3553. if (!obj) {
  3554. return this.options_;
  3555. }
  3556. this.options_ = merge$2(this.options_, obj);
  3557. return this.options_;
  3558. }
  3559. /**
  3560. * Get the `Component`s DOM element
  3561. *
  3562. * @return {Element}
  3563. * The DOM element for this `Component`.
  3564. */
  3565. el() {
  3566. return this.el_;
  3567. }
  3568. /**
  3569. * Create the `Component`s DOM element.
  3570. *
  3571. * @param {string} [tagName]
  3572. * Element's DOM node type. e.g. 'div'
  3573. *
  3574. * @param {Object} [properties]
  3575. * An object of properties that should be set.
  3576. *
  3577. * @param {Object} [attributes]
  3578. * An object of attributes that should be set.
  3579. *
  3580. * @return {Element}
  3581. * The element that gets created.
  3582. */
  3583. createEl(tagName, properties, attributes) {
  3584. return createEl(tagName, properties, attributes);
  3585. }
  3586. /**
  3587. * Localize a string given the string in english.
  3588. *
  3589. * If tokens are provided, it'll try and run a simple token replacement on the provided string.
  3590. * The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.
  3591. *
  3592. * If a `defaultValue` is provided, it'll use that over `string`,
  3593. * if a value isn't found in provided language files.
  3594. * This is useful if you want to have a descriptive key for token replacement
  3595. * but have a succinct localized string and not require `en.json` to be included.
  3596. *
  3597. * Currently, it is used for the progress bar timing.
  3598. * ```js
  3599. * {
  3600. * "progress bar timing: currentTime={1} duration={2}": "{1} of {2}"
  3601. * }
  3602. * ```
  3603. * It is then used like so:
  3604. * ```js
  3605. * this.localize('progress bar timing: currentTime={1} duration{2}',
  3606. * [this.player_.currentTime(), this.player_.duration()],
  3607. * '{1} of {2}');
  3608. * ```
  3609. *
  3610. * Which outputs something like: `01:23 of 24:56`.
  3611. *
  3612. *
  3613. * @param {string} string
  3614. * The string to localize and the key to lookup in the language files.
  3615. * @param {string[]} [tokens]
  3616. * If the current item has token replacements, provide the tokens here.
  3617. * @param {string} [defaultValue]
  3618. * Defaults to `string`. Can be a default value to use for token replacement
  3619. * if the lookup key is needed to be separate.
  3620. *
  3621. * @return {string}
  3622. * The localized string or if no localization exists the english string.
  3623. */
  3624. localize(string, tokens, defaultValue = string) {
  3625. const code = this.player_.language && this.player_.language();
  3626. const languages = this.player_.languages && this.player_.languages();
  3627. const language = languages && languages[code];
  3628. const primaryCode = code && code.split('-')[0];
  3629. const primaryLang = languages && languages[primaryCode];
  3630. let localizedString = defaultValue;
  3631. if (language && language[string]) {
  3632. localizedString = language[string];
  3633. } else if (primaryLang && primaryLang[string]) {
  3634. localizedString = primaryLang[string];
  3635. }
  3636. if (tokens) {
  3637. localizedString = localizedString.replace(/\{(\d+)\}/g, function (match, index) {
  3638. const value = tokens[index - 1];
  3639. let ret = value;
  3640. if (typeof value === 'undefined') {
  3641. ret = match;
  3642. }
  3643. return ret;
  3644. });
  3645. }
  3646. return localizedString;
  3647. }
  3648. /**
  3649. * Handles language change for the player in components. Should be overridden by sub-components.
  3650. *
  3651. * @abstract
  3652. */
  3653. handleLanguagechange() {}
  3654. /**
  3655. * Return the `Component`s DOM element. This is where children get inserted.
  3656. * This will usually be the the same as the element returned in {@link Component#el}.
  3657. *
  3658. * @return {Element}
  3659. * The content element for this `Component`.
  3660. */
  3661. contentEl() {
  3662. return this.contentEl_ || this.el_;
  3663. }
  3664. /**
  3665. * Get this `Component`s ID
  3666. *
  3667. * @return {string}
  3668. * The id of this `Component`
  3669. */
  3670. id() {
  3671. return this.id_;
  3672. }
  3673. /**
  3674. * Get the `Component`s name. The name gets used to reference the `Component`
  3675. * and is set during registration.
  3676. *
  3677. * @return {string}
  3678. * The name of this `Component`.
  3679. */
  3680. name() {
  3681. return this.name_;
  3682. }
  3683. /**
  3684. * Get an array of all child components
  3685. *
  3686. * @return {Array}
  3687. * The children
  3688. */
  3689. children() {
  3690. return this.children_;
  3691. }
  3692. /**
  3693. * Returns the child `Component` with the given `id`.
  3694. *
  3695. * @param {string} id
  3696. * The id of the child `Component` to get.
  3697. *
  3698. * @return {Component|undefined}
  3699. * The child `Component` with the given `id` or undefined.
  3700. */
  3701. getChildById(id) {
  3702. return this.childIndex_[id];
  3703. }
  3704. /**
  3705. * Returns the child `Component` with the given `name`.
  3706. *
  3707. * @param {string} name
  3708. * The name of the child `Component` to get.
  3709. *
  3710. * @return {Component|undefined}
  3711. * The child `Component` with the given `name` or undefined.
  3712. */
  3713. getChild(name) {
  3714. if (!name) {
  3715. return;
  3716. }
  3717. return this.childNameIndex_[name];
  3718. }
  3719. /**
  3720. * Returns the descendant `Component` following the givent
  3721. * descendant `names`. For instance ['foo', 'bar', 'baz'] would
  3722. * try to get 'foo' on the current component, 'bar' on the 'foo'
  3723. * component and 'baz' on the 'bar' component and return undefined
  3724. * if any of those don't exist.
  3725. *
  3726. * @param {...string[]|...string} names
  3727. * The name of the child `Component` to get.
  3728. *
  3729. * @return {Component|undefined}
  3730. * The descendant `Component` following the given descendant
  3731. * `names` or undefined.
  3732. */
  3733. getDescendant(...names) {
  3734. // flatten array argument into the main array
  3735. names = names.reduce((acc, n) => acc.concat(n), []);
  3736. let currentChild = this;
  3737. for (let i = 0; i < names.length; i++) {
  3738. currentChild = currentChild.getChild(names[i]);
  3739. if (!currentChild || !currentChild.getChild) {
  3740. return;
  3741. }
  3742. }
  3743. return currentChild;
  3744. }
  3745. /**
  3746. * Add a child `Component` inside the current `Component`.
  3747. *
  3748. *
  3749. * @param {string|Component} child
  3750. * The name or instance of a child to add.
  3751. *
  3752. * @param {Object} [options={}]
  3753. * The key/value store of options that will get passed to children of
  3754. * the child.
  3755. *
  3756. * @param {number} [index=this.children_.length]
  3757. * The index to attempt to add a child into.
  3758. *
  3759. * @return {Component}
  3760. * The `Component` that gets added as a child. When using a string the
  3761. * `Component` will get created by this process.
  3762. */
  3763. addChild(child, options = {}, index = this.children_.length) {
  3764. let component;
  3765. let componentName;
  3766. // If child is a string, create component with options
  3767. if (typeof child === 'string') {
  3768. componentName = toTitleCase$1(child);
  3769. const componentClassName = options.componentClass || componentName;
  3770. // Set name through options
  3771. options.name = componentName;
  3772. // Create a new object & element for this controls set
  3773. // If there's no .player_, this is a player
  3774. const ComponentClass = Component$1.getComponent(componentClassName);
  3775. if (!ComponentClass) {
  3776. throw new Error(`Component ${componentClassName} does not exist`);
  3777. }
  3778. // data stored directly on the videojs object may be
  3779. // misidentified as a component to retain
  3780. // backwards-compatibility with 4.x. check to make sure the
  3781. // component class can be instantiated.
  3782. if (typeof ComponentClass !== 'function') {
  3783. return null;
  3784. }
  3785. component = new ComponentClass(this.player_ || this, options);
  3786. // child is a component instance
  3787. } else {
  3788. component = child;
  3789. }
  3790. if (component.parentComponent_) {
  3791. component.parentComponent_.removeChild(component);
  3792. }
  3793. this.children_.splice(index, 0, component);
  3794. component.parentComponent_ = this;
  3795. if (typeof component.id === 'function') {
  3796. this.childIndex_[component.id()] = component;
  3797. }
  3798. // If a name wasn't used to create the component, check if we can use the
  3799. // name function of the component
  3800. componentName = componentName || component.name && toTitleCase$1(component.name());
  3801. if (componentName) {
  3802. this.childNameIndex_[componentName] = component;
  3803. this.childNameIndex_[toLowerCase(componentName)] = component;
  3804. }
  3805. // Add the UI object's element to the container div (box)
  3806. // Having an element is not required
  3807. if (typeof component.el === 'function' && component.el()) {
  3808. // If inserting before a component, insert before that component's element
  3809. let refNode = null;
  3810. if (this.children_[index + 1]) {
  3811. // Most children are components, but the video tech is an HTML element
  3812. if (this.children_[index + 1].el_) {
  3813. refNode = this.children_[index + 1].el_;
  3814. } else if (isEl(this.children_[index + 1])) {
  3815. refNode = this.children_[index + 1];
  3816. }
  3817. }
  3818. this.contentEl().insertBefore(component.el(), refNode);
  3819. }
  3820. // Return so it can stored on parent object if desired.
  3821. return component;
  3822. }
  3823. /**
  3824. * Remove a child `Component` from this `Component`s list of children. Also removes
  3825. * the child `Component`s element from this `Component`s element.
  3826. *
  3827. * @param {Component} component
  3828. * The child `Component` to remove.
  3829. */
  3830. removeChild(component) {
  3831. if (typeof component === 'string') {
  3832. component = this.getChild(component);
  3833. }
  3834. if (!component || !this.children_) {
  3835. return;
  3836. }
  3837. let childFound = false;
  3838. for (let i = this.children_.length - 1; i >= 0; i--) {
  3839. if (this.children_[i] === component) {
  3840. childFound = true;
  3841. this.children_.splice(i, 1);
  3842. break;
  3843. }
  3844. }
  3845. if (!childFound) {
  3846. return;
  3847. }
  3848. component.parentComponent_ = null;
  3849. this.childIndex_[component.id()] = null;
  3850. this.childNameIndex_[toTitleCase$1(component.name())] = null;
  3851. this.childNameIndex_[toLowerCase(component.name())] = null;
  3852. const compEl = component.el();
  3853. if (compEl && compEl.parentNode === this.contentEl()) {
  3854. this.contentEl().removeChild(component.el());
  3855. }
  3856. }
  3857. /**
  3858. * Add and initialize default child `Component`s based upon options.
  3859. */
  3860. initChildren() {
  3861. const children = this.options_.children;
  3862. if (children) {
  3863. // `this` is `parent`
  3864. const parentOptions = this.options_;
  3865. const handleAdd = child => {
  3866. const name = child.name;
  3867. let opts = child.opts;
  3868. // Allow options for children to be set at the parent options
  3869. // e.g. videojs(id, { controlBar: false });
  3870. // instead of videojs(id, { children: { controlBar: false });
  3871. if (parentOptions[name] !== undefined) {
  3872. opts = parentOptions[name];
  3873. }
  3874. // Allow for disabling default components
  3875. // e.g. options['children']['posterImage'] = false
  3876. if (opts === false) {
  3877. return;
  3878. }
  3879. // Allow options to be passed as a simple boolean if no configuration
  3880. // is necessary.
  3881. if (opts === true) {
  3882. opts = {};
  3883. }
  3884. // We also want to pass the original player options
  3885. // to each component as well so they don't need to
  3886. // reach back into the player for options later.
  3887. opts.playerOptions = this.options_.playerOptions;
  3888. // Create and add the child component.
  3889. // Add a direct reference to the child by name on the parent instance.
  3890. // If two of the same component are used, different names should be supplied
  3891. // for each
  3892. const newChild = this.addChild(name, opts);
  3893. if (newChild) {
  3894. this[name] = newChild;
  3895. }
  3896. };
  3897. // Allow for an array of children details to passed in the options
  3898. let workingChildren;
  3899. const Tech = Component$1.getComponent('Tech');
  3900. if (Array.isArray(children)) {
  3901. workingChildren = children;
  3902. } else {
  3903. workingChildren = Object.keys(children);
  3904. }
  3905. workingChildren
  3906. // children that are in this.options_ but also in workingChildren would
  3907. // give us extra children we do not want. So, we want to filter them out.
  3908. .concat(Object.keys(this.options_).filter(function (child) {
  3909. return !workingChildren.some(function (wchild) {
  3910. if (typeof wchild === 'string') {
  3911. return child === wchild;
  3912. }
  3913. return child === wchild.name;
  3914. });
  3915. })).map(child => {
  3916. let name;
  3917. let opts;
  3918. if (typeof child === 'string') {
  3919. name = child;
  3920. opts = children[name] || this.options_[name] || {};
  3921. } else {
  3922. name = child.name;
  3923. opts = child;
  3924. }
  3925. return {
  3926. name,
  3927. opts
  3928. };
  3929. }).filter(child => {
  3930. // we have to make sure that child.name isn't in the techOrder since
  3931. // techs are registered as Components but can't aren't compatible
  3932. // See https://github.com/videojs/video.js/issues/2772
  3933. const c = Component$1.getComponent(child.opts.componentClass || toTitleCase$1(child.name));
  3934. return c && !Tech.isTech(c);
  3935. }).forEach(handleAdd);
  3936. }
  3937. }
  3938. /**
  3939. * Builds the default DOM class name. Should be overridden by sub-components.
  3940. *
  3941. * @return {string}
  3942. * The DOM class name for this object.
  3943. *
  3944. * @abstract
  3945. */
  3946. buildCSSClass() {
  3947. // Child classes can include a function that does:
  3948. // return 'CLASS NAME' + this._super();
  3949. return '';
  3950. }
  3951. /**
  3952. * Bind a listener to the component's ready state.
  3953. * Different from event listeners in that if the ready event has already happened
  3954. * it will trigger the function immediately.
  3955. *
  3956. * @param {ReadyCallback} fn
  3957. * Function that gets called when the `Component` is ready.
  3958. *
  3959. * @return {Component}
  3960. * Returns itself; method can be chained.
  3961. */
  3962. ready(fn, sync = false) {
  3963. if (!fn) {
  3964. return;
  3965. }
  3966. if (!this.isReady_) {
  3967. this.readyQueue_ = this.readyQueue_ || [];
  3968. this.readyQueue_.push(fn);
  3969. return;
  3970. }
  3971. if (sync) {
  3972. fn.call(this);
  3973. } else {
  3974. // Call the function asynchronously by default for consistency
  3975. this.setTimeout(fn, 1);
  3976. }
  3977. }
  3978. /**
  3979. * Trigger all the ready listeners for this `Component`.
  3980. *
  3981. * @fires Component#ready
  3982. */
  3983. triggerReady() {
  3984. this.isReady_ = true;
  3985. // Ensure ready is triggered asynchronously
  3986. this.setTimeout(function () {
  3987. const readyQueue = this.readyQueue_;
  3988. // Reset Ready Queue
  3989. this.readyQueue_ = [];
  3990. if (readyQueue && readyQueue.length > 0) {
  3991. readyQueue.forEach(function (fn) {
  3992. fn.call(this);
  3993. }, this);
  3994. }
  3995. // Allow for using event listeners also
  3996. /**
  3997. * Triggered when a `Component` is ready.
  3998. *
  3999. * @event Component#ready
  4000. * @type {Event}
  4001. */
  4002. this.trigger('ready');
  4003. }, 1);
  4004. }
  4005. /**
  4006. * Find a single DOM element matching a `selector`. This can be within the `Component`s
  4007. * `contentEl()` or another custom context.
  4008. *
  4009. * @param {string} selector
  4010. * A valid CSS selector, which will be passed to `querySelector`.
  4011. *
  4012. * @param {Element|string} [context=this.contentEl()]
  4013. * A DOM element within which to query. Can also be a selector string in
  4014. * which case the first matching element will get used as context. If
  4015. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  4016. * nothing it falls back to `document`.
  4017. *
  4018. * @return {Element|null}
  4019. * the dom element that was found, or null
  4020. *
  4021. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  4022. */
  4023. $(selector, context) {
  4024. return $(selector, context || this.contentEl());
  4025. }
  4026. /**
  4027. * Finds all DOM element matching a `selector`. This can be within the `Component`s
  4028. * `contentEl()` or another custom context.
  4029. *
  4030. * @param {string} selector
  4031. * A valid CSS selector, which will be passed to `querySelectorAll`.
  4032. *
  4033. * @param {Element|string} [context=this.contentEl()]
  4034. * A DOM element within which to query. Can also be a selector string in
  4035. * which case the first matching element will get used as context. If
  4036. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  4037. * nothing it falls back to `document`.
  4038. *
  4039. * @return {NodeList}
  4040. * a list of dom elements that were found
  4041. *
  4042. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  4043. */
  4044. $$(selector, context) {
  4045. return $$(selector, context || this.contentEl());
  4046. }
  4047. /**
  4048. * Check if a component's element has a CSS class name.
  4049. *
  4050. * @param {string} classToCheck
  4051. * CSS class name to check.
  4052. *
  4053. * @return {boolean}
  4054. * - True if the `Component` has the class.
  4055. * - False if the `Component` does not have the class`
  4056. */
  4057. hasClass(classToCheck) {
  4058. return hasClass(this.el_, classToCheck);
  4059. }
  4060. /**
  4061. * Add a CSS class name to the `Component`s element.
  4062. *
  4063. * @param {...string} classesToAdd
  4064. * One or more CSS class name to add.
  4065. */
  4066. addClass(...classesToAdd) {
  4067. addClass(this.el_, ...classesToAdd);
  4068. }
  4069. /**
  4070. * Remove a CSS class name from the `Component`s element.
  4071. *
  4072. * @param {...string} classesToRemove
  4073. * One or more CSS class name to remove.
  4074. */
  4075. removeClass(...classesToRemove) {
  4076. removeClass(this.el_, ...classesToRemove);
  4077. }
  4078. /**
  4079. * Add or remove a CSS class name from the component's element.
  4080. * - `classToToggle` gets added when {@link Component#hasClass} would return false.
  4081. * - `classToToggle` gets removed when {@link Component#hasClass} would return true.
  4082. *
  4083. * @param {string} classToToggle
  4084. * The class to add or remove based on (@link Component#hasClass}
  4085. *
  4086. * @param {boolean|Dom~predicate} [predicate]
  4087. * An {@link Dom~predicate} function or a boolean
  4088. */
  4089. toggleClass(classToToggle, predicate) {
  4090. toggleClass(this.el_, classToToggle, predicate);
  4091. }
  4092. /**
  4093. * Show the `Component`s element if it is hidden by removing the
  4094. * 'vjs-hidden' class name from it.
  4095. */
  4096. show() {
  4097. this.removeClass('vjs-hidden');
  4098. }
  4099. /**
  4100. * Hide the `Component`s element if it is currently showing by adding the
  4101. * 'vjs-hidden` class name to it.
  4102. */
  4103. hide() {
  4104. this.addClass('vjs-hidden');
  4105. }
  4106. /**
  4107. * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing'
  4108. * class name to it. Used during fadeIn/fadeOut.
  4109. *
  4110. * @private
  4111. */
  4112. lockShowing() {
  4113. this.addClass('vjs-lock-showing');
  4114. }
  4115. /**
  4116. * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing'
  4117. * class name from it. Used during fadeIn/fadeOut.
  4118. *
  4119. * @private
  4120. */
  4121. unlockShowing() {
  4122. this.removeClass('vjs-lock-showing');
  4123. }
  4124. /**
  4125. * Get the value of an attribute on the `Component`s element.
  4126. *
  4127. * @param {string} attribute
  4128. * Name of the attribute to get the value from.
  4129. *
  4130. * @return {string|null}
  4131. * - The value of the attribute that was asked for.
  4132. * - Can be an empty string on some browsers if the attribute does not exist
  4133. * or has no value
  4134. * - Most browsers will return null if the attribute does not exist or has
  4135. * no value.
  4136. *
  4137. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute}
  4138. */
  4139. getAttribute(attribute) {
  4140. return getAttribute(this.el_, attribute);
  4141. }
  4142. /**
  4143. * Set the value of an attribute on the `Component`'s element
  4144. *
  4145. * @param {string} attribute
  4146. * Name of the attribute to set.
  4147. *
  4148. * @param {string} value
  4149. * Value to set the attribute to.
  4150. *
  4151. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute}
  4152. */
  4153. setAttribute(attribute, value) {
  4154. setAttribute(this.el_, attribute, value);
  4155. }
  4156. /**
  4157. * Remove an attribute from the `Component`s element.
  4158. *
  4159. * @param {string} attribute
  4160. * Name of the attribute to remove.
  4161. *
  4162. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute}
  4163. */
  4164. removeAttribute(attribute) {
  4165. removeAttribute(this.el_, attribute);
  4166. }
  4167. /**
  4168. * Get or set the width of the component based upon the CSS styles.
  4169. * See {@link Component#dimension} for more detailed information.
  4170. *
  4171. * @param {number|string} [num]
  4172. * The width that you want to set postfixed with '%', 'px' or nothing.
  4173. *
  4174. * @param {boolean} [skipListeners]
  4175. * Skip the componentresize event trigger
  4176. *
  4177. * @return {number|string}
  4178. * The width when getting, zero if there is no width. Can be a string
  4179. * postpixed with '%' or 'px'.
  4180. */
  4181. width(num, skipListeners) {
  4182. return this.dimension('width', num, skipListeners);
  4183. }
  4184. /**
  4185. * Get or set the height of the component based upon the CSS styles.
  4186. * See {@link Component#dimension} for more detailed information.
  4187. *
  4188. * @param {number|string} [num]
  4189. * The height that you want to set postfixed with '%', 'px' or nothing.
  4190. *
  4191. * @param {boolean} [skipListeners]
  4192. * Skip the componentresize event trigger
  4193. *
  4194. * @return {number|string}
  4195. * The width when getting, zero if there is no width. Can be a string
  4196. * postpixed with '%' or 'px'.
  4197. */
  4198. height(num, skipListeners) {
  4199. return this.dimension('height', num, skipListeners);
  4200. }
  4201. /**
  4202. * Set both the width and height of the `Component` element at the same time.
  4203. *
  4204. * @param {number|string} width
  4205. * Width to set the `Component`s element to.
  4206. *
  4207. * @param {number|string} height
  4208. * Height to set the `Component`s element to.
  4209. */
  4210. dimensions(width, height) {
  4211. // Skip componentresize listeners on width for optimization
  4212. this.width(width, true);
  4213. this.height(height);
  4214. }
  4215. /**
  4216. * Get or set width or height of the `Component` element. This is the shared code
  4217. * for the {@link Component#width} and {@link Component#height}.
  4218. *
  4219. * Things to know:
  4220. * - If the width or height in an number this will return the number postfixed with 'px'.
  4221. * - If the width/height is a percent this will return the percent postfixed with '%'
  4222. * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function
  4223. * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`.
  4224. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/}
  4225. * for more information
  4226. * - If you want the computed style of the component, use {@link Component#currentWidth}
  4227. * and {@link {Component#currentHeight}
  4228. *
  4229. * @fires Component#componentresize
  4230. *
  4231. * @param {string} widthOrHeight
  4232. 8 'width' or 'height'
  4233. *
  4234. * @param {number|string} [num]
  4235. 8 New dimension
  4236. *
  4237. * @param {boolean} [skipListeners]
  4238. * Skip componentresize event trigger
  4239. *
  4240. * @return {number}
  4241. * The dimension when getting or 0 if unset
  4242. */
  4243. dimension(widthOrHeight, num, skipListeners) {
  4244. if (num !== undefined) {
  4245. // Set to zero if null or literally NaN (NaN !== NaN)
  4246. if (num === null || num !== num) {
  4247. num = 0;
  4248. }
  4249. // Check if using css width/height (% or px) and adjust
  4250. if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {
  4251. this.el_.style[widthOrHeight] = num;
  4252. } else if (num === 'auto') {
  4253. this.el_.style[widthOrHeight] = '';
  4254. } else {
  4255. this.el_.style[widthOrHeight] = num + 'px';
  4256. }
  4257. // skipListeners allows us to avoid triggering the resize event when setting both width and height
  4258. if (!skipListeners) {
  4259. /**
  4260. * Triggered when a component is resized.
  4261. *
  4262. * @event Component#componentresize
  4263. * @type {Event}
  4264. */
  4265. this.trigger('componentresize');
  4266. }
  4267. return;
  4268. }
  4269. // Not setting a value, so getting it
  4270. // Make sure element exists
  4271. if (!this.el_) {
  4272. return 0;
  4273. }
  4274. // Get dimension value from style
  4275. const val = this.el_.style[widthOrHeight];
  4276. const pxIndex = val.indexOf('px');
  4277. if (pxIndex !== -1) {
  4278. // Return the pixel value with no 'px'
  4279. return parseInt(val.slice(0, pxIndex), 10);
  4280. }
  4281. // No px so using % or no style was set, so falling back to offsetWidth/height
  4282. // If component has display:none, offset will return 0
  4283. // TODO: handle display:none and no dimension style using px
  4284. return parseInt(this.el_['offset' + toTitleCase$1(widthOrHeight)], 10);
  4285. }
  4286. /**
  4287. * Get the computed width or the height of the component's element.
  4288. *
  4289. * Uses `window.getComputedStyle`.
  4290. *
  4291. * @param {string} widthOrHeight
  4292. * A string containing 'width' or 'height'. Whichever one you want to get.
  4293. *
  4294. * @return {number}
  4295. * The dimension that gets asked for or 0 if nothing was set
  4296. * for that dimension.
  4297. */
  4298. currentDimension(widthOrHeight) {
  4299. let computedWidthOrHeight = 0;
  4300. if (widthOrHeight !== 'width' && widthOrHeight !== 'height') {
  4301. throw new Error('currentDimension only accepts width or height value');
  4302. }
  4303. computedWidthOrHeight = computedStyle(this.el_, widthOrHeight);
  4304. // remove 'px' from variable and parse as integer
  4305. computedWidthOrHeight = parseFloat(computedWidthOrHeight);
  4306. // if the computed value is still 0, it's possible that the browser is lying
  4307. // and we want to check the offset values.
  4308. // This code also runs wherever getComputedStyle doesn't exist.
  4309. if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) {
  4310. const rule = `offset${toTitleCase$1(widthOrHeight)}`;
  4311. computedWidthOrHeight = this.el_[rule];
  4312. }
  4313. return computedWidthOrHeight;
  4314. }
  4315. /**
  4316. * An object that contains width and height values of the `Component`s
  4317. * computed style. Uses `window.getComputedStyle`.
  4318. *
  4319. * @typedef {Object} Component~DimensionObject
  4320. *
  4321. * @property {number} width
  4322. * The width of the `Component`s computed style.
  4323. *
  4324. * @property {number} height
  4325. * The height of the `Component`s computed style.
  4326. */
  4327. /**
  4328. * Get an object that contains computed width and height values of the
  4329. * component's element.
  4330. *
  4331. * Uses `window.getComputedStyle`.
  4332. *
  4333. * @return {Component~DimensionObject}
  4334. * The computed dimensions of the component's element.
  4335. */
  4336. currentDimensions() {
  4337. return {
  4338. width: this.currentDimension('width'),
  4339. height: this.currentDimension('height')
  4340. };
  4341. }
  4342. /**
  4343. * Get the computed width of the component's element.
  4344. *
  4345. * Uses `window.getComputedStyle`.
  4346. *
  4347. * @return {number}
  4348. * The computed width of the component's element.
  4349. */
  4350. currentWidth() {
  4351. return this.currentDimension('width');
  4352. }
  4353. /**
  4354. * Get the computed height of the component's element.
  4355. *
  4356. * Uses `window.getComputedStyle`.
  4357. *
  4358. * @return {number}
  4359. * The computed height of the component's element.
  4360. */
  4361. currentHeight() {
  4362. return this.currentDimension('height');
  4363. }
  4364. /**
  4365. * Set the focus to this component
  4366. */
  4367. focus() {
  4368. this.el_.focus();
  4369. }
  4370. /**
  4371. * Remove the focus from this component
  4372. */
  4373. blur() {
  4374. this.el_.blur();
  4375. }
  4376. /**
  4377. * When this Component receives a `keydown` event which it does not process,
  4378. * it passes the event to the Player for handling.
  4379. *
  4380. * @param {KeyboardEvent} event
  4381. * The `keydown` event that caused this function to be called.
  4382. */
  4383. handleKeyDown(event) {
  4384. if (this.player_) {
  4385. // We only stop propagation here because we want unhandled events to fall
  4386. // back to the browser. Exclude Tab for focus trapping.
  4387. if (!keycode.isEventKey(event, 'Tab')) {
  4388. event.stopPropagation();
  4389. }
  4390. this.player_.handleKeyDown(event);
  4391. }
  4392. }
  4393. /**
  4394. * Many components used to have a `handleKeyPress` method, which was poorly
  4395. * named because it listened to a `keydown` event. This method name now
  4396. * delegates to `handleKeyDown`. This means anyone calling `handleKeyPress`
  4397. * will not see their method calls stop working.
  4398. *
  4399. * @param {Event} event
  4400. * The event that caused this function to be called.
  4401. */
  4402. handleKeyPress(event) {
  4403. this.handleKeyDown(event);
  4404. }
  4405. /**
  4406. * Emit a 'tap' events when touch event support gets detected. This gets used to
  4407. * support toggling the controls through a tap on the video. They get enabled
  4408. * because every sub-component would have extra overhead otherwise.
  4409. *
  4410. * @private
  4411. * @fires Component#tap
  4412. * @listens Component#touchstart
  4413. * @listens Component#touchmove
  4414. * @listens Component#touchleave
  4415. * @listens Component#touchcancel
  4416. * @listens Component#touchend
  4417. */
  4418. emitTapEvents() {
  4419. // Track the start time so we can determine how long the touch lasted
  4420. let touchStart = 0;
  4421. let firstTouch = null;
  4422. // Maximum movement allowed during a touch event to still be considered a tap
  4423. // Other popular libs use anywhere from 2 (hammer.js) to 15,
  4424. // so 10 seems like a nice, round number.
  4425. const tapMovementThreshold = 10;
  4426. // The maximum length a touch can be while still being considered a tap
  4427. const touchTimeThreshold = 200;
  4428. let couldBeTap;
  4429. this.on('touchstart', function (event) {
  4430. // If more than one finger, don't consider treating this as a click
  4431. if (event.touches.length === 1) {
  4432. // Copy pageX/pageY from the object
  4433. firstTouch = {
  4434. pageX: event.touches[0].pageX,
  4435. pageY: event.touches[0].pageY
  4436. };
  4437. // Record start time so we can detect a tap vs. "touch and hold"
  4438. touchStart = window.performance.now();
  4439. // Reset couldBeTap tracking
  4440. couldBeTap = true;
  4441. }
  4442. });
  4443. this.on('touchmove', function (event) {
  4444. // If more than one finger, don't consider treating this as a click
  4445. if (event.touches.length > 1) {
  4446. couldBeTap = false;
  4447. } else if (firstTouch) {
  4448. // Some devices will throw touchmoves for all but the slightest of taps.
  4449. // So, if we moved only a small distance, this could still be a tap
  4450. const xdiff = event.touches[0].pageX - firstTouch.pageX;
  4451. const ydiff = event.touches[0].pageY - firstTouch.pageY;
  4452. const touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
  4453. if (touchDistance > tapMovementThreshold) {
  4454. couldBeTap = false;
  4455. }
  4456. }
  4457. });
  4458. const noTap = function () {
  4459. couldBeTap = false;
  4460. };
  4461. // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
  4462. this.on('touchleave', noTap);
  4463. this.on('touchcancel', noTap);
  4464. // When the touch ends, measure how long it took and trigger the appropriate
  4465. // event
  4466. this.on('touchend', function (event) {
  4467. firstTouch = null;
  4468. // Proceed only if the touchmove/leave/cancel event didn't happen
  4469. if (couldBeTap === true) {
  4470. // Measure how long the touch lasted
  4471. const touchTime = window.performance.now() - touchStart;
  4472. // Make sure the touch was less than the threshold to be considered a tap
  4473. if (touchTime < touchTimeThreshold) {
  4474. // Don't let browser turn this into a click
  4475. event.preventDefault();
  4476. /**
  4477. * Triggered when a `Component` is tapped.
  4478. *
  4479. * @event Component#tap
  4480. * @type {MouseEvent}
  4481. */
  4482. this.trigger('tap');
  4483. // It may be good to copy the touchend event object and change the
  4484. // type to tap, if the other event properties aren't exact after
  4485. // Events.fixEvent runs (e.g. event.target)
  4486. }
  4487. }
  4488. });
  4489. }
  4490. /**
  4491. * This function reports user activity whenever touch events happen. This can get
  4492. * turned off by any sub-components that wants touch events to act another way.
  4493. *
  4494. * Report user touch activity when touch events occur. User activity gets used to
  4495. * determine when controls should show/hide. It is simple when it comes to mouse
  4496. * events, because any mouse event should show the controls. So we capture mouse
  4497. * events that bubble up to the player and report activity when that happens.
  4498. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player
  4499. * controls. So touch events can't help us at the player level either.
  4500. *
  4501. * User activity gets checked asynchronously. So what could happen is a tap event
  4502. * on the video turns the controls off. Then the `touchend` event bubbles up to
  4503. * the player. Which, if it reported user activity, would turn the controls right
  4504. * back on. We also don't want to completely block touch events from bubbling up.
  4505. * Furthermore a `touchmove` event and anything other than a tap, should not turn
  4506. * controls back on.
  4507. *
  4508. * @listens Component#touchstart
  4509. * @listens Component#touchmove
  4510. * @listens Component#touchend
  4511. * @listens Component#touchcancel
  4512. */
  4513. enableTouchActivity() {
  4514. // Don't continue if the root player doesn't support reporting user activity
  4515. if (!this.player() || !this.player().reportUserActivity) {
  4516. return;
  4517. }
  4518. // listener for reporting that the user is active
  4519. const report = bind_(this.player(), this.player().reportUserActivity);
  4520. let touchHolding;
  4521. this.on('touchstart', function () {
  4522. report();
  4523. // For as long as the they are touching the device or have their mouse down,
  4524. // we consider them active even if they're not moving their finger or mouse.
  4525. // So we want to continue to update that they are active
  4526. this.clearInterval(touchHolding);
  4527. // report at the same interval as activityCheck
  4528. touchHolding = this.setInterval(report, 250);
  4529. });
  4530. const touchEnd = function (event) {
  4531. report();
  4532. // stop the interval that maintains activity if the touch is holding
  4533. this.clearInterval(touchHolding);
  4534. };
  4535. this.on('touchmove', report);
  4536. this.on('touchend', touchEnd);
  4537. this.on('touchcancel', touchEnd);
  4538. }
  4539. /**
  4540. * A callback that has no parameters and is bound into `Component`s context.
  4541. *
  4542. * @callback Component~GenericCallback
  4543. * @this Component
  4544. */
  4545. /**
  4546. * Creates a function that runs after an `x` millisecond timeout. This function is a
  4547. * wrapper around `window.setTimeout`. There are a few reasons to use this one
  4548. * instead though:
  4549. * 1. It gets cleared via {@link Component#clearTimeout} when
  4550. * {@link Component#dispose} gets called.
  4551. * 2. The function callback will gets turned into a {@link Component~GenericCallback}
  4552. *
  4553. * > Note: You can't use `window.clearTimeout` on the id returned by this function. This
  4554. * will cause its dispose listener not to get cleaned up! Please use
  4555. * {@link Component#clearTimeout} or {@link Component#dispose} instead.
  4556. *
  4557. * @param {Component~GenericCallback} fn
  4558. * The function that will be run after `timeout`.
  4559. *
  4560. * @param {number} timeout
  4561. * Timeout in milliseconds to delay before executing the specified function.
  4562. *
  4563. * @return {number}
  4564. * Returns a timeout ID that gets used to identify the timeout. It can also
  4565. * get used in {@link Component#clearTimeout} to clear the timeout that
  4566. * was set.
  4567. *
  4568. * @listens Component#dispose
  4569. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout}
  4570. */
  4571. setTimeout(fn, timeout) {
  4572. // declare as variables so they are properly available in timeout function
  4573. // eslint-disable-next-line
  4574. var timeoutId;
  4575. fn = bind_(this, fn);
  4576. this.clearTimersOnDispose_();
  4577. timeoutId = window.setTimeout(() => {
  4578. if (this.setTimeoutIds_.has(timeoutId)) {
  4579. this.setTimeoutIds_.delete(timeoutId);
  4580. }
  4581. fn();
  4582. }, timeout);
  4583. this.setTimeoutIds_.add(timeoutId);
  4584. return timeoutId;
  4585. }
  4586. /**
  4587. * Clears a timeout that gets created via `window.setTimeout` or
  4588. * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout}
  4589. * use this function instead of `window.clearTimout`. If you don't your dispose
  4590. * listener will not get cleaned up until {@link Component#dispose}!
  4591. *
  4592. * @param {number} timeoutId
  4593. * The id of the timeout to clear. The return value of
  4594. * {@link Component#setTimeout} or `window.setTimeout`.
  4595. *
  4596. * @return {number}
  4597. * Returns the timeout id that was cleared.
  4598. *
  4599. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout}
  4600. */
  4601. clearTimeout(timeoutId) {
  4602. if (this.setTimeoutIds_.has(timeoutId)) {
  4603. this.setTimeoutIds_.delete(timeoutId);
  4604. window.clearTimeout(timeoutId);
  4605. }
  4606. return timeoutId;
  4607. }
  4608. /**
  4609. * Creates a function that gets run every `x` milliseconds. This function is a wrapper
  4610. * around `window.setInterval`. There are a few reasons to use this one instead though.
  4611. * 1. It gets cleared via {@link Component#clearInterval} when
  4612. * {@link Component#dispose} gets called.
  4613. * 2. The function callback will be a {@link Component~GenericCallback}
  4614. *
  4615. * @param {Component~GenericCallback} fn
  4616. * The function to run every `x` seconds.
  4617. *
  4618. * @param {number} interval
  4619. * Execute the specified function every `x` milliseconds.
  4620. *
  4621. * @return {number}
  4622. * Returns an id that can be used to identify the interval. It can also be be used in
  4623. * {@link Component#clearInterval} to clear the interval.
  4624. *
  4625. * @listens Component#dispose
  4626. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval}
  4627. */
  4628. setInterval(fn, interval) {
  4629. fn = bind_(this, fn);
  4630. this.clearTimersOnDispose_();
  4631. const intervalId = window.setInterval(fn, interval);
  4632. this.setIntervalIds_.add(intervalId);
  4633. return intervalId;
  4634. }
  4635. /**
  4636. * Clears an interval that gets created via `window.setInterval` or
  4637. * {@link Component#setInterval}. If you set an interval via {@link Component#setInterval}
  4638. * use this function instead of `window.clearInterval`. If you don't your dispose
  4639. * listener will not get cleaned up until {@link Component#dispose}!
  4640. *
  4641. * @param {number} intervalId
  4642. * The id of the interval to clear. The return value of
  4643. * {@link Component#setInterval} or `window.setInterval`.
  4644. *
  4645. * @return {number}
  4646. * Returns the interval id that was cleared.
  4647. *
  4648. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval}
  4649. */
  4650. clearInterval(intervalId) {
  4651. if (this.setIntervalIds_.has(intervalId)) {
  4652. this.setIntervalIds_.delete(intervalId);
  4653. window.clearInterval(intervalId);
  4654. }
  4655. return intervalId;
  4656. }
  4657. /**
  4658. * Queues up a callback to be passed to requestAnimationFrame (rAF), but
  4659. * with a few extra bonuses:
  4660. *
  4661. * - Supports browsers that do not support rAF by falling back to
  4662. * {@link Component#setTimeout}.
  4663. *
  4664. * - The callback is turned into a {@link Component~GenericCallback} (i.e.
  4665. * bound to the component).
  4666. *
  4667. * - Automatic cancellation of the rAF callback is handled if the component
  4668. * is disposed before it is called.
  4669. *
  4670. * @param {Component~GenericCallback} fn
  4671. * A function that will be bound to this component and executed just
  4672. * before the browser's next repaint.
  4673. *
  4674. * @return {number}
  4675. * Returns an rAF ID that gets used to identify the timeout. It can
  4676. * also be used in {@link Component#cancelAnimationFrame} to cancel
  4677. * the animation frame callback.
  4678. *
  4679. * @listens Component#dispose
  4680. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}
  4681. */
  4682. requestAnimationFrame(fn) {
  4683. this.clearTimersOnDispose_();
  4684. // declare as variables so they are properly available in rAF function
  4685. // eslint-disable-next-line
  4686. var id;
  4687. fn = bind_(this, fn);
  4688. id = window.requestAnimationFrame(() => {
  4689. if (this.rafIds_.has(id)) {
  4690. this.rafIds_.delete(id);
  4691. }
  4692. fn();
  4693. });
  4694. this.rafIds_.add(id);
  4695. return id;
  4696. }
  4697. /**
  4698. * Request an animation frame, but only one named animation
  4699. * frame will be queued. Another will never be added until
  4700. * the previous one finishes.
  4701. *
  4702. * @param {string} name
  4703. * The name to give this requestAnimationFrame
  4704. *
  4705. * @param {Component~GenericCallback} fn
  4706. * A function that will be bound to this component and executed just
  4707. * before the browser's next repaint.
  4708. */
  4709. requestNamedAnimationFrame(name, fn) {
  4710. if (this.namedRafs_.has(name)) {
  4711. return;
  4712. }
  4713. this.clearTimersOnDispose_();
  4714. fn = bind_(this, fn);
  4715. const id = this.requestAnimationFrame(() => {
  4716. fn();
  4717. if (this.namedRafs_.has(name)) {
  4718. this.namedRafs_.delete(name);
  4719. }
  4720. });
  4721. this.namedRafs_.set(name, id);
  4722. return name;
  4723. }
  4724. /**
  4725. * Cancels a current named animation frame if it exists.
  4726. *
  4727. * @param {string} name
  4728. * The name of the requestAnimationFrame to cancel.
  4729. */
  4730. cancelNamedAnimationFrame(name) {
  4731. if (!this.namedRafs_.has(name)) {
  4732. return;
  4733. }
  4734. this.cancelAnimationFrame(this.namedRafs_.get(name));
  4735. this.namedRafs_.delete(name);
  4736. }
  4737. /**
  4738. * Cancels a queued callback passed to {@link Component#requestAnimationFrame}
  4739. * (rAF).
  4740. *
  4741. * If you queue an rAF callback via {@link Component#requestAnimationFrame},
  4742. * use this function instead of `window.cancelAnimationFrame`. If you don't,
  4743. * your dispose listener will not get cleaned up until {@link Component#dispose}!
  4744. *
  4745. * @param {number} id
  4746. * The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}.
  4747. *
  4748. * @return {number}
  4749. * Returns the rAF ID that was cleared.
  4750. *
  4751. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame}
  4752. */
  4753. cancelAnimationFrame(id) {
  4754. if (this.rafIds_.has(id)) {
  4755. this.rafIds_.delete(id);
  4756. window.cancelAnimationFrame(id);
  4757. }
  4758. return id;
  4759. }
  4760. /**
  4761. * A function to setup `requestAnimationFrame`, `setTimeout`,
  4762. * and `setInterval`, clearing on dispose.
  4763. *
  4764. * > Previously each timer added and removed dispose listeners on it's own.
  4765. * For better performance it was decided to batch them all, and use `Set`s
  4766. * to track outstanding timer ids.
  4767. *
  4768. * @private
  4769. */
  4770. clearTimersOnDispose_() {
  4771. if (this.clearingTimersOnDispose_) {
  4772. return;
  4773. }
  4774. this.clearingTimersOnDispose_ = true;
  4775. this.one('dispose', () => {
  4776. [['namedRafs_', 'cancelNamedAnimationFrame'], ['rafIds_', 'cancelAnimationFrame'], ['setTimeoutIds_', 'clearTimeout'], ['setIntervalIds_', 'clearInterval']].forEach(([idName, cancelName]) => {
  4777. // for a `Set` key will actually be the value again
  4778. // so forEach((val, val) =>` but for maps we want to use
  4779. // the key.
  4780. this[idName].forEach((val, key) => this[cancelName](key));
  4781. });
  4782. this.clearingTimersOnDispose_ = false;
  4783. });
  4784. }
  4785. /**
  4786. * Register a `Component` with `videojs` given the name and the component.
  4787. *
  4788. * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s
  4789. * should be registered using {@link Tech.registerTech} or
  4790. * {@link videojs:videojs.registerTech}.
  4791. *
  4792. * > NOTE: This function can also be seen on videojs as
  4793. * {@link videojs:videojs.registerComponent}.
  4794. *
  4795. * @param {string} name
  4796. * The name of the `Component` to register.
  4797. *
  4798. * @param {Component} ComponentToRegister
  4799. * The `Component` class to register.
  4800. *
  4801. * @return {Component}
  4802. * The `Component` that was registered.
  4803. */
  4804. static registerComponent(name, ComponentToRegister) {
  4805. if (typeof name !== 'string' || !name) {
  4806. throw new Error(`Illegal component name, "${name}"; must be a non-empty string.`);
  4807. }
  4808. const Tech = Component$1.getComponent('Tech');
  4809. // We need to make sure this check is only done if Tech has been registered.
  4810. const isTech = Tech && Tech.isTech(ComponentToRegister);
  4811. const isComp = Component$1 === ComponentToRegister || Component$1.prototype.isPrototypeOf(ComponentToRegister.prototype);
  4812. if (isTech || !isComp) {
  4813. let reason;
  4814. if (isTech) {
  4815. reason = 'techs must be registered using Tech.registerTech()';
  4816. } else {
  4817. reason = 'must be a Component subclass';
  4818. }
  4819. throw new Error(`Illegal component, "${name}"; ${reason}.`);
  4820. }
  4821. name = toTitleCase$1(name);
  4822. if (!Component$1.components_) {
  4823. Component$1.components_ = {};
  4824. }
  4825. const Player = Component$1.getComponent('Player');
  4826. if (name === 'Player' && Player && Player.players) {
  4827. const players = Player.players;
  4828. const playerNames = Object.keys(players);
  4829. // If we have players that were disposed, then their name will still be
  4830. // in Players.players. So, we must loop through and verify that the value
  4831. // for each item is not null. This allows registration of the Player component
  4832. // after all players have been disposed or before any were created.
  4833. if (players && playerNames.length > 0 && playerNames.map(pname => players[pname]).every(Boolean)) {
  4834. throw new Error('Can not register Player component after player has been created.');
  4835. }
  4836. }
  4837. Component$1.components_[name] = ComponentToRegister;
  4838. Component$1.components_[toLowerCase(name)] = ComponentToRegister;
  4839. return ComponentToRegister;
  4840. }
  4841. /**
  4842. * Get a `Component` based on the name it was registered with.
  4843. *
  4844. * @param {string} name
  4845. * The Name of the component to get.
  4846. *
  4847. * @return {Component}
  4848. * The `Component` that got registered under the given name.
  4849. */
  4850. static getComponent(name) {
  4851. if (!name || !Component$1.components_) {
  4852. return;
  4853. }
  4854. return Component$1.components_[name];
  4855. }
  4856. }
  4857. Component$1.registerComponent('Component', Component$1);
  4858. /**
  4859. * @file time.js
  4860. * @module time
  4861. */
  4862. /**
  4863. * Returns the time for the specified index at the start or end
  4864. * of a TimeRange object.
  4865. *
  4866. * @typedef {Function} TimeRangeIndex
  4867. *
  4868. * @param {number} [index=0]
  4869. * The range number to return the time for.
  4870. *
  4871. * @return {number}
  4872. * The time offset at the specified index.
  4873. *
  4874. * @deprecated The index argument must be provided.
  4875. * In the future, leaving it out will throw an error.
  4876. */
  4877. /**
  4878. * An object that contains ranges of time, which mimics {@link TimeRanges}.
  4879. *
  4880. * @typedef {Object} TimeRange
  4881. *
  4882. * @property {number} length
  4883. * The number of time ranges represented by this object.
  4884. *
  4885. * @property {module:time~TimeRangeIndex} start
  4886. * Returns the time offset at which a specified time range begins.
  4887. *
  4888. * @property {module:time~TimeRangeIndex} end
  4889. * Returns the time offset at which a specified time range ends.
  4890. *
  4891. * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges
  4892. */
  4893. /**
  4894. * Check if any of the time ranges are over the maximum index.
  4895. *
  4896. * @private
  4897. * @param {string} fnName
  4898. * The function name to use for logging
  4899. *
  4900. * @param {number} index
  4901. * The index to check
  4902. *
  4903. * @param {number} maxIndex
  4904. * The maximum possible index
  4905. *
  4906. * @throws {Error} if the timeRanges provided are over the maxIndex
  4907. */
  4908. function rangeCheck(fnName, index, maxIndex) {
  4909. if (typeof index !== 'number' || index < 0 || index > maxIndex) {
  4910. throw new Error(`Failed to execute '${fnName}' on 'TimeRanges': The index provided (${index}) is non-numeric or out of bounds (0-${maxIndex}).`);
  4911. }
  4912. }
  4913. /**
  4914. * Get the time for the specified index at the start or end
  4915. * of a TimeRange object.
  4916. *
  4917. * @private
  4918. * @param {string} fnName
  4919. * The function name to use for logging
  4920. *
  4921. * @param {string} valueIndex
  4922. * The property that should be used to get the time. should be
  4923. * 'start' or 'end'
  4924. *
  4925. * @param {Array} ranges
  4926. * An array of time ranges
  4927. *
  4928. * @param {Array} [rangeIndex=0]
  4929. * The index to start the search at
  4930. *
  4931. * @return {number}
  4932. * The time that offset at the specified index.
  4933. *
  4934. * @deprecated rangeIndex must be set to a value, in the future this will throw an error.
  4935. * @throws {Error} if rangeIndex is more than the length of ranges
  4936. */
  4937. function getRange(fnName, valueIndex, ranges, rangeIndex) {
  4938. rangeCheck(fnName, rangeIndex, ranges.length - 1);
  4939. return ranges[rangeIndex][valueIndex];
  4940. }
  4941. /**
  4942. * Create a time range object given ranges of time.
  4943. *
  4944. * @private
  4945. * @param {Array} [ranges]
  4946. * An array of time ranges.
  4947. *
  4948. * @return {TimeRange}
  4949. */
  4950. function createTimeRangesObj(ranges) {
  4951. let timeRangesObj;
  4952. if (ranges === undefined || ranges.length === 0) {
  4953. timeRangesObj = {
  4954. length: 0,
  4955. start() {
  4956. throw new Error('This TimeRanges object is empty');
  4957. },
  4958. end() {
  4959. throw new Error('This TimeRanges object is empty');
  4960. }
  4961. };
  4962. } else {
  4963. timeRangesObj = {
  4964. length: ranges.length,
  4965. start: getRange.bind(null, 'start', 0, ranges),
  4966. end: getRange.bind(null, 'end', 1, ranges)
  4967. };
  4968. }
  4969. if (window.Symbol && window.Symbol.iterator) {
  4970. timeRangesObj[window.Symbol.iterator] = () => (ranges || []).values();
  4971. }
  4972. return timeRangesObj;
  4973. }
  4974. /**
  4975. * Create a `TimeRange` object which mimics an
  4976. * {@link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges|HTML5 TimeRanges instance}.
  4977. *
  4978. * @param {number|Array[]} start
  4979. * The start of a single range (a number) or an array of ranges (an
  4980. * array of arrays of two numbers each).
  4981. *
  4982. * @param {number} end
  4983. * The end of a single range. Cannot be used with the array form of
  4984. * the `start` argument.
  4985. *
  4986. * @return {TimeRange}
  4987. */
  4988. function createTimeRanges$1(start, end) {
  4989. if (Array.isArray(start)) {
  4990. return createTimeRangesObj(start);
  4991. } else if (start === undefined || end === undefined) {
  4992. return createTimeRangesObj();
  4993. }
  4994. return createTimeRangesObj([[start, end]]);
  4995. }
  4996. /**
  4997. * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in
  4998. * seconds) will force a number of leading zeros to cover the length of the
  4999. * guide.
  5000. *
  5001. * @private
  5002. * @param {number} seconds
  5003. * Number of seconds to be turned into a string
  5004. *
  5005. * @param {number} guide
  5006. * Number (in seconds) to model the string after
  5007. *
  5008. * @return {string}
  5009. * Time formatted as H:MM:SS or M:SS
  5010. */
  5011. const defaultImplementation = function (seconds, guide) {
  5012. seconds = seconds < 0 ? 0 : seconds;
  5013. let s = Math.floor(seconds % 60);
  5014. let m = Math.floor(seconds / 60 % 60);
  5015. let h = Math.floor(seconds / 3600);
  5016. const gm = Math.floor(guide / 60 % 60);
  5017. const gh = Math.floor(guide / 3600);
  5018. // handle invalid times
  5019. if (isNaN(seconds) || seconds === Infinity) {
  5020. // '-' is false for all relational operators (e.g. <, >=) so this setting
  5021. // will add the minimum number of fields specified by the guide
  5022. h = m = s = '-';
  5023. }
  5024. // Check if we need to show hours
  5025. h = h > 0 || gh > 0 ? h + ':' : '';
  5026. // If hours are showing, we may need to add a leading zero.
  5027. // Always show at least one digit of minutes.
  5028. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':';
  5029. // Check if leading zero is need for seconds
  5030. s = s < 10 ? '0' + s : s;
  5031. return h + m + s;
  5032. };
  5033. // Internal pointer to the current implementation.
  5034. let implementation = defaultImplementation;
  5035. /**
  5036. * Replaces the default formatTime implementation with a custom implementation.
  5037. *
  5038. * @param {Function} customImplementation
  5039. * A function which will be used in place of the default formatTime
  5040. * implementation. Will receive the current time in seconds and the
  5041. * guide (in seconds) as arguments.
  5042. */
  5043. function setFormatTime(customImplementation) {
  5044. implementation = customImplementation;
  5045. }
  5046. /**
  5047. * Resets formatTime to the default implementation.
  5048. */
  5049. function resetFormatTime() {
  5050. implementation = defaultImplementation;
  5051. }
  5052. /**
  5053. * Delegates to either the default time formatting function or a custom
  5054. * function supplied via `setFormatTime`.
  5055. *
  5056. * Formats seconds as a time string (H:MM:SS or M:SS). Supplying a
  5057. * guide (in seconds) will force a number of leading zeros to cover the
  5058. * length of the guide.
  5059. *
  5060. * @example formatTime(125, 600) === "02:05"
  5061. * @param {number} seconds
  5062. * Number of seconds to be turned into a string
  5063. *
  5064. * @param {number} guide
  5065. * Number (in seconds) to model the string after
  5066. *
  5067. * @return {string}
  5068. * Time formatted as H:MM:SS or M:SS
  5069. */
  5070. function formatTime(seconds, guide = seconds) {
  5071. return implementation(seconds, guide);
  5072. }
  5073. var Time = /*#__PURE__*/Object.freeze({
  5074. __proto__: null,
  5075. createTimeRanges: createTimeRanges$1,
  5076. createTimeRange: createTimeRanges$1,
  5077. setFormatTime: setFormatTime,
  5078. resetFormatTime: resetFormatTime,
  5079. formatTime: formatTime
  5080. });
  5081. /**
  5082. * @file buffer.js
  5083. * @module buffer
  5084. */
  5085. /**
  5086. * Compute the percentage of the media that has been buffered.
  5087. *
  5088. * @param { import('./time').TimeRange } buffered
  5089. * The current `TimeRanges` object representing buffered time ranges
  5090. *
  5091. * @param {number} duration
  5092. * Total duration of the media
  5093. *
  5094. * @return {number}
  5095. * Percent buffered of the total duration in decimal form.
  5096. */
  5097. function bufferedPercent(buffered, duration) {
  5098. let bufferedDuration = 0;
  5099. let start;
  5100. let end;
  5101. if (!duration) {
  5102. return 0;
  5103. }
  5104. if (!buffered || !buffered.length) {
  5105. buffered = createTimeRanges$1(0, 0);
  5106. }
  5107. for (let i = 0; i < buffered.length; i++) {
  5108. start = buffered.start(i);
  5109. end = buffered.end(i);
  5110. // buffered end can be bigger than duration by a very small fraction
  5111. if (end > duration) {
  5112. end = duration;
  5113. }
  5114. bufferedDuration += end - start;
  5115. }
  5116. return bufferedDuration / duration;
  5117. }
  5118. /**
  5119. * @file media-error.js
  5120. */
  5121. /**
  5122. * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class.
  5123. *
  5124. * @param {number|string|Object|MediaError} value
  5125. * This can be of multiple types:
  5126. * - number: should be a standard error code
  5127. * - string: an error message (the code will be 0)
  5128. * - Object: arbitrary properties
  5129. * - `MediaError` (native): used to populate a video.js `MediaError` object
  5130. * - `MediaError` (video.js): will return itself if it's already a
  5131. * video.js `MediaError` object.
  5132. *
  5133. * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror}
  5134. * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes}
  5135. *
  5136. * @class MediaError
  5137. */
  5138. function MediaError(value) {
  5139. // Allow redundant calls to this constructor to avoid having `instanceof`
  5140. // checks peppered around the code.
  5141. if (value instanceof MediaError) {
  5142. return value;
  5143. }
  5144. if (typeof value === 'number') {
  5145. this.code = value;
  5146. } else if (typeof value === 'string') {
  5147. // default code is zero, so this is a custom error
  5148. this.message = value;
  5149. } else if (isObject$1(value)) {
  5150. // We assign the `code` property manually because native `MediaError` objects
  5151. // do not expose it as an own/enumerable property of the object.
  5152. if (typeof value.code === 'number') {
  5153. this.code = value.code;
  5154. }
  5155. Object.assign(this, value);
  5156. }
  5157. if (!this.message) {
  5158. this.message = MediaError.defaultMessages[this.code] || '';
  5159. }
  5160. }
  5161. /**
  5162. * The error code that refers two one of the defined `MediaError` types
  5163. *
  5164. * @type {Number}
  5165. */
  5166. MediaError.prototype.code = 0;
  5167. /**
  5168. * An optional message that to show with the error. Message is not part of the HTML5
  5169. * video spec but allows for more informative custom errors.
  5170. *
  5171. * @type {String}
  5172. */
  5173. MediaError.prototype.message = '';
  5174. /**
  5175. * An optional status code that can be set by plugins to allow even more detail about
  5176. * the error. For example a plugin might provide a specific HTTP status code and an
  5177. * error message for that code. Then when the plugin gets that error this class will
  5178. * know how to display an error message for it. This allows a custom message to show
  5179. * up on the `Player` error overlay.
  5180. *
  5181. * @type {Array}
  5182. */
  5183. MediaError.prototype.status = null;
  5184. /**
  5185. * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the
  5186. * specification listed under {@link MediaError} for more information.
  5187. *
  5188. * @enum {array}
  5189. * @readonly
  5190. * @property {string} 0 - MEDIA_ERR_CUSTOM
  5191. * @property {string} 1 - MEDIA_ERR_ABORTED
  5192. * @property {string} 2 - MEDIA_ERR_NETWORK
  5193. * @property {string} 3 - MEDIA_ERR_DECODE
  5194. * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED
  5195. * @property {string} 5 - MEDIA_ERR_ENCRYPTED
  5196. */
  5197. MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED'];
  5198. /**
  5199. * The default `MediaError` messages based on the {@link MediaError.errorTypes}.
  5200. *
  5201. * @type {Array}
  5202. * @constant
  5203. */
  5204. MediaError.defaultMessages = {
  5205. 1: 'You aborted the media playback',
  5206. 2: 'A network error caused the media download to fail part-way.',
  5207. 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
  5208. 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
  5209. 5: 'The media is encrypted and we do not have the keys to decrypt it.'
  5210. };
  5211. // Add types as properties on MediaError
  5212. // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  5213. for (let errNum = 0; errNum < MediaError.errorTypes.length; errNum++) {
  5214. MediaError[MediaError.errorTypes[errNum]] = errNum;
  5215. // values should be accessible on both the class and instance
  5216. MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
  5217. }
  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, 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. const trackToJson_ = function (track) {
  5273. const ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce((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 { import('../tech/tech').default } 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. const textTracksToJson = function (tech) {
  5303. const trackEls = tech.$$('track');
  5304. const trackObjs = Array.prototype.map.call(trackEls, t => t.track);
  5305. const tracks = Array.prototype.map.call(trackEls, function (trackEl) {
  5306. const json = trackToJson_(trackEl.track);
  5307. if (trackEl.src) {
  5308. json.src = trackEl.src;
  5309. }
  5310. return json;
  5311. });
  5312. return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
  5313. return trackObjs.indexOf(track) === -1;
  5314. }).map(trackToJson_));
  5315. };
  5316. /**
  5317. * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript
  5318. * object {@link TextTrack} representations.
  5319. *
  5320. * @param {Array} json
  5321. * An array of `TextTrack` representation objects, like those that would be
  5322. * produced by `textTracksToJson`.
  5323. *
  5324. * @param {Tech} tech
  5325. * The `Tech` to create the `TextTrack`s on.
  5326. */
  5327. const jsonToTextTracks = function (json, tech) {
  5328. json.forEach(function (track) {
  5329. const addedTrack = tech.addRemoteTextTrack(track).track;
  5330. if (!track.src && track.cues) {
  5331. track.cues.forEach(cue => addedTrack.addCue(cue));
  5332. }
  5333. });
  5334. return tech.textTracks();
  5335. };
  5336. var textTrackConverter = {
  5337. textTracksToJson,
  5338. jsonToTextTracks,
  5339. trackToJson_
  5340. };
  5341. /**
  5342. * @file modal-dialog.js
  5343. */
  5344. const MODAL_CLASS_NAME = 'vjs-modal-dialog';
  5345. /**
  5346. * The `ModalDialog` displays over the video and its controls, which blocks
  5347. * interaction with the player until it is closed.
  5348. *
  5349. * Modal dialogs include a "Close" button and will close when that button
  5350. * is activated - or when ESC is pressed anywhere.
  5351. *
  5352. * @extends Component
  5353. */
  5354. class ModalDialog extends Component$1 {
  5355. /**
  5356. * Create an instance of this class.
  5357. *
  5358. * @param { import('./player').default } player
  5359. * The `Player` that this class should be attached to.
  5360. *
  5361. * @param {Object} [options]
  5362. * The key/value store of player options.
  5363. *
  5364. * @param { import('./utils/dom').ContentDescriptor} [options.content=undefined]
  5365. * Provide customized content for this modal.
  5366. *
  5367. * @param {string} [options.description]
  5368. * A text description for the modal, primarily for accessibility.
  5369. *
  5370. * @param {boolean} [options.fillAlways=false]
  5371. * Normally, modals are automatically filled only the first time
  5372. * they open. This tells the modal to refresh its content
  5373. * every time it opens.
  5374. *
  5375. * @param {string} [options.label]
  5376. * A text label for the modal, primarily for accessibility.
  5377. *
  5378. * @param {boolean} [options.pauseOnOpen=true]
  5379. * If `true`, playback will will be paused if playing when
  5380. * the modal opens, and resumed when it closes.
  5381. *
  5382. * @param {boolean} [options.temporary=true]
  5383. * If `true`, the modal can only be opened once; it will be
  5384. * disposed as soon as it's closed.
  5385. *
  5386. * @param {boolean} [options.uncloseable=false]
  5387. * If `true`, the user will not be able to close the modal
  5388. * through the UI in the normal ways. Programmatic closing is
  5389. * still possible.
  5390. */
  5391. constructor(player, options) {
  5392. super(player, options);
  5393. this.handleKeyDown_ = e => this.handleKeyDown(e);
  5394. this.close_ = e => this.close(e);
  5395. this.opened_ = this.hasBeenOpened_ = this.hasBeenFilled_ = false;
  5396. this.closeable(!this.options_.uncloseable);
  5397. this.content(this.options_.content);
  5398. // Make sure the contentEl is defined AFTER any children are initialized
  5399. // because we only want the contents of the modal in the contentEl
  5400. // (not the UI elements like the close button).
  5401. this.contentEl_ = createEl('div', {
  5402. className: `${MODAL_CLASS_NAME}-content`
  5403. }, {
  5404. role: 'document'
  5405. });
  5406. this.descEl_ = createEl('p', {
  5407. className: `${MODAL_CLASS_NAME}-description vjs-control-text`,
  5408. id: this.el().getAttribute('aria-describedby')
  5409. });
  5410. textContent(this.descEl_, this.description());
  5411. this.el_.appendChild(this.descEl_);
  5412. this.el_.appendChild(this.contentEl_);
  5413. }
  5414. /**
  5415. * Create the `ModalDialog`'s DOM element
  5416. *
  5417. * @return {Element}
  5418. * The DOM element that gets created.
  5419. */
  5420. createEl() {
  5421. return super.createEl('div', {
  5422. className: this.buildCSSClass(),
  5423. tabIndex: -1
  5424. }, {
  5425. 'aria-describedby': `${this.id()}_description`,
  5426. 'aria-hidden': 'true',
  5427. 'aria-label': this.label(),
  5428. 'role': 'dialog'
  5429. });
  5430. }
  5431. dispose() {
  5432. this.contentEl_ = null;
  5433. this.descEl_ = null;
  5434. this.previouslyActiveEl_ = null;
  5435. super.dispose();
  5436. }
  5437. /**
  5438. * Builds the default DOM `className`.
  5439. *
  5440. * @return {string}
  5441. * The DOM `className` for this object.
  5442. */
  5443. buildCSSClass() {
  5444. return `${MODAL_CLASS_NAME} vjs-hidden ${super.buildCSSClass()}`;
  5445. }
  5446. /**
  5447. * Returns the label string for this modal. Primarily used for accessibility.
  5448. *
  5449. * @return {string}
  5450. * the localized or raw label of this modal.
  5451. */
  5452. label() {
  5453. return this.localize(this.options_.label || 'Modal Window');
  5454. }
  5455. /**
  5456. * Returns the description string for this modal. Primarily used for
  5457. * accessibility.
  5458. *
  5459. * @return {string}
  5460. * The localized or raw description of this modal.
  5461. */
  5462. description() {
  5463. let desc = this.options_.description || this.localize('This is a modal window.');
  5464. // Append a universal closeability message if the modal is closeable.
  5465. if (this.closeable()) {
  5466. desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.');
  5467. }
  5468. return desc;
  5469. }
  5470. /**
  5471. * Opens the modal.
  5472. *
  5473. * @fires ModalDialog#beforemodalopen
  5474. * @fires ModalDialog#modalopen
  5475. */
  5476. open() {
  5477. if (!this.opened_) {
  5478. const player = this.player();
  5479. /**
  5480. * Fired just before a `ModalDialog` is opened.
  5481. *
  5482. * @event ModalDialog#beforemodalopen
  5483. * @type {Event}
  5484. */
  5485. this.trigger('beforemodalopen');
  5486. this.opened_ = true;
  5487. // Fill content if the modal has never opened before and
  5488. // never been filled.
  5489. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {
  5490. this.fill();
  5491. }
  5492. // If the player was playing, pause it and take note of its previously
  5493. // playing state.
  5494. this.wasPlaying_ = !player.paused();
  5495. if (this.options_.pauseOnOpen && this.wasPlaying_) {
  5496. player.pause();
  5497. }
  5498. this.on('keydown', this.handleKeyDown_);
  5499. // Hide controls and note if they were enabled.
  5500. this.hadControls_ = player.controls();
  5501. player.controls(false);
  5502. this.show();
  5503. this.conditionalFocus_();
  5504. this.el().setAttribute('aria-hidden', 'false');
  5505. /**
  5506. * Fired just after a `ModalDialog` is opened.
  5507. *
  5508. * @event ModalDialog#modalopen
  5509. * @type {Event}
  5510. */
  5511. this.trigger('modalopen');
  5512. this.hasBeenOpened_ = true;
  5513. }
  5514. }
  5515. /**
  5516. * If the `ModalDialog` is currently open or closed.
  5517. *
  5518. * @param {boolean} [value]
  5519. * If given, it will open (`true`) or close (`false`) the modal.
  5520. *
  5521. * @return {boolean}
  5522. * the current open state of the modaldialog
  5523. */
  5524. opened(value) {
  5525. if (typeof value === 'boolean') {
  5526. this[value ? 'open' : 'close']();
  5527. }
  5528. return this.opened_;
  5529. }
  5530. /**
  5531. * Closes the modal, does nothing if the `ModalDialog` is
  5532. * not open.
  5533. *
  5534. * @fires ModalDialog#beforemodalclose
  5535. * @fires ModalDialog#modalclose
  5536. */
  5537. close() {
  5538. if (!this.opened_) {
  5539. return;
  5540. }
  5541. const player = this.player();
  5542. /**
  5543. * Fired just before a `ModalDialog` is closed.
  5544. *
  5545. * @event ModalDialog#beforemodalclose
  5546. * @type {Event}
  5547. */
  5548. this.trigger('beforemodalclose');
  5549. this.opened_ = false;
  5550. if (this.wasPlaying_ && this.options_.pauseOnOpen) {
  5551. player.play();
  5552. }
  5553. this.off('keydown', this.handleKeyDown_);
  5554. if (this.hadControls_) {
  5555. player.controls(true);
  5556. }
  5557. this.hide();
  5558. this.el().setAttribute('aria-hidden', 'true');
  5559. /**
  5560. * Fired just after a `ModalDialog` is closed.
  5561. *
  5562. * @event ModalDialog#modalclose
  5563. * @type {Event}
  5564. */
  5565. this.trigger('modalclose');
  5566. this.conditionalBlur_();
  5567. if (this.options_.temporary) {
  5568. this.dispose();
  5569. }
  5570. }
  5571. /**
  5572. * Check to see if the `ModalDialog` is closeable via the UI.
  5573. *
  5574. * @param {boolean} [value]
  5575. * If given as a boolean, it will set the `closeable` option.
  5576. *
  5577. * @return {boolean}
  5578. * Returns the final value of the closable option.
  5579. */
  5580. closeable(value) {
  5581. if (typeof value === 'boolean') {
  5582. const closeable = this.closeable_ = !!value;
  5583. let close = this.getChild('closeButton');
  5584. // If this is being made closeable and has no close button, add one.
  5585. if (closeable && !close) {
  5586. // The close button should be a child of the modal - not its
  5587. // content element, so temporarily change the content element.
  5588. const temp = this.contentEl_;
  5589. this.contentEl_ = this.el_;
  5590. close = this.addChild('closeButton', {
  5591. controlText: 'Close Modal Dialog'
  5592. });
  5593. this.contentEl_ = temp;
  5594. this.on(close, 'close', this.close_);
  5595. }
  5596. // If this is being made uncloseable and has a close button, remove it.
  5597. if (!closeable && close) {
  5598. this.off(close, 'close', this.close_);
  5599. this.removeChild(close);
  5600. close.dispose();
  5601. }
  5602. }
  5603. return this.closeable_;
  5604. }
  5605. /**
  5606. * Fill the modal's content element with the modal's "content" option.
  5607. * The content element will be emptied before this change takes place.
  5608. */
  5609. fill() {
  5610. this.fillWith(this.content());
  5611. }
  5612. /**
  5613. * Fill the modal's content element with arbitrary content.
  5614. * The content element will be emptied before this change takes place.
  5615. *
  5616. * @fires ModalDialog#beforemodalfill
  5617. * @fires ModalDialog#modalfill
  5618. *
  5619. * @param { import('./utils/dom').ContentDescriptor} [content]
  5620. * The same rules apply to this as apply to the `content` option.
  5621. */
  5622. fillWith(content) {
  5623. const contentEl = this.contentEl();
  5624. const parentEl = contentEl.parentNode;
  5625. const nextSiblingEl = contentEl.nextSibling;
  5626. /**
  5627. * Fired just before a `ModalDialog` is filled with content.
  5628. *
  5629. * @event ModalDialog#beforemodalfill
  5630. * @type {Event}
  5631. */
  5632. this.trigger('beforemodalfill');
  5633. this.hasBeenFilled_ = true;
  5634. // Detach the content element from the DOM before performing
  5635. // manipulation to avoid modifying the live DOM multiple times.
  5636. parentEl.removeChild(contentEl);
  5637. this.empty();
  5638. insertContent(contentEl, content);
  5639. /**
  5640. * Fired just after a `ModalDialog` is filled with content.
  5641. *
  5642. * @event ModalDialog#modalfill
  5643. * @type {Event}
  5644. */
  5645. this.trigger('modalfill');
  5646. // Re-inject the re-filled content element.
  5647. if (nextSiblingEl) {
  5648. parentEl.insertBefore(contentEl, nextSiblingEl);
  5649. } else {
  5650. parentEl.appendChild(contentEl);
  5651. }
  5652. // make sure that the close button is last in the dialog DOM
  5653. const closeButton = this.getChild('closeButton');
  5654. if (closeButton) {
  5655. parentEl.appendChild(closeButton.el_);
  5656. }
  5657. }
  5658. /**
  5659. * Empties the content element. This happens anytime the modal is filled.
  5660. *
  5661. * @fires ModalDialog#beforemodalempty
  5662. * @fires ModalDialog#modalempty
  5663. */
  5664. empty() {
  5665. /**
  5666. * Fired just before a `ModalDialog` is emptied.
  5667. *
  5668. * @event ModalDialog#beforemodalempty
  5669. * @type {Event}
  5670. */
  5671. this.trigger('beforemodalempty');
  5672. emptyEl(this.contentEl());
  5673. /**
  5674. * Fired just after a `ModalDialog` is emptied.
  5675. *
  5676. * @event ModalDialog#modalempty
  5677. * @type {Event}
  5678. */
  5679. this.trigger('modalempty');
  5680. }
  5681. /**
  5682. * Gets or sets the modal content, which gets normalized before being
  5683. * rendered into the DOM.
  5684. *
  5685. * This does not update the DOM or fill the modal, but it is called during
  5686. * that process.
  5687. *
  5688. * @param { import('./utils/dom').ContentDescriptor} [value]
  5689. * If defined, sets the internal content value to be used on the
  5690. * next call(s) to `fill`. This value is normalized before being
  5691. * inserted. To "clear" the internal content value, pass `null`.
  5692. *
  5693. * @return { import('./utils/dom').ContentDescriptor}
  5694. * The current content of the modal dialog
  5695. */
  5696. content(value) {
  5697. if (typeof value !== 'undefined') {
  5698. this.content_ = value;
  5699. }
  5700. return this.content_;
  5701. }
  5702. /**
  5703. * conditionally focus the modal dialog if focus was previously on the player.
  5704. *
  5705. * @private
  5706. */
  5707. conditionalFocus_() {
  5708. const activeEl = document.activeElement;
  5709. const playerEl = this.player_.el_;
  5710. this.previouslyActiveEl_ = null;
  5711. if (playerEl.contains(activeEl) || playerEl === activeEl) {
  5712. this.previouslyActiveEl_ = activeEl;
  5713. this.focus();
  5714. }
  5715. }
  5716. /**
  5717. * conditionally blur the element and refocus the last focused element
  5718. *
  5719. * @private
  5720. */
  5721. conditionalBlur_() {
  5722. if (this.previouslyActiveEl_) {
  5723. this.previouslyActiveEl_.focus();
  5724. this.previouslyActiveEl_ = null;
  5725. }
  5726. }
  5727. /**
  5728. * Keydown handler. Attached when modal is focused.
  5729. *
  5730. * @listens keydown
  5731. */
  5732. handleKeyDown(event) {
  5733. // Do not allow keydowns to reach out of the modal dialog.
  5734. event.stopPropagation();
  5735. if (keycode.isEventKey(event, 'Escape') && this.closeable()) {
  5736. event.preventDefault();
  5737. this.close();
  5738. return;
  5739. }
  5740. // exit early if it isn't a tab key
  5741. if (!keycode.isEventKey(event, 'Tab')) {
  5742. return;
  5743. }
  5744. const focusableEls = this.focusableEls_();
  5745. const activeEl = this.el_.querySelector(':focus');
  5746. let focusIndex;
  5747. for (let i = 0; i < focusableEls.length; i++) {
  5748. if (activeEl === focusableEls[i]) {
  5749. focusIndex = i;
  5750. break;
  5751. }
  5752. }
  5753. if (document.activeElement === this.el_) {
  5754. focusIndex = 0;
  5755. }
  5756. if (event.shiftKey && focusIndex === 0) {
  5757. focusableEls[focusableEls.length - 1].focus();
  5758. event.preventDefault();
  5759. } else if (!event.shiftKey && focusIndex === focusableEls.length - 1) {
  5760. focusableEls[0].focus();
  5761. event.preventDefault();
  5762. }
  5763. }
  5764. /**
  5765. * get all focusable elements
  5766. *
  5767. * @private
  5768. */
  5769. focusableEls_() {
  5770. const allChildren = this.el_.querySelectorAll('*');
  5771. return Array.prototype.filter.call(allChildren, child => {
  5772. 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');
  5773. });
  5774. }
  5775. }
  5776. /**
  5777. * Default options for `ModalDialog` default options.
  5778. *
  5779. * @type {Object}
  5780. * @private
  5781. */
  5782. ModalDialog.prototype.options_ = {
  5783. pauseOnOpen: true,
  5784. temporary: true
  5785. };
  5786. Component$1.registerComponent('ModalDialog', ModalDialog);
  5787. /**
  5788. * @file track-list.js
  5789. */
  5790. /**
  5791. * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and
  5792. * {@link VideoTrackList}
  5793. *
  5794. * @extends EventTarget
  5795. */
  5796. class TrackList extends EventTarget$2 {
  5797. /**
  5798. * Create an instance of this class
  5799. *
  5800. * @param { import('./track').default[] } tracks
  5801. * A list of tracks to initialize the list with.
  5802. *
  5803. * @abstract
  5804. */
  5805. constructor(tracks = []) {
  5806. super();
  5807. this.tracks_ = [];
  5808. /**
  5809. * @memberof TrackList
  5810. * @member {number} length
  5811. * The current number of `Track`s in the this Trackist.
  5812. * @instance
  5813. */
  5814. Object.defineProperty(this, 'length', {
  5815. get() {
  5816. return this.tracks_.length;
  5817. }
  5818. });
  5819. for (let i = 0; i < tracks.length; i++) {
  5820. this.addTrack(tracks[i]);
  5821. }
  5822. }
  5823. /**
  5824. * Add a {@link Track} to the `TrackList`
  5825. *
  5826. * @param { import('./track').default } track
  5827. * The audio, video, or text track to add to the list.
  5828. *
  5829. * @fires TrackList#addtrack
  5830. */
  5831. addTrack(track) {
  5832. const index = this.tracks_.length;
  5833. if (!('' + index in this)) {
  5834. Object.defineProperty(this, index, {
  5835. get() {
  5836. return this.tracks_[index];
  5837. }
  5838. });
  5839. }
  5840. // Do not add duplicate tracks
  5841. if (this.tracks_.indexOf(track) === -1) {
  5842. this.tracks_.push(track);
  5843. /**
  5844. * Triggered when a track is added to a track list.
  5845. *
  5846. * @event TrackList#addtrack
  5847. * @type {Event}
  5848. * @property {Track} track
  5849. * A reference to track that was added.
  5850. */
  5851. this.trigger({
  5852. track,
  5853. type: 'addtrack',
  5854. target: this
  5855. });
  5856. }
  5857. /**
  5858. * Triggered when a track label is changed.
  5859. *
  5860. * @event TrackList#addtrack
  5861. * @type {Event}
  5862. * @property {Track} track
  5863. * A reference to track that was added.
  5864. */
  5865. track.labelchange_ = () => {
  5866. this.trigger({
  5867. track,
  5868. type: 'labelchange',
  5869. target: this
  5870. });
  5871. };
  5872. if (isEvented(track)) {
  5873. track.addEventListener('labelchange', track.labelchange_);
  5874. }
  5875. }
  5876. /**
  5877. * Remove a {@link Track} from the `TrackList`
  5878. *
  5879. * @param { import('./track').default } rtrack
  5880. * The audio, video, or text track to remove from the list.
  5881. *
  5882. * @fires TrackList#removetrack
  5883. */
  5884. removeTrack(rtrack) {
  5885. let track;
  5886. for (let i = 0, l = this.length; i < l; i++) {
  5887. if (this[i] === rtrack) {
  5888. track = this[i];
  5889. if (track.off) {
  5890. track.off();
  5891. }
  5892. this.tracks_.splice(i, 1);
  5893. break;
  5894. }
  5895. }
  5896. if (!track) {
  5897. return;
  5898. }
  5899. /**
  5900. * Triggered when a track is removed from track list.
  5901. *
  5902. * @event TrackList#removetrack
  5903. * @type {Event}
  5904. * @property {Track} track
  5905. * A reference to track that was removed.
  5906. */
  5907. this.trigger({
  5908. track,
  5909. type: 'removetrack',
  5910. target: this
  5911. });
  5912. }
  5913. /**
  5914. * Get a Track from the TrackList by a tracks id
  5915. *
  5916. * @param {string} id - the id of the track to get
  5917. * @method getTrackById
  5918. * @return { import('./track').default }
  5919. * @private
  5920. */
  5921. getTrackById(id) {
  5922. let result = null;
  5923. for (let i = 0, l = this.length; i < l; i++) {
  5924. const track = this[i];
  5925. if (track.id === id) {
  5926. result = track;
  5927. break;
  5928. }
  5929. }
  5930. return result;
  5931. }
  5932. }
  5933. /**
  5934. * Triggered when a different track is selected/enabled.
  5935. *
  5936. * @event TrackList#change
  5937. * @type {Event}
  5938. */
  5939. /**
  5940. * Events that can be called with on + eventName. See {@link EventHandler}.
  5941. *
  5942. * @property {Object} TrackList#allowedEvents_
  5943. * @private
  5944. */
  5945. TrackList.prototype.allowedEvents_ = {
  5946. change: 'change',
  5947. addtrack: 'addtrack',
  5948. removetrack: 'removetrack',
  5949. labelchange: 'labelchange'
  5950. };
  5951. // emulate attribute EventHandler support to allow for feature detection
  5952. for (const event in TrackList.prototype.allowedEvents_) {
  5953. TrackList.prototype['on' + event] = null;
  5954. }
  5955. /**
  5956. * @file audio-track-list.js
  5957. */
  5958. /**
  5959. * Anywhere we call this function we diverge from the spec
  5960. * as we only support one enabled audiotrack at a time
  5961. *
  5962. * @param {AudioTrackList} list
  5963. * list to work on
  5964. *
  5965. * @param { import('./audio-track').default } track
  5966. * The track to skip
  5967. *
  5968. * @private
  5969. */
  5970. const disableOthers$1 = function (list, track) {
  5971. for (let i = 0; i < list.length; i++) {
  5972. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  5973. continue;
  5974. }
  5975. // another audio track is enabled, disable it
  5976. list[i].enabled = false;
  5977. }
  5978. };
  5979. /**
  5980. * The current list of {@link AudioTrack} for a media file.
  5981. *
  5982. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist}
  5983. * @extends TrackList
  5984. */
  5985. class AudioTrackList extends TrackList {
  5986. /**
  5987. * Create an instance of this class.
  5988. *
  5989. * @param {AudioTrack[]} [tracks=[]]
  5990. * A list of `AudioTrack` to instantiate the list with.
  5991. */
  5992. constructor(tracks = []) {
  5993. // make sure only 1 track is enabled
  5994. // sorted from last index to first index
  5995. for (let i = tracks.length - 1; i >= 0; i--) {
  5996. if (tracks[i].enabled) {
  5997. disableOthers$1(tracks, tracks[i]);
  5998. break;
  5999. }
  6000. }
  6001. super(tracks);
  6002. this.changing_ = false;
  6003. }
  6004. /**
  6005. * Add an {@link AudioTrack} to the `AudioTrackList`.
  6006. *
  6007. * @param { import('./audio-track').default } track
  6008. * The AudioTrack to add to the list
  6009. *
  6010. * @fires TrackList#addtrack
  6011. */
  6012. addTrack(track) {
  6013. if (track.enabled) {
  6014. disableOthers$1(this, track);
  6015. }
  6016. super.addTrack(track);
  6017. // native tracks don't have this
  6018. if (!track.addEventListener) {
  6019. return;
  6020. }
  6021. track.enabledChange_ = () => {
  6022. // when we are disabling other tracks (since we don't support
  6023. // more than one track at a time) we will set changing_
  6024. // to true so that we don't trigger additional change events
  6025. if (this.changing_) {
  6026. return;
  6027. }
  6028. this.changing_ = true;
  6029. disableOthers$1(this, track);
  6030. this.changing_ = false;
  6031. this.trigger('change');
  6032. };
  6033. /**
  6034. * @listens AudioTrack#enabledchange
  6035. * @fires TrackList#change
  6036. */
  6037. track.addEventListener('enabledchange', track.enabledChange_);
  6038. }
  6039. removeTrack(rtrack) {
  6040. super.removeTrack(rtrack);
  6041. if (rtrack.removeEventListener && rtrack.enabledChange_) {
  6042. rtrack.removeEventListener('enabledchange', rtrack.enabledChange_);
  6043. rtrack.enabledChange_ = null;
  6044. }
  6045. }
  6046. }
  6047. /**
  6048. * @file video-track-list.js
  6049. */
  6050. /**
  6051. * Un-select all other {@link VideoTrack}s that are selected.
  6052. *
  6053. * @param {VideoTrackList} list
  6054. * list to work on
  6055. *
  6056. * @param { import('./video-track').default } track
  6057. * The track to skip
  6058. *
  6059. * @private
  6060. */
  6061. const disableOthers = function (list, track) {
  6062. for (let i = 0; i < list.length; i++) {
  6063. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  6064. continue;
  6065. }
  6066. // another video track is enabled, disable it
  6067. list[i].selected = false;
  6068. }
  6069. };
  6070. /**
  6071. * The current list of {@link VideoTrack} for a video.
  6072. *
  6073. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist}
  6074. * @extends TrackList
  6075. */
  6076. class VideoTrackList extends TrackList {
  6077. /**
  6078. * Create an instance of this class.
  6079. *
  6080. * @param {VideoTrack[]} [tracks=[]]
  6081. * A list of `VideoTrack` to instantiate the list with.
  6082. */
  6083. constructor(tracks = []) {
  6084. // make sure only 1 track is enabled
  6085. // sorted from last index to first index
  6086. for (let i = tracks.length - 1; i >= 0; i--) {
  6087. if (tracks[i].selected) {
  6088. disableOthers(tracks, tracks[i]);
  6089. break;
  6090. }
  6091. }
  6092. super(tracks);
  6093. this.changing_ = false;
  6094. /**
  6095. * @member {number} VideoTrackList#selectedIndex
  6096. * The current index of the selected {@link VideoTrack`}.
  6097. */
  6098. Object.defineProperty(this, 'selectedIndex', {
  6099. get() {
  6100. for (let i = 0; i < this.length; i++) {
  6101. if (this[i].selected) {
  6102. return i;
  6103. }
  6104. }
  6105. return -1;
  6106. },
  6107. set() {}
  6108. });
  6109. }
  6110. /**
  6111. * Add a {@link VideoTrack} to the `VideoTrackList`.
  6112. *
  6113. * @param { import('./video-track').default } track
  6114. * The VideoTrack to add to the list
  6115. *
  6116. * @fires TrackList#addtrack
  6117. */
  6118. addTrack(track) {
  6119. if (track.selected) {
  6120. disableOthers(this, track);
  6121. }
  6122. super.addTrack(track);
  6123. // native tracks don't have this
  6124. if (!track.addEventListener) {
  6125. return;
  6126. }
  6127. track.selectedChange_ = () => {
  6128. if (this.changing_) {
  6129. return;
  6130. }
  6131. this.changing_ = true;
  6132. disableOthers(this, track);
  6133. this.changing_ = false;
  6134. this.trigger('change');
  6135. };
  6136. /**
  6137. * @listens VideoTrack#selectedchange
  6138. * @fires TrackList#change
  6139. */
  6140. track.addEventListener('selectedchange', track.selectedChange_);
  6141. }
  6142. removeTrack(rtrack) {
  6143. super.removeTrack(rtrack);
  6144. if (rtrack.removeEventListener && rtrack.selectedChange_) {
  6145. rtrack.removeEventListener('selectedchange', rtrack.selectedChange_);
  6146. rtrack.selectedChange_ = null;
  6147. }
  6148. }
  6149. }
  6150. /**
  6151. * @file text-track-list.js
  6152. */
  6153. /**
  6154. * The current list of {@link TextTrack} for a media file.
  6155. *
  6156. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist}
  6157. * @extends TrackList
  6158. */
  6159. class TextTrackList extends TrackList {
  6160. /**
  6161. * Add a {@link TextTrack} to the `TextTrackList`
  6162. *
  6163. * @param { import('./text-track').default } track
  6164. * The text track to add to the list.
  6165. *
  6166. * @fires TrackList#addtrack
  6167. */
  6168. addTrack(track) {
  6169. super.addTrack(track);
  6170. if (!this.queueChange_) {
  6171. this.queueChange_ = () => this.queueTrigger('change');
  6172. }
  6173. if (!this.triggerSelectedlanguagechange) {
  6174. this.triggerSelectedlanguagechange_ = () => this.trigger('selectedlanguagechange');
  6175. }
  6176. /**
  6177. * @listens TextTrack#modechange
  6178. * @fires TrackList#change
  6179. */
  6180. track.addEventListener('modechange', this.queueChange_);
  6181. const nonLanguageTextTrackKind = ['metadata', 'chapters'];
  6182. if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) {
  6183. track.addEventListener('modechange', this.triggerSelectedlanguagechange_);
  6184. }
  6185. }
  6186. removeTrack(rtrack) {
  6187. super.removeTrack(rtrack);
  6188. // manually remove the event handlers we added
  6189. if (rtrack.removeEventListener) {
  6190. if (this.queueChange_) {
  6191. rtrack.removeEventListener('modechange', this.queueChange_);
  6192. }
  6193. if (this.selectedlanguagechange_) {
  6194. rtrack.removeEventListener('modechange', this.triggerSelectedlanguagechange_);
  6195. }
  6196. }
  6197. }
  6198. }
  6199. /**
  6200. * @file html-track-element-list.js
  6201. */
  6202. /**
  6203. * The current list of {@link HtmlTrackElement}s.
  6204. */
  6205. class HtmlTrackElementList {
  6206. /**
  6207. * Create an instance of this class.
  6208. *
  6209. * @param {HtmlTrackElement[]} [tracks=[]]
  6210. * A list of `HtmlTrackElement` to instantiate the list with.
  6211. */
  6212. constructor(trackElements = []) {
  6213. this.trackElements_ = [];
  6214. /**
  6215. * @memberof HtmlTrackElementList
  6216. * @member {number} length
  6217. * The current number of `Track`s in the this Trackist.
  6218. * @instance
  6219. */
  6220. Object.defineProperty(this, 'length', {
  6221. get() {
  6222. return this.trackElements_.length;
  6223. }
  6224. });
  6225. for (let i = 0, length = trackElements.length; i < length; i++) {
  6226. this.addTrackElement_(trackElements[i]);
  6227. }
  6228. }
  6229. /**
  6230. * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList`
  6231. *
  6232. * @param {HtmlTrackElement} trackElement
  6233. * The track element to add to the list.
  6234. *
  6235. * @private
  6236. */
  6237. addTrackElement_(trackElement) {
  6238. const index = this.trackElements_.length;
  6239. if (!('' + index in this)) {
  6240. Object.defineProperty(this, index, {
  6241. get() {
  6242. return this.trackElements_[index];
  6243. }
  6244. });
  6245. }
  6246. // Do not add duplicate elements
  6247. if (this.trackElements_.indexOf(trackElement) === -1) {
  6248. this.trackElements_.push(trackElement);
  6249. }
  6250. }
  6251. /**
  6252. * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an
  6253. * {@link TextTrack}.
  6254. *
  6255. * @param {TextTrack} track
  6256. * The track associated with a track element.
  6257. *
  6258. * @return {HtmlTrackElement|undefined}
  6259. * The track element that was found or undefined.
  6260. *
  6261. * @private
  6262. */
  6263. getTrackElementByTrack_(track) {
  6264. let trackElement_;
  6265. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6266. if (track === this.trackElements_[i].track) {
  6267. trackElement_ = this.trackElements_[i];
  6268. break;
  6269. }
  6270. }
  6271. return trackElement_;
  6272. }
  6273. /**
  6274. * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList`
  6275. *
  6276. * @param {HtmlTrackElement} trackElement
  6277. * The track element to remove from the list.
  6278. *
  6279. * @private
  6280. */
  6281. removeTrackElement_(trackElement) {
  6282. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6283. if (trackElement === this.trackElements_[i]) {
  6284. if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === 'function') {
  6285. this.trackElements_[i].track.off();
  6286. }
  6287. if (typeof this.trackElements_[i].off === 'function') {
  6288. this.trackElements_[i].off();
  6289. }
  6290. this.trackElements_.splice(i, 1);
  6291. break;
  6292. }
  6293. }
  6294. }
  6295. }
  6296. /**
  6297. * @file text-track-cue-list.js
  6298. */
  6299. /**
  6300. * @typedef {Object} TextTrackCueList~TextTrackCue
  6301. *
  6302. * @property {string} id
  6303. * The unique id for this text track cue
  6304. *
  6305. * @property {number} startTime
  6306. * The start time for this text track cue
  6307. *
  6308. * @property {number} endTime
  6309. * The end time for this text track cue
  6310. *
  6311. * @property {boolean} pauseOnExit
  6312. * Pause when the end time is reached if true.
  6313. *
  6314. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue}
  6315. */
  6316. /**
  6317. * A List of TextTrackCues.
  6318. *
  6319. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist}
  6320. */
  6321. class TextTrackCueList {
  6322. /**
  6323. * Create an instance of this class..
  6324. *
  6325. * @param {Array} cues
  6326. * A list of cues to be initialized with
  6327. */
  6328. constructor(cues) {
  6329. TextTrackCueList.prototype.setCues_.call(this, cues);
  6330. /**
  6331. * @memberof TextTrackCueList
  6332. * @member {number} length
  6333. * The current number of `TextTrackCue`s in the TextTrackCueList.
  6334. * @instance
  6335. */
  6336. Object.defineProperty(this, 'length', {
  6337. get() {
  6338. return this.length_;
  6339. }
  6340. });
  6341. }
  6342. /**
  6343. * A setter for cues in this list. Creates getters
  6344. * an an index for the cues.
  6345. *
  6346. * @param {Array} cues
  6347. * An array of cues to set
  6348. *
  6349. * @private
  6350. */
  6351. setCues_(cues) {
  6352. const oldLength = this.length || 0;
  6353. let i = 0;
  6354. const l = cues.length;
  6355. this.cues_ = cues;
  6356. this.length_ = cues.length;
  6357. const defineProp = function (index) {
  6358. if (!('' + index in this)) {
  6359. Object.defineProperty(this, '' + index, {
  6360. get() {
  6361. return this.cues_[index];
  6362. }
  6363. });
  6364. }
  6365. };
  6366. if (oldLength < l) {
  6367. i = oldLength;
  6368. for (; i < l; i++) {
  6369. defineProp.call(this, i);
  6370. }
  6371. }
  6372. }
  6373. /**
  6374. * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id.
  6375. *
  6376. * @param {string} id
  6377. * The id of the cue that should be searched for.
  6378. *
  6379. * @return {TextTrackCueList~TextTrackCue|null}
  6380. * A single cue or null if none was found.
  6381. */
  6382. getCueById(id) {
  6383. let result = null;
  6384. for (let i = 0, l = this.length; i < l; i++) {
  6385. const cue = this[i];
  6386. if (cue.id === id) {
  6387. result = cue;
  6388. break;
  6389. }
  6390. }
  6391. return result;
  6392. }
  6393. }
  6394. /**
  6395. * @file track-kinds.js
  6396. */
  6397. /**
  6398. * All possible `VideoTrackKind`s
  6399. *
  6400. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind
  6401. * @typedef VideoTrack~Kind
  6402. * @enum
  6403. */
  6404. const VideoTrackKind = {
  6405. alternative: 'alternative',
  6406. captions: 'captions',
  6407. main: 'main',
  6408. sign: 'sign',
  6409. subtitles: 'subtitles',
  6410. commentary: 'commentary'
  6411. };
  6412. /**
  6413. * All possible `AudioTrackKind`s
  6414. *
  6415. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind
  6416. * @typedef AudioTrack~Kind
  6417. * @enum
  6418. */
  6419. const AudioTrackKind = {
  6420. 'alternative': 'alternative',
  6421. 'descriptions': 'descriptions',
  6422. 'main': 'main',
  6423. 'main-desc': 'main-desc',
  6424. 'translation': 'translation',
  6425. 'commentary': 'commentary'
  6426. };
  6427. /**
  6428. * All possible `TextTrackKind`s
  6429. *
  6430. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind
  6431. * @typedef TextTrack~Kind
  6432. * @enum
  6433. */
  6434. const TextTrackKind = {
  6435. subtitles: 'subtitles',
  6436. captions: 'captions',
  6437. descriptions: 'descriptions',
  6438. chapters: 'chapters',
  6439. metadata: 'metadata'
  6440. };
  6441. /**
  6442. * All possible `TextTrackMode`s
  6443. *
  6444. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
  6445. * @typedef TextTrack~Mode
  6446. * @enum
  6447. */
  6448. const TextTrackMode = {
  6449. disabled: 'disabled',
  6450. hidden: 'hidden',
  6451. showing: 'showing'
  6452. };
  6453. /**
  6454. * @file track.js
  6455. */
  6456. /**
  6457. * A Track class that contains all of the common functionality for {@link AudioTrack},
  6458. * {@link VideoTrack}, and {@link TextTrack}.
  6459. *
  6460. * > Note: This class should not be used directly
  6461. *
  6462. * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html}
  6463. * @extends EventTarget
  6464. * @abstract
  6465. */
  6466. class Track extends EventTarget$2 {
  6467. /**
  6468. * Create an instance of this class.
  6469. *
  6470. * @param {Object} [options={}]
  6471. * Object of option names and values
  6472. *
  6473. * @param {string} [options.kind='']
  6474. * A valid kind for the track type you are creating.
  6475. *
  6476. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6477. * A unique id for this AudioTrack.
  6478. *
  6479. * @param {string} [options.label='']
  6480. * The menu label for this track.
  6481. *
  6482. * @param {string} [options.language='']
  6483. * A valid two character language code.
  6484. *
  6485. * @abstract
  6486. */
  6487. constructor(options = {}) {
  6488. super();
  6489. const trackProps = {
  6490. id: options.id || 'vjs_track_' + newGUID(),
  6491. kind: options.kind || '',
  6492. language: options.language || ''
  6493. };
  6494. let label = options.label || '';
  6495. /**
  6496. * @memberof Track
  6497. * @member {string} id
  6498. * The id of this track. Cannot be changed after creation.
  6499. * @instance
  6500. *
  6501. * @readonly
  6502. */
  6503. /**
  6504. * @memberof Track
  6505. * @member {string} kind
  6506. * The kind of track that this is. Cannot be changed after creation.
  6507. * @instance
  6508. *
  6509. * @readonly
  6510. */
  6511. /**
  6512. * @memberof Track
  6513. * @member {string} language
  6514. * The two letter language code for this track. Cannot be changed after
  6515. * creation.
  6516. * @instance
  6517. *
  6518. * @readonly
  6519. */
  6520. for (const key in trackProps) {
  6521. Object.defineProperty(this, key, {
  6522. get() {
  6523. return trackProps[key];
  6524. },
  6525. set() {}
  6526. });
  6527. }
  6528. /**
  6529. * @memberof Track
  6530. * @member {string} label
  6531. * The label of this track. Cannot be changed after creation.
  6532. * @instance
  6533. *
  6534. * @fires Track#labelchange
  6535. */
  6536. Object.defineProperty(this, 'label', {
  6537. get() {
  6538. return label;
  6539. },
  6540. set(newLabel) {
  6541. if (newLabel !== label) {
  6542. label = newLabel;
  6543. /**
  6544. * An event that fires when label changes on this track.
  6545. *
  6546. * > Note: This is not part of the spec!
  6547. *
  6548. * @event Track#labelchange
  6549. * @type {Event}
  6550. */
  6551. this.trigger('labelchange');
  6552. }
  6553. }
  6554. });
  6555. }
  6556. }
  6557. /**
  6558. * @file url.js
  6559. * @module url
  6560. */
  6561. /**
  6562. * @typedef {Object} url:URLObject
  6563. *
  6564. * @property {string} protocol
  6565. * The protocol of the url that was parsed.
  6566. *
  6567. * @property {string} hostname
  6568. * The hostname of the url that was parsed.
  6569. *
  6570. * @property {string} port
  6571. * The port of the url that was parsed.
  6572. *
  6573. * @property {string} pathname
  6574. * The pathname of the url that was parsed.
  6575. *
  6576. * @property {string} search
  6577. * The search query of the url that was parsed.
  6578. *
  6579. * @property {string} hash
  6580. * The hash of the url that was parsed.
  6581. *
  6582. * @property {string} host
  6583. * The host of the url that was parsed.
  6584. */
  6585. /**
  6586. * Resolve and parse the elements of a URL.
  6587. *
  6588. * @function
  6589. * @param {String} url
  6590. * The url to parse
  6591. *
  6592. * @return {url:URLObject}
  6593. * An object of url details
  6594. */
  6595. const parseUrl = function (url) {
  6596. // This entire method can be replace with URL once we are able to drop IE11
  6597. const props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];
  6598. // add the url to an anchor and let the browser parse the URL
  6599. const a = document.createElement('a');
  6600. a.href = url;
  6601. // Copy the specific URL properties to a new object
  6602. // This is also needed for IE because the anchor loses its
  6603. // properties when it's removed from the dom
  6604. const details = {};
  6605. for (let i = 0; i < props.length; i++) {
  6606. details[props[i]] = a[props[i]];
  6607. }
  6608. // IE adds the port to the host property unlike everyone else. If
  6609. // a port identifier is added for standard ports, strip it.
  6610. if (details.protocol === 'http:') {
  6611. details.host = details.host.replace(/:80$/, '');
  6612. }
  6613. if (details.protocol === 'https:') {
  6614. details.host = details.host.replace(/:443$/, '');
  6615. }
  6616. if (!details.protocol) {
  6617. details.protocol = window.location.protocol;
  6618. }
  6619. /* istanbul ignore if */
  6620. if (!details.host) {
  6621. details.host = window.location.host;
  6622. }
  6623. return details;
  6624. };
  6625. /**
  6626. * Get absolute version of relative URL.
  6627. *
  6628. * @function
  6629. * @param {string} url
  6630. * URL to make absolute
  6631. *
  6632. * @return {string}
  6633. * Absolute URL
  6634. *
  6635. * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  6636. */
  6637. const getAbsoluteURL = function (url) {
  6638. // Check if absolute URL
  6639. if (!url.match(/^https?:\/\//)) {
  6640. // Add the url to an anchor and let the browser parse it to convert to an absolute url
  6641. const a = document.createElement('a');
  6642. a.href = url;
  6643. url = a.href;
  6644. }
  6645. return url;
  6646. };
  6647. /**
  6648. * Returns the extension of the passed file name. It will return an empty string
  6649. * if passed an invalid path.
  6650. *
  6651. * @function
  6652. * @param {string} path
  6653. * The fileName path like '/path/to/file.mp4'
  6654. *
  6655. * @return {string}
  6656. * The extension in lower case or an empty string if no
  6657. * extension could be found.
  6658. */
  6659. const getFileExtension = function (path) {
  6660. if (typeof path === 'string') {
  6661. const splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/;
  6662. const pathParts = splitPathRe.exec(path);
  6663. if (pathParts) {
  6664. return pathParts.pop().toLowerCase();
  6665. }
  6666. }
  6667. return '';
  6668. };
  6669. /**
  6670. * Returns whether the url passed is a cross domain request or not.
  6671. *
  6672. * @function
  6673. * @param {string} url
  6674. * The url to check.
  6675. *
  6676. * @param {Object} [winLoc]
  6677. * the domain to check the url against, defaults to window.location
  6678. *
  6679. * @param {string} [winLoc.protocol]
  6680. * The window location protocol defaults to window.location.protocol
  6681. *
  6682. * @param {string} [winLoc.host]
  6683. * The window location host defaults to window.location.host
  6684. *
  6685. * @return {boolean}
  6686. * Whether it is a cross domain request or not.
  6687. */
  6688. const isCrossOrigin = function (url, winLoc = window.location) {
  6689. const urlInfo = parseUrl(url);
  6690. // IE8 protocol relative urls will return ':' for protocol
  6691. const srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol;
  6692. // Check if url is for another domain/origin
  6693. // IE8 doesn't know location.origin, so we won't rely on it here
  6694. const crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host;
  6695. return crossOrigin;
  6696. };
  6697. var Url = /*#__PURE__*/Object.freeze({
  6698. __proto__: null,
  6699. parseUrl: parseUrl,
  6700. getAbsoluteURL: getAbsoluteURL,
  6701. getFileExtension: getFileExtension,
  6702. isCrossOrigin: isCrossOrigin
  6703. });
  6704. var win;
  6705. if (typeof window !== "undefined") {
  6706. win = window;
  6707. } else if (typeof commonjsGlobal !== "undefined") {
  6708. win = commonjsGlobal;
  6709. } else if (typeof self !== "undefined") {
  6710. win = self;
  6711. } else {
  6712. win = {};
  6713. }
  6714. var window_1 = win;
  6715. var _extends_1 = createCommonjsModule(function (module) {
  6716. function _extends() {
  6717. module.exports = _extends = Object.assign ? Object.assign.bind() : function (target) {
  6718. for (var i = 1; i < arguments.length; i++) {
  6719. var source = arguments[i];
  6720. for (var key in source) {
  6721. if (Object.prototype.hasOwnProperty.call(source, key)) {
  6722. target[key] = source[key];
  6723. }
  6724. }
  6725. }
  6726. return target;
  6727. }, module.exports.__esModule = true, module.exports["default"] = module.exports;
  6728. return _extends.apply(this, arguments);
  6729. }
  6730. module.exports = _extends, module.exports.__esModule = true, module.exports["default"] = module.exports;
  6731. });
  6732. var _extends$1 = unwrapExports(_extends_1);
  6733. var isFunction_1 = isFunction;
  6734. var toString = Object.prototype.toString;
  6735. function isFunction(fn) {
  6736. if (!fn) {
  6737. return false;
  6738. }
  6739. var string = toString.call(fn);
  6740. return string === '[object Function]' || typeof fn === 'function' && string !== '[object RegExp]' || typeof window !== 'undefined' && (
  6741. // IE8 and below
  6742. fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt);
  6743. }
  6744. var httpResponseHandler = function httpResponseHandler(callback, decodeResponseBody) {
  6745. if (decodeResponseBody === void 0) {
  6746. decodeResponseBody = false;
  6747. }
  6748. return function (err, response, responseBody) {
  6749. // if the XHR failed, return that error
  6750. if (err) {
  6751. callback(err);
  6752. return;
  6753. } // if the HTTP status code is 4xx or 5xx, the request also failed
  6754. if (response.statusCode >= 400 && response.statusCode <= 599) {
  6755. var cause = responseBody;
  6756. if (decodeResponseBody) {
  6757. if (window_1.TextDecoder) {
  6758. var charset = getCharset(response.headers && response.headers['content-type']);
  6759. try {
  6760. cause = new TextDecoder(charset).decode(responseBody);
  6761. } catch (e) {}
  6762. } else {
  6763. cause = String.fromCharCode.apply(null, new Uint8Array(responseBody));
  6764. }
  6765. }
  6766. callback({
  6767. cause: cause
  6768. });
  6769. return;
  6770. } // otherwise, request succeeded
  6771. callback(null, responseBody);
  6772. };
  6773. };
  6774. function getCharset(contentTypeHeader) {
  6775. if (contentTypeHeader === void 0) {
  6776. contentTypeHeader = '';
  6777. }
  6778. return contentTypeHeader.toLowerCase().split(';').reduce(function (charset, contentType) {
  6779. var _contentType$split = contentType.split('='),
  6780. type = _contentType$split[0],
  6781. value = _contentType$split[1];
  6782. if (type.trim() === 'charset') {
  6783. return value.trim();
  6784. }
  6785. return charset;
  6786. }, 'utf-8');
  6787. }
  6788. var httpHandler = httpResponseHandler;
  6789. createXHR.httpHandler = httpHandler;
  6790. /**
  6791. * @license
  6792. * slighly modified parse-headers 2.0.2 <https://github.com/kesla/parse-headers/>
  6793. * Copyright (c) 2014 David Björklund
  6794. * Available under the MIT license
  6795. * <https://github.com/kesla/parse-headers/blob/master/LICENCE>
  6796. */
  6797. var parseHeaders = function parseHeaders(headers) {
  6798. var result = {};
  6799. if (!headers) {
  6800. return result;
  6801. }
  6802. headers.trim().split('\n').forEach(function (row) {
  6803. var index = row.indexOf(':');
  6804. var key = row.slice(0, index).trim().toLowerCase();
  6805. var value = row.slice(index + 1).trim();
  6806. if (typeof result[key] === 'undefined') {
  6807. result[key] = value;
  6808. } else if (Array.isArray(result[key])) {
  6809. result[key].push(value);
  6810. } else {
  6811. result[key] = [result[key], value];
  6812. }
  6813. });
  6814. return result;
  6815. };
  6816. var lib = createXHR; // Allow use of default import syntax in TypeScript
  6817. var default_1 = createXHR;
  6818. createXHR.XMLHttpRequest = window_1.XMLHttpRequest || noop$1;
  6819. createXHR.XDomainRequest = "withCredentials" in new createXHR.XMLHttpRequest() ? createXHR.XMLHttpRequest : window_1.XDomainRequest;
  6820. forEachArray(["get", "put", "post", "patch", "head", "delete"], function (method) {
  6821. createXHR[method === "delete" ? "del" : method] = function (uri, options, callback) {
  6822. options = initParams(uri, options, callback);
  6823. options.method = method.toUpperCase();
  6824. return _createXHR(options);
  6825. };
  6826. });
  6827. function forEachArray(array, iterator) {
  6828. for (var i = 0; i < array.length; i++) {
  6829. iterator(array[i]);
  6830. }
  6831. }
  6832. function isEmpty(obj) {
  6833. for (var i in obj) {
  6834. if (obj.hasOwnProperty(i)) return false;
  6835. }
  6836. return true;
  6837. }
  6838. function initParams(uri, options, callback) {
  6839. var params = uri;
  6840. if (isFunction_1(options)) {
  6841. callback = options;
  6842. if (typeof uri === "string") {
  6843. params = {
  6844. uri: uri
  6845. };
  6846. }
  6847. } else {
  6848. params = _extends_1({}, options, {
  6849. uri: uri
  6850. });
  6851. }
  6852. params.callback = callback;
  6853. return params;
  6854. }
  6855. function createXHR(uri, options, callback) {
  6856. options = initParams(uri, options, callback);
  6857. return _createXHR(options);
  6858. }
  6859. function _createXHR(options) {
  6860. if (typeof options.callback === "undefined") {
  6861. throw new Error("callback argument missing");
  6862. }
  6863. var called = false;
  6864. var callback = function cbOnce(err, response, body) {
  6865. if (!called) {
  6866. called = true;
  6867. options.callback(err, response, body);
  6868. }
  6869. };
  6870. function readystatechange() {
  6871. if (xhr.readyState === 4) {
  6872. setTimeout(loadFunc, 0);
  6873. }
  6874. }
  6875. function getBody() {
  6876. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  6877. var body = undefined;
  6878. if (xhr.response) {
  6879. body = xhr.response;
  6880. } else {
  6881. body = xhr.responseText || getXml(xhr);
  6882. }
  6883. if (isJson) {
  6884. try {
  6885. body = JSON.parse(body);
  6886. } catch (e) {}
  6887. }
  6888. return body;
  6889. }
  6890. function errorFunc(evt) {
  6891. clearTimeout(timeoutTimer);
  6892. if (!(evt instanceof Error)) {
  6893. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error"));
  6894. }
  6895. evt.statusCode = 0;
  6896. return callback(evt, failureResponse);
  6897. } // will load the data & process the response in a special response object
  6898. function loadFunc() {
  6899. if (aborted) return;
  6900. var status;
  6901. clearTimeout(timeoutTimer);
  6902. if (options.useXDR && xhr.status === undefined) {
  6903. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  6904. status = 200;
  6905. } else {
  6906. status = xhr.status === 1223 ? 204 : xhr.status;
  6907. }
  6908. var response = failureResponse;
  6909. var err = null;
  6910. if (status !== 0) {
  6911. response = {
  6912. body: getBody(),
  6913. statusCode: status,
  6914. method: method,
  6915. headers: {},
  6916. url: uri,
  6917. rawRequest: xhr
  6918. };
  6919. if (xhr.getAllResponseHeaders) {
  6920. //remember xhr can in fact be XDR for CORS in IE
  6921. response.headers = parseHeaders(xhr.getAllResponseHeaders());
  6922. }
  6923. } else {
  6924. err = new Error("Internal XMLHttpRequest Error");
  6925. }
  6926. return callback(err, response, response.body);
  6927. }
  6928. var xhr = options.xhr || null;
  6929. if (!xhr) {
  6930. if (options.cors || options.useXDR) {
  6931. xhr = new createXHR.XDomainRequest();
  6932. } else {
  6933. xhr = new createXHR.XMLHttpRequest();
  6934. }
  6935. }
  6936. var key;
  6937. var aborted;
  6938. var uri = xhr.url = options.uri || options.url;
  6939. var method = xhr.method = options.method || "GET";
  6940. var body = options.body || options.data;
  6941. var headers = xhr.headers = options.headers || {};
  6942. var sync = !!options.sync;
  6943. var isJson = false;
  6944. var timeoutTimer;
  6945. var failureResponse = {
  6946. body: undefined,
  6947. headers: {},
  6948. statusCode: 0,
  6949. method: method,
  6950. url: uri,
  6951. rawRequest: xhr
  6952. };
  6953. if ("json" in options && options.json !== false) {
  6954. isJson = true;
  6955. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json"); //Don't override existing accept header declared by user
  6956. if (method !== "GET" && method !== "HEAD") {
  6957. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json"); //Don't override existing accept header declared by user
  6958. body = JSON.stringify(options.json === true ? body : options.json);
  6959. }
  6960. }
  6961. xhr.onreadystatechange = readystatechange;
  6962. xhr.onload = loadFunc;
  6963. xhr.onerror = errorFunc; // IE9 must have onprogress be set to a unique function.
  6964. xhr.onprogress = function () {// IE must die
  6965. };
  6966. xhr.onabort = function () {
  6967. aborted = true;
  6968. };
  6969. xhr.ontimeout = errorFunc;
  6970. xhr.open(method, uri, !sync, options.username, options.password); //has to be after open
  6971. if (!sync) {
  6972. xhr.withCredentials = !!options.withCredentials;
  6973. } // Cannot set timeout with sync request
  6974. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  6975. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  6976. if (!sync && options.timeout > 0) {
  6977. timeoutTimer = setTimeout(function () {
  6978. if (aborted) return;
  6979. aborted = true; //IE9 may still call readystatechange
  6980. xhr.abort("timeout");
  6981. var e = new Error("XMLHttpRequest timeout");
  6982. e.code = "ETIMEDOUT";
  6983. errorFunc(e);
  6984. }, options.timeout);
  6985. }
  6986. if (xhr.setRequestHeader) {
  6987. for (key in headers) {
  6988. if (headers.hasOwnProperty(key)) {
  6989. xhr.setRequestHeader(key, headers[key]);
  6990. }
  6991. }
  6992. } else if (options.headers && !isEmpty(options.headers)) {
  6993. throw new Error("Headers cannot be set on an XDomainRequest object");
  6994. }
  6995. if ("responseType" in options) {
  6996. xhr.responseType = options.responseType;
  6997. }
  6998. if ("beforeSend" in options && typeof options.beforeSend === "function") {
  6999. options.beforeSend(xhr);
  7000. } // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  7001. // XMLHttpRequest spec says to pass null as body to indicate no body
  7002. // See https://github.com/naugtur/xhr/issues/100.
  7003. xhr.send(body || null);
  7004. return xhr;
  7005. }
  7006. function getXml(xhr) {
  7007. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  7008. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  7009. try {
  7010. if (xhr.responseType === "document") {
  7011. return xhr.responseXML;
  7012. }
  7013. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror";
  7014. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  7015. return xhr.responseXML;
  7016. }
  7017. } catch (e) {}
  7018. return null;
  7019. }
  7020. function noop$1() {}
  7021. lib.default = default_1;
  7022. /**
  7023. * @file text-track.js
  7024. */
  7025. /**
  7026. * Takes a webvtt file contents and parses it into cues
  7027. *
  7028. * @param {string} srcContent
  7029. * webVTT file contents
  7030. *
  7031. * @param {TextTrack} track
  7032. * TextTrack to add cues to. Cues come from the srcContent.
  7033. *
  7034. * @private
  7035. */
  7036. const parseCues = function (srcContent, track) {
  7037. const parser = new window.WebVTT.Parser(window, window.vttjs, window.WebVTT.StringDecoder());
  7038. const errors = [];
  7039. parser.oncue = function (cue) {
  7040. track.addCue(cue);
  7041. };
  7042. parser.onparsingerror = function (error) {
  7043. errors.push(error);
  7044. };
  7045. parser.onflush = function () {
  7046. track.trigger({
  7047. type: 'loadeddata',
  7048. target: track
  7049. });
  7050. };
  7051. parser.parse(srcContent);
  7052. if (errors.length > 0) {
  7053. if (window.console && window.console.groupCollapsed) {
  7054. window.console.groupCollapsed(`Text Track parsing errors for ${track.src}`);
  7055. }
  7056. errors.forEach(error => log$1.error(error));
  7057. if (window.console && window.console.groupEnd) {
  7058. window.console.groupEnd();
  7059. }
  7060. }
  7061. parser.flush();
  7062. };
  7063. /**
  7064. * Load a `TextTrack` from a specified url.
  7065. *
  7066. * @param {string} src
  7067. * Url to load track from.
  7068. *
  7069. * @param {TextTrack} track
  7070. * Track to add cues to. Comes from the content at the end of `url`.
  7071. *
  7072. * @private
  7073. */
  7074. const loadTrack = function (src, track) {
  7075. const opts = {
  7076. uri: src
  7077. };
  7078. const crossOrigin = isCrossOrigin(src);
  7079. if (crossOrigin) {
  7080. opts.cors = crossOrigin;
  7081. }
  7082. const withCredentials = track.tech_.crossOrigin() === 'use-credentials';
  7083. if (withCredentials) {
  7084. opts.withCredentials = withCredentials;
  7085. }
  7086. lib(opts, bind_(this, function (err, response, responseBody) {
  7087. if (err) {
  7088. return log$1.error(err, response);
  7089. }
  7090. track.loaded_ = true;
  7091. // Make sure that vttjs has loaded, otherwise, wait till it finished loading
  7092. // NOTE: this is only used for the alt/video.novtt.js build
  7093. if (typeof window.WebVTT !== 'function') {
  7094. if (track.tech_) {
  7095. // to prevent use before define eslint error, we define loadHandler
  7096. // as a let here
  7097. track.tech_.any(['vttjsloaded', 'vttjserror'], event => {
  7098. if (event.type === 'vttjserror') {
  7099. log$1.error(`vttjs failed to load, stopping trying to process ${track.src}`);
  7100. return;
  7101. }
  7102. return parseCues(responseBody, track);
  7103. });
  7104. }
  7105. } else {
  7106. parseCues(responseBody, track);
  7107. }
  7108. }));
  7109. };
  7110. /**
  7111. * A representation of a single `TextTrack`.
  7112. *
  7113. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack}
  7114. * @extends Track
  7115. */
  7116. class TextTrack extends Track {
  7117. /**
  7118. * Create an instance of this class.
  7119. *
  7120. * @param {Object} options={}
  7121. * Object of option names and values
  7122. *
  7123. * @param { import('../tech/tech').default } options.tech
  7124. * A reference to the tech that owns this TextTrack.
  7125. *
  7126. * @param {TextTrack~Kind} [options.kind='subtitles']
  7127. * A valid text track kind.
  7128. *
  7129. * @param {TextTrack~Mode} [options.mode='disabled']
  7130. * A valid text track mode.
  7131. *
  7132. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7133. * A unique id for this TextTrack.
  7134. *
  7135. * @param {string} [options.label='']
  7136. * The menu label for this track.
  7137. *
  7138. * @param {string} [options.language='']
  7139. * A valid two character language code.
  7140. *
  7141. * @param {string} [options.srclang='']
  7142. * A valid two character language code. An alternative, but deprioritized
  7143. * version of `options.language`
  7144. *
  7145. * @param {string} [options.src]
  7146. * A url to TextTrack cues.
  7147. *
  7148. * @param {boolean} [options.default]
  7149. * If this track should default to on or off.
  7150. */
  7151. constructor(options = {}) {
  7152. if (!options.tech) {
  7153. throw new Error('A tech was not provided.');
  7154. }
  7155. const settings = merge$2(options, {
  7156. kind: TextTrackKind[options.kind] || 'subtitles',
  7157. language: options.language || options.srclang || ''
  7158. });
  7159. let mode = TextTrackMode[settings.mode] || 'disabled';
  7160. const default_ = settings.default;
  7161. if (settings.kind === 'metadata' || settings.kind === 'chapters') {
  7162. mode = 'hidden';
  7163. }
  7164. super(settings);
  7165. this.tech_ = settings.tech;
  7166. this.cues_ = [];
  7167. this.activeCues_ = [];
  7168. this.preload_ = this.tech_.preloadTextTracks !== false;
  7169. const cues = new TextTrackCueList(this.cues_);
  7170. const activeCues = new TextTrackCueList(this.activeCues_);
  7171. let changed = false;
  7172. this.timeupdateHandler = bind_(this, function (event = {}) {
  7173. if (this.tech_.isDisposed()) {
  7174. return;
  7175. }
  7176. if (!this.tech_.isReady_) {
  7177. if (event.type !== 'timeupdate') {
  7178. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7179. }
  7180. return;
  7181. }
  7182. // Accessing this.activeCues for the side-effects of updating itself
  7183. // due to its nature as a getter function. Do not remove or cues will
  7184. // stop updating!
  7185. // Use the setter to prevent deletion from uglify (pure_getters rule)
  7186. this.activeCues = this.activeCues;
  7187. if (changed) {
  7188. this.trigger('cuechange');
  7189. changed = false;
  7190. }
  7191. if (event.type !== 'timeupdate') {
  7192. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7193. }
  7194. });
  7195. const disposeHandler = () => {
  7196. this.stopTracking();
  7197. };
  7198. this.tech_.one('dispose', disposeHandler);
  7199. if (mode !== 'disabled') {
  7200. this.startTracking();
  7201. }
  7202. Object.defineProperties(this, {
  7203. /**
  7204. * @memberof TextTrack
  7205. * @member {boolean} default
  7206. * If this track was set to be on or off by default. Cannot be changed after
  7207. * creation.
  7208. * @instance
  7209. *
  7210. * @readonly
  7211. */
  7212. default: {
  7213. get() {
  7214. return default_;
  7215. },
  7216. set() {}
  7217. },
  7218. /**
  7219. * @memberof TextTrack
  7220. * @member {string} mode
  7221. * Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will
  7222. * not be set if setting to an invalid mode.
  7223. * @instance
  7224. *
  7225. * @fires TextTrack#modechange
  7226. */
  7227. mode: {
  7228. get() {
  7229. return mode;
  7230. },
  7231. set(newMode) {
  7232. if (!TextTrackMode[newMode]) {
  7233. return;
  7234. }
  7235. if (mode === newMode) {
  7236. return;
  7237. }
  7238. mode = newMode;
  7239. if (!this.preload_ && mode !== 'disabled' && this.cues.length === 0) {
  7240. // On-demand load.
  7241. loadTrack(this.src, this);
  7242. }
  7243. this.stopTracking();
  7244. if (mode !== 'disabled') {
  7245. this.startTracking();
  7246. }
  7247. /**
  7248. * An event that fires when mode changes on this track. This allows
  7249. * the TextTrackList that holds this track to act accordingly.
  7250. *
  7251. * > Note: This is not part of the spec!
  7252. *
  7253. * @event TextTrack#modechange
  7254. * @type {Event}
  7255. */
  7256. this.trigger('modechange');
  7257. }
  7258. },
  7259. /**
  7260. * @memberof TextTrack
  7261. * @member {TextTrackCueList} cues
  7262. * The text track cue list for this TextTrack.
  7263. * @instance
  7264. */
  7265. cues: {
  7266. get() {
  7267. if (!this.loaded_) {
  7268. return null;
  7269. }
  7270. return cues;
  7271. },
  7272. set() {}
  7273. },
  7274. /**
  7275. * @memberof TextTrack
  7276. * @member {TextTrackCueList} activeCues
  7277. * The list text track cues that are currently active for this TextTrack.
  7278. * @instance
  7279. */
  7280. activeCues: {
  7281. get() {
  7282. if (!this.loaded_) {
  7283. return null;
  7284. }
  7285. // nothing to do
  7286. if (this.cues.length === 0) {
  7287. return activeCues;
  7288. }
  7289. const ct = this.tech_.currentTime();
  7290. const active = [];
  7291. for (let i = 0, l = this.cues.length; i < l; i++) {
  7292. const cue = this.cues[i];
  7293. if (cue.startTime <= ct && cue.endTime >= ct) {
  7294. active.push(cue);
  7295. }
  7296. }
  7297. changed = false;
  7298. if (active.length !== this.activeCues_.length) {
  7299. changed = true;
  7300. } else {
  7301. for (let i = 0; i < active.length; i++) {
  7302. if (this.activeCues_.indexOf(active[i]) === -1) {
  7303. changed = true;
  7304. }
  7305. }
  7306. }
  7307. this.activeCues_ = active;
  7308. activeCues.setCues_(this.activeCues_);
  7309. return activeCues;
  7310. },
  7311. // /!\ Keep this setter empty (see the timeupdate handler above)
  7312. set() {}
  7313. }
  7314. });
  7315. if (settings.src) {
  7316. this.src = settings.src;
  7317. if (!this.preload_) {
  7318. // Tracks will load on-demand.
  7319. // Act like we're loaded for other purposes.
  7320. this.loaded_ = true;
  7321. }
  7322. if (this.preload_ || settings.kind !== 'subtitles' && settings.kind !== 'captions') {
  7323. loadTrack(this.src, this);
  7324. }
  7325. } else {
  7326. this.loaded_ = true;
  7327. }
  7328. }
  7329. startTracking() {
  7330. // More precise cues based on requestVideoFrameCallback with a requestAnimationFram fallback
  7331. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7332. // Also listen to timeupdate in case rVFC/rAF stops (window in background, audio in video el)
  7333. this.tech_.on('timeupdate', this.timeupdateHandler);
  7334. }
  7335. stopTracking() {
  7336. if (this.rvf_) {
  7337. this.tech_.cancelVideoFrameCallback(this.rvf_);
  7338. this.rvf_ = undefined;
  7339. }
  7340. this.tech_.off('timeupdate', this.timeupdateHandler);
  7341. }
  7342. /**
  7343. * Add a cue to the internal list of cues.
  7344. *
  7345. * @param {TextTrack~Cue} cue
  7346. * The cue to add to our internal list
  7347. */
  7348. addCue(originalCue) {
  7349. let cue = originalCue;
  7350. if (window.vttjs && !(originalCue instanceof window.vttjs.VTTCue)) {
  7351. cue = new window.vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text);
  7352. for (const prop in originalCue) {
  7353. if (!(prop in cue)) {
  7354. cue[prop] = originalCue[prop];
  7355. }
  7356. }
  7357. // make sure that `id` is copied over
  7358. cue.id = originalCue.id;
  7359. cue.originalCue_ = originalCue;
  7360. }
  7361. const tracks = this.tech_.textTracks();
  7362. for (let i = 0; i < tracks.length; i++) {
  7363. if (tracks[i] !== this) {
  7364. tracks[i].removeCue(cue);
  7365. }
  7366. }
  7367. this.cues_.push(cue);
  7368. this.cues.setCues_(this.cues_);
  7369. }
  7370. /**
  7371. * Remove a cue from our internal list
  7372. *
  7373. * @param {TextTrack~Cue} removeCue
  7374. * The cue to remove from our internal list
  7375. */
  7376. removeCue(removeCue) {
  7377. let i = this.cues_.length;
  7378. while (i--) {
  7379. const cue = this.cues_[i];
  7380. if (cue === removeCue || cue.originalCue_ && cue.originalCue_ === removeCue) {
  7381. this.cues_.splice(i, 1);
  7382. this.cues.setCues_(this.cues_);
  7383. break;
  7384. }
  7385. }
  7386. }
  7387. }
  7388. /**
  7389. * cuechange - One or more cues in the track have become active or stopped being active.
  7390. */
  7391. TextTrack.prototype.allowedEvents_ = {
  7392. cuechange: 'cuechange'
  7393. };
  7394. /**
  7395. * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList}
  7396. * only one `AudioTrack` in the list will be enabled at a time.
  7397. *
  7398. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack}
  7399. * @extends Track
  7400. */
  7401. class AudioTrack extends Track {
  7402. /**
  7403. * Create an instance of this class.
  7404. *
  7405. * @param {Object} [options={}]
  7406. * Object of option names and values
  7407. *
  7408. * @param {AudioTrack~Kind} [options.kind='']
  7409. * A valid audio track kind
  7410. *
  7411. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7412. * A unique id for this AudioTrack.
  7413. *
  7414. * @param {string} [options.label='']
  7415. * The menu label for this track.
  7416. *
  7417. * @param {string} [options.language='']
  7418. * A valid two character language code.
  7419. *
  7420. * @param {boolean} [options.enabled]
  7421. * If this track is the one that is currently playing. If this track is part of
  7422. * an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled.
  7423. */
  7424. constructor(options = {}) {
  7425. const settings = merge$2(options, {
  7426. kind: AudioTrackKind[options.kind] || ''
  7427. });
  7428. super(settings);
  7429. let enabled = false;
  7430. /**
  7431. * @memberof AudioTrack
  7432. * @member {boolean} enabled
  7433. * If this `AudioTrack` is enabled or not. When setting this will
  7434. * fire {@link AudioTrack#enabledchange} if the state of enabled is changed.
  7435. * @instance
  7436. *
  7437. * @fires VideoTrack#selectedchange
  7438. */
  7439. Object.defineProperty(this, 'enabled', {
  7440. get() {
  7441. return enabled;
  7442. },
  7443. set(newEnabled) {
  7444. // an invalid or unchanged value
  7445. if (typeof newEnabled !== 'boolean' || newEnabled === enabled) {
  7446. return;
  7447. }
  7448. enabled = newEnabled;
  7449. /**
  7450. * An event that fires when enabled changes on this track. This allows
  7451. * the AudioTrackList that holds this track to act accordingly.
  7452. *
  7453. * > Note: This is not part of the spec! Native tracks will do
  7454. * this internally without an event.
  7455. *
  7456. * @event AudioTrack#enabledchange
  7457. * @type {Event}
  7458. */
  7459. this.trigger('enabledchange');
  7460. }
  7461. });
  7462. // if the user sets this track to selected then
  7463. // set selected to that true value otherwise
  7464. // we keep it false
  7465. if (settings.enabled) {
  7466. this.enabled = settings.enabled;
  7467. }
  7468. this.loaded_ = true;
  7469. }
  7470. }
  7471. /**
  7472. * A representation of a single `VideoTrack`.
  7473. *
  7474. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack}
  7475. * @extends Track
  7476. */
  7477. class VideoTrack extends Track {
  7478. /**
  7479. * Create an instance of this class.
  7480. *
  7481. * @param {Object} [options={}]
  7482. * Object of option names and values
  7483. *
  7484. * @param {string} [options.kind='']
  7485. * A valid {@link VideoTrack~Kind}
  7486. *
  7487. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7488. * A unique id for this AudioTrack.
  7489. *
  7490. * @param {string} [options.label='']
  7491. * The menu label for this track.
  7492. *
  7493. * @param {string} [options.language='']
  7494. * A valid two character language code.
  7495. *
  7496. * @param {boolean} [options.selected]
  7497. * If this track is the one that is currently playing.
  7498. */
  7499. constructor(options = {}) {
  7500. const settings = merge$2(options, {
  7501. kind: VideoTrackKind[options.kind] || ''
  7502. });
  7503. super(settings);
  7504. let selected = false;
  7505. /**
  7506. * @memberof VideoTrack
  7507. * @member {boolean} selected
  7508. * If this `VideoTrack` is selected or not. When setting this will
  7509. * fire {@link VideoTrack#selectedchange} if the state of selected changed.
  7510. * @instance
  7511. *
  7512. * @fires VideoTrack#selectedchange
  7513. */
  7514. Object.defineProperty(this, 'selected', {
  7515. get() {
  7516. return selected;
  7517. },
  7518. set(newSelected) {
  7519. // an invalid or unchanged value
  7520. if (typeof newSelected !== 'boolean' || newSelected === selected) {
  7521. return;
  7522. }
  7523. selected = newSelected;
  7524. /**
  7525. * An event that fires when selected changes on this track. This allows
  7526. * the VideoTrackList that holds this track to act accordingly.
  7527. *
  7528. * > Note: This is not part of the spec! Native tracks will do
  7529. * this internally without an event.
  7530. *
  7531. * @event VideoTrack#selectedchange
  7532. * @type {Event}
  7533. */
  7534. this.trigger('selectedchange');
  7535. }
  7536. });
  7537. // if the user sets this track to selected then
  7538. // set selected to that true value otherwise
  7539. // we keep it false
  7540. if (settings.selected) {
  7541. this.selected = settings.selected;
  7542. }
  7543. }
  7544. }
  7545. /**
  7546. * @file html-track-element.js
  7547. */
  7548. /**
  7549. * A single track represented in the DOM.
  7550. *
  7551. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement}
  7552. * @extends EventTarget
  7553. */
  7554. class HTMLTrackElement extends EventTarget$2 {
  7555. /**
  7556. * Create an instance of this class.
  7557. *
  7558. * @param {Object} options={}
  7559. * Object of option names and values
  7560. *
  7561. * @param { import('../tech/tech').default } options.tech
  7562. * A reference to the tech that owns this HTMLTrackElement.
  7563. *
  7564. * @param {TextTrack~Kind} [options.kind='subtitles']
  7565. * A valid text track kind.
  7566. *
  7567. * @param {TextTrack~Mode} [options.mode='disabled']
  7568. * A valid text track mode.
  7569. *
  7570. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7571. * A unique id for this TextTrack.
  7572. *
  7573. * @param {string} [options.label='']
  7574. * The menu label for this track.
  7575. *
  7576. * @param {string} [options.language='']
  7577. * A valid two character language code.
  7578. *
  7579. * @param {string} [options.srclang='']
  7580. * A valid two character language code. An alternative, but deprioritized
  7581. * version of `options.language`
  7582. *
  7583. * @param {string} [options.src]
  7584. * A url to TextTrack cues.
  7585. *
  7586. * @param {boolean} [options.default]
  7587. * If this track should default to on or off.
  7588. */
  7589. constructor(options = {}) {
  7590. super();
  7591. let readyState;
  7592. const track = new TextTrack(options);
  7593. this.kind = track.kind;
  7594. this.src = track.src;
  7595. this.srclang = track.language;
  7596. this.label = track.label;
  7597. this.default = track.default;
  7598. Object.defineProperties(this, {
  7599. /**
  7600. * @memberof HTMLTrackElement
  7601. * @member {HTMLTrackElement~ReadyState} readyState
  7602. * The current ready state of the track element.
  7603. * @instance
  7604. */
  7605. readyState: {
  7606. get() {
  7607. return readyState;
  7608. }
  7609. },
  7610. /**
  7611. * @memberof HTMLTrackElement
  7612. * @member {TextTrack} track
  7613. * The underlying TextTrack object.
  7614. * @instance
  7615. *
  7616. */
  7617. track: {
  7618. get() {
  7619. return track;
  7620. }
  7621. }
  7622. });
  7623. readyState = HTMLTrackElement.NONE;
  7624. /**
  7625. * @listens TextTrack#loadeddata
  7626. * @fires HTMLTrackElement#load
  7627. */
  7628. track.addEventListener('loadeddata', () => {
  7629. readyState = HTMLTrackElement.LOADED;
  7630. this.trigger({
  7631. type: 'load',
  7632. target: this
  7633. });
  7634. });
  7635. }
  7636. }
  7637. HTMLTrackElement.prototype.allowedEvents_ = {
  7638. load: 'load'
  7639. };
  7640. /**
  7641. * The text track not loaded state.
  7642. *
  7643. * @type {number}
  7644. * @static
  7645. */
  7646. HTMLTrackElement.NONE = 0;
  7647. /**
  7648. * The text track loading state.
  7649. *
  7650. * @type {number}
  7651. * @static
  7652. */
  7653. HTMLTrackElement.LOADING = 1;
  7654. /**
  7655. * The text track loaded state.
  7656. *
  7657. * @type {number}
  7658. * @static
  7659. */
  7660. HTMLTrackElement.LOADED = 2;
  7661. /**
  7662. * The text track failed to load state.
  7663. *
  7664. * @type {number}
  7665. * @static
  7666. */
  7667. HTMLTrackElement.ERROR = 3;
  7668. /*
  7669. * This file contains all track properties that are used in
  7670. * player.js, tech.js, html5.js and possibly other techs in the future.
  7671. */
  7672. const NORMAL = {
  7673. audio: {
  7674. ListClass: AudioTrackList,
  7675. TrackClass: AudioTrack,
  7676. capitalName: 'Audio'
  7677. },
  7678. video: {
  7679. ListClass: VideoTrackList,
  7680. TrackClass: VideoTrack,
  7681. capitalName: 'Video'
  7682. },
  7683. text: {
  7684. ListClass: TextTrackList,
  7685. TrackClass: TextTrack,
  7686. capitalName: 'Text'
  7687. }
  7688. };
  7689. Object.keys(NORMAL).forEach(function (type) {
  7690. NORMAL[type].getterName = `${type}Tracks`;
  7691. NORMAL[type].privateName = `${type}Tracks_`;
  7692. });
  7693. const REMOTE = {
  7694. remoteText: {
  7695. ListClass: TextTrackList,
  7696. TrackClass: TextTrack,
  7697. capitalName: 'RemoteText',
  7698. getterName: 'remoteTextTracks',
  7699. privateName: 'remoteTextTracks_'
  7700. },
  7701. remoteTextEl: {
  7702. ListClass: HtmlTrackElementList,
  7703. TrackClass: HTMLTrackElement,
  7704. capitalName: 'RemoteTextTrackEls',
  7705. getterName: 'remoteTextTrackEls',
  7706. privateName: 'remoteTextTrackEls_'
  7707. }
  7708. };
  7709. const ALL = Object.assign({}, NORMAL, REMOTE);
  7710. REMOTE.names = Object.keys(REMOTE);
  7711. NORMAL.names = Object.keys(NORMAL);
  7712. ALL.names = [].concat(REMOTE.names).concat(NORMAL.names);
  7713. var vtt = {};
  7714. /**
  7715. * @file tech.js
  7716. */
  7717. /**
  7718. * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
  7719. * that just contains the src url alone.
  7720. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
  7721. * `var SourceString = 'http://example.com/some-video.mp4';`
  7722. *
  7723. * @typedef {Object|string} Tech~SourceObject
  7724. *
  7725. * @property {string} src
  7726. * The url to the source
  7727. *
  7728. * @property {string} type
  7729. * The mime type of the source
  7730. */
  7731. /**
  7732. * A function used by {@link Tech} to create a new {@link TextTrack}.
  7733. *
  7734. * @private
  7735. *
  7736. * @param {Tech} self
  7737. * An instance of the Tech class.
  7738. *
  7739. * @param {string} kind
  7740. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  7741. *
  7742. * @param {string} [label]
  7743. * Label to identify the text track
  7744. *
  7745. * @param {string} [language]
  7746. * Two letter language abbreviation
  7747. *
  7748. * @param {Object} [options={}]
  7749. * An object with additional text track options
  7750. *
  7751. * @return {TextTrack}
  7752. * The text track that was created.
  7753. */
  7754. function createTrackHelper(self, kind, label, language, options = {}) {
  7755. const tracks = self.textTracks();
  7756. options.kind = kind;
  7757. if (label) {
  7758. options.label = label;
  7759. }
  7760. if (language) {
  7761. options.language = language;
  7762. }
  7763. options.tech = self;
  7764. const track = new ALL.text.TrackClass(options);
  7765. tracks.addTrack(track);
  7766. return track;
  7767. }
  7768. /**
  7769. * This is the base class for media playback technology controllers, such as
  7770. * {@link HTML5}
  7771. *
  7772. * @extends Component
  7773. */
  7774. class Tech extends Component$1 {
  7775. /**
  7776. * Create an instance of this Tech.
  7777. *
  7778. * @param {Object} [options]
  7779. * The key/value store of player options.
  7780. *
  7781. * @param {Function} [ready]
  7782. * Callback function to call when the `HTML5` Tech is ready.
  7783. */
  7784. constructor(options = {}, ready = function () {}) {
  7785. // we don't want the tech to report user activity automatically.
  7786. // This is done manually in addControlsListeners
  7787. options.reportTouchActivity = false;
  7788. super(null, options, ready);
  7789. this.onDurationChange_ = e => this.onDurationChange(e);
  7790. this.trackProgress_ = e => this.trackProgress(e);
  7791. this.trackCurrentTime_ = e => this.trackCurrentTime(e);
  7792. this.stopTrackingCurrentTime_ = e => this.stopTrackingCurrentTime(e);
  7793. this.disposeSourceHandler_ = e => this.disposeSourceHandler(e);
  7794. this.queuedHanders_ = new Set();
  7795. // keep track of whether the current source has played at all to
  7796. // implement a very limited played()
  7797. this.hasStarted_ = false;
  7798. this.on('playing', function () {
  7799. this.hasStarted_ = true;
  7800. });
  7801. this.on('loadstart', function () {
  7802. this.hasStarted_ = false;
  7803. });
  7804. ALL.names.forEach(name => {
  7805. const props = ALL[name];
  7806. if (options && options[props.getterName]) {
  7807. this[props.privateName] = options[props.getterName];
  7808. }
  7809. });
  7810. // Manually track progress in cases where the browser/tech doesn't report it.
  7811. if (!this.featuresProgressEvents) {
  7812. this.manualProgressOn();
  7813. }
  7814. // Manually track timeupdates in cases where the browser/tech doesn't report it.
  7815. if (!this.featuresTimeupdateEvents) {
  7816. this.manualTimeUpdatesOn();
  7817. }
  7818. ['Text', 'Audio', 'Video'].forEach(track => {
  7819. if (options[`native${track}Tracks`] === false) {
  7820. this[`featuresNative${track}Tracks`] = false;
  7821. }
  7822. });
  7823. if (options.nativeCaptions === false || options.nativeTextTracks === false) {
  7824. this.featuresNativeTextTracks = false;
  7825. } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
  7826. this.featuresNativeTextTracks = true;
  7827. }
  7828. if (!this.featuresNativeTextTracks) {
  7829. this.emulateTextTracks();
  7830. }
  7831. this.preloadTextTracks = options.preloadTextTracks !== false;
  7832. this.autoRemoteTextTracks_ = new ALL.text.ListClass();
  7833. this.initTrackListeners();
  7834. // Turn on component tap events only if not using native controls
  7835. if (!options.nativeControlsForTouch) {
  7836. this.emitTapEvents();
  7837. }
  7838. if (this.constructor) {
  7839. this.name_ = this.constructor.name || 'Unknown Tech';
  7840. }
  7841. }
  7842. /**
  7843. * A special function to trigger source set in a way that will allow player
  7844. * to re-trigger if the player or tech are not ready yet.
  7845. *
  7846. * @fires Tech#sourceset
  7847. * @param {string} src The source string at the time of the source changing.
  7848. */
  7849. triggerSourceset(src) {
  7850. if (!this.isReady_) {
  7851. // on initial ready we have to trigger source set
  7852. // 1ms after ready so that player can watch for it.
  7853. this.one('ready', () => this.setTimeout(() => this.triggerSourceset(src), 1));
  7854. }
  7855. /**
  7856. * Fired when the source is set on the tech causing the media element
  7857. * to reload.
  7858. *
  7859. * @see {@link Player#event:sourceset}
  7860. * @event Tech#sourceset
  7861. * @type {Event}
  7862. */
  7863. this.trigger({
  7864. src,
  7865. type: 'sourceset'
  7866. });
  7867. }
  7868. /* Fallbacks for unsupported event types
  7869. ================================================================================ */
  7870. /**
  7871. * Polyfill the `progress` event for browsers that don't support it natively.
  7872. *
  7873. * @see {@link Tech#trackProgress}
  7874. */
  7875. manualProgressOn() {
  7876. this.on('durationchange', this.onDurationChange_);
  7877. this.manualProgress = true;
  7878. // Trigger progress watching when a source begins loading
  7879. this.one('ready', this.trackProgress_);
  7880. }
  7881. /**
  7882. * Turn off the polyfill for `progress` events that was created in
  7883. * {@link Tech#manualProgressOn}
  7884. */
  7885. manualProgressOff() {
  7886. this.manualProgress = false;
  7887. this.stopTrackingProgress();
  7888. this.off('durationchange', this.onDurationChange_);
  7889. }
  7890. /**
  7891. * This is used to trigger a `progress` event when the buffered percent changes. It
  7892. * sets an interval function that will be called every 500 milliseconds to check if the
  7893. * buffer end percent has changed.
  7894. *
  7895. * > This function is called by {@link Tech#manualProgressOn}
  7896. *
  7897. * @param {Event} event
  7898. * The `ready` event that caused this to run.
  7899. *
  7900. * @listens Tech#ready
  7901. * @fires Tech#progress
  7902. */
  7903. trackProgress(event) {
  7904. this.stopTrackingProgress();
  7905. this.progressInterval = this.setInterval(bind_(this, function () {
  7906. // Don't trigger unless buffered amount is greater than last time
  7907. const numBufferedPercent = this.bufferedPercent();
  7908. if (this.bufferedPercent_ !== numBufferedPercent) {
  7909. /**
  7910. * See {@link Player#progress}
  7911. *
  7912. * @event Tech#progress
  7913. * @type {Event}
  7914. */
  7915. this.trigger('progress');
  7916. }
  7917. this.bufferedPercent_ = numBufferedPercent;
  7918. if (numBufferedPercent === 1) {
  7919. this.stopTrackingProgress();
  7920. }
  7921. }), 500);
  7922. }
  7923. /**
  7924. * Update our internal duration on a `durationchange` event by calling
  7925. * {@link Tech#duration}.
  7926. *
  7927. * @param {Event} event
  7928. * The `durationchange` event that caused this to run.
  7929. *
  7930. * @listens Tech#durationchange
  7931. */
  7932. onDurationChange(event) {
  7933. this.duration_ = this.duration();
  7934. }
  7935. /**
  7936. * Get and create a `TimeRange` object for buffering.
  7937. *
  7938. * @return { import('../utils/time').TimeRange }
  7939. * The time range object that was created.
  7940. */
  7941. buffered() {
  7942. return createTimeRanges$1(0, 0);
  7943. }
  7944. /**
  7945. * Get the percentage of the current video that is currently buffered.
  7946. *
  7947. * @return {number}
  7948. * A number from 0 to 1 that represents the decimal percentage of the
  7949. * video that is buffered.
  7950. *
  7951. */
  7952. bufferedPercent() {
  7953. return bufferedPercent(this.buffered(), this.duration_);
  7954. }
  7955. /**
  7956. * Turn off the polyfill for `progress` events that was created in
  7957. * {@link Tech#manualProgressOn}
  7958. * Stop manually tracking progress events by clearing the interval that was set in
  7959. * {@link Tech#trackProgress}.
  7960. */
  7961. stopTrackingProgress() {
  7962. this.clearInterval(this.progressInterval);
  7963. }
  7964. /**
  7965. * Polyfill the `timeupdate` event for browsers that don't support it.
  7966. *
  7967. * @see {@link Tech#trackCurrentTime}
  7968. */
  7969. manualTimeUpdatesOn() {
  7970. this.manualTimeUpdates = true;
  7971. this.on('play', this.trackCurrentTime_);
  7972. this.on('pause', this.stopTrackingCurrentTime_);
  7973. }
  7974. /**
  7975. * Turn off the polyfill for `timeupdate` events that was created in
  7976. * {@link Tech#manualTimeUpdatesOn}
  7977. */
  7978. manualTimeUpdatesOff() {
  7979. this.manualTimeUpdates = false;
  7980. this.stopTrackingCurrentTime();
  7981. this.off('play', this.trackCurrentTime_);
  7982. this.off('pause', this.stopTrackingCurrentTime_);
  7983. }
  7984. /**
  7985. * Sets up an interval function to track current time and trigger `timeupdate` every
  7986. * 250 milliseconds.
  7987. *
  7988. * @listens Tech#play
  7989. * @triggers Tech#timeupdate
  7990. */
  7991. trackCurrentTime() {
  7992. if (this.currentTimeInterval) {
  7993. this.stopTrackingCurrentTime();
  7994. }
  7995. this.currentTimeInterval = this.setInterval(function () {
  7996. /**
  7997. * Triggered at an interval of 250ms to indicated that time is passing in the video.
  7998. *
  7999. * @event Tech#timeupdate
  8000. * @type {Event}
  8001. */
  8002. this.trigger({
  8003. type: 'timeupdate',
  8004. target: this,
  8005. manuallyTriggered: true
  8006. });
  8007. // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  8008. }, 250);
  8009. }
  8010. /**
  8011. * Stop the interval function created in {@link Tech#trackCurrentTime} so that the
  8012. * `timeupdate` event is no longer triggered.
  8013. *
  8014. * @listens {Tech#pause}
  8015. */
  8016. stopTrackingCurrentTime() {
  8017. this.clearInterval(this.currentTimeInterval);
  8018. // #1002 - if the video ends right before the next timeupdate would happen,
  8019. // the progress bar won't make it all the way to the end
  8020. this.trigger({
  8021. type: 'timeupdate',
  8022. target: this,
  8023. manuallyTriggered: true
  8024. });
  8025. }
  8026. /**
  8027. * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},
  8028. * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.
  8029. *
  8030. * @fires Component#dispose
  8031. */
  8032. dispose() {
  8033. // clear out all tracks because we can't reuse them between techs
  8034. this.clearTracks(NORMAL.names);
  8035. // Turn off any manual progress or timeupdate tracking
  8036. if (this.manualProgress) {
  8037. this.manualProgressOff();
  8038. }
  8039. if (this.manualTimeUpdates) {
  8040. this.manualTimeUpdatesOff();
  8041. }
  8042. super.dispose();
  8043. }
  8044. /**
  8045. * Clear out a single `TrackList` or an array of `TrackLists` given their names.
  8046. *
  8047. * > Note: Techs without source handlers should call this between sources for `video`
  8048. * & `audio` tracks. You don't want to use them between tracks!
  8049. *
  8050. * @param {string[]|string} types
  8051. * TrackList names to clear, valid names are `video`, `audio`, and
  8052. * `text`.
  8053. */
  8054. clearTracks(types) {
  8055. types = [].concat(types);
  8056. // clear out all tracks because we can't reuse them between techs
  8057. types.forEach(type => {
  8058. const list = this[`${type}Tracks`]() || [];
  8059. let i = list.length;
  8060. while (i--) {
  8061. const track = list[i];
  8062. if (type === 'text') {
  8063. this.removeRemoteTextTrack(track);
  8064. }
  8065. list.removeTrack(track);
  8066. }
  8067. });
  8068. }
  8069. /**
  8070. * Remove any TextTracks added via addRemoteTextTrack that are
  8071. * flagged for automatic garbage collection
  8072. */
  8073. cleanupAutoTextTracks() {
  8074. const list = this.autoRemoteTextTracks_ || [];
  8075. let i = list.length;
  8076. while (i--) {
  8077. const track = list[i];
  8078. this.removeRemoteTextTrack(track);
  8079. }
  8080. }
  8081. /**
  8082. * Reset the tech, which will removes all sources and reset the internal readyState.
  8083. *
  8084. * @abstract
  8085. */
  8086. reset() {}
  8087. /**
  8088. * Get the value of `crossOrigin` from the tech.
  8089. *
  8090. * @abstract
  8091. *
  8092. * @see {Html5#crossOrigin}
  8093. */
  8094. crossOrigin() {}
  8095. /**
  8096. * Set the value of `crossOrigin` on the tech.
  8097. *
  8098. * @abstract
  8099. *
  8100. * @param {string} crossOrigin the crossOrigin value
  8101. * @see {Html5#setCrossOrigin}
  8102. */
  8103. setCrossOrigin() {}
  8104. /**
  8105. * Get or set an error on the Tech.
  8106. *
  8107. * @param {MediaError} [err]
  8108. * Error to set on the Tech
  8109. *
  8110. * @return {MediaError|null}
  8111. * The current error object on the tech, or null if there isn't one.
  8112. */
  8113. error(err) {
  8114. if (err !== undefined) {
  8115. this.error_ = new MediaError(err);
  8116. this.trigger('error');
  8117. }
  8118. return this.error_;
  8119. }
  8120. /**
  8121. * Returns the `TimeRange`s that have been played through for the current source.
  8122. *
  8123. * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.
  8124. * It only checks whether the source has played at all or not.
  8125. *
  8126. * @return {TimeRange}
  8127. * - A single time range if this video has played
  8128. * - An empty set of ranges if not.
  8129. */
  8130. played() {
  8131. if (this.hasStarted_) {
  8132. return createTimeRanges$1(0, 0);
  8133. }
  8134. return createTimeRanges$1();
  8135. }
  8136. /**
  8137. * Start playback
  8138. *
  8139. * @abstract
  8140. *
  8141. * @see {Html5#play}
  8142. */
  8143. play() {}
  8144. /**
  8145. * Set whether we are scrubbing or not
  8146. *
  8147. * @abstract
  8148. * @param {boolean} _isScrubbing
  8149. * - true for we are currently scrubbing
  8150. * - false for we are no longer scrubbing
  8151. *
  8152. * @see {Html5#setScrubbing}
  8153. */
  8154. setScrubbing(_isScrubbing) {}
  8155. /**
  8156. * Get whether we are scrubbing or not
  8157. *
  8158. * @abstract
  8159. *
  8160. * @see {Html5#scrubbing}
  8161. */
  8162. scrubbing() {}
  8163. /**
  8164. * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was
  8165. * previously called.
  8166. *
  8167. * @param {number} _seconds
  8168. * Set the current time of the media to this.
  8169. * @fires Tech#timeupdate
  8170. */
  8171. setCurrentTime(_seconds) {
  8172. // improve the accuracy of manual timeupdates
  8173. if (this.manualTimeUpdates) {
  8174. /**
  8175. * A manual `timeupdate` event.
  8176. *
  8177. * @event Tech#timeupdate
  8178. * @type {Event}
  8179. */
  8180. this.trigger({
  8181. type: 'timeupdate',
  8182. target: this,
  8183. manuallyTriggered: true
  8184. });
  8185. }
  8186. }
  8187. /**
  8188. * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
  8189. * {@link TextTrackList} events.
  8190. *
  8191. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
  8192. *
  8193. * @fires Tech#audiotrackchange
  8194. * @fires Tech#videotrackchange
  8195. * @fires Tech#texttrackchange
  8196. */
  8197. initTrackListeners() {
  8198. /**
  8199. * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
  8200. *
  8201. * @event Tech#audiotrackchange
  8202. * @type {Event}
  8203. */
  8204. /**
  8205. * Triggered when tracks are added or removed on the Tech {@link VideoTrackList}
  8206. *
  8207. * @event Tech#videotrackchange
  8208. * @type {Event}
  8209. */
  8210. /**
  8211. * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
  8212. *
  8213. * @event Tech#texttrackchange
  8214. * @type {Event}
  8215. */
  8216. NORMAL.names.forEach(name => {
  8217. const props = NORMAL[name];
  8218. const trackListChanges = () => {
  8219. this.trigger(`${name}trackchange`);
  8220. };
  8221. const tracks = this[props.getterName]();
  8222. tracks.addEventListener('removetrack', trackListChanges);
  8223. tracks.addEventListener('addtrack', trackListChanges);
  8224. this.on('dispose', () => {
  8225. tracks.removeEventListener('removetrack', trackListChanges);
  8226. tracks.removeEventListener('addtrack', trackListChanges);
  8227. });
  8228. });
  8229. }
  8230. /**
  8231. * Emulate TextTracks using vtt.js if necessary
  8232. *
  8233. * @fires Tech#vttjsloaded
  8234. * @fires Tech#vttjserror
  8235. */
  8236. addWebVttScript_() {
  8237. if (window.WebVTT) {
  8238. return;
  8239. }
  8240. // Initially, Tech.el_ is a child of a dummy-div wait until the Component system
  8241. // signals that the Tech is ready at which point Tech.el_ is part of the DOM
  8242. // before inserting the WebVTT script
  8243. if (document.body.contains(this.el())) {
  8244. // load via require if available and vtt.js script location was not passed in
  8245. // as an option. novtt builds will turn the above require call into an empty object
  8246. // which will cause this if check to always fail.
  8247. if (!this.options_['vtt.js'] && isPlain(vtt) && Object.keys(vtt).length > 0) {
  8248. this.trigger('vttjsloaded');
  8249. return;
  8250. }
  8251. // load vtt.js via the script location option or the cdn of no location was
  8252. // passed in
  8253. const script = document.createElement('script');
  8254. script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';
  8255. script.onload = () => {
  8256. /**
  8257. * Fired when vtt.js is loaded.
  8258. *
  8259. * @event Tech#vttjsloaded
  8260. * @type {Event}
  8261. */
  8262. this.trigger('vttjsloaded');
  8263. };
  8264. script.onerror = () => {
  8265. /**
  8266. * Fired when vtt.js was not loaded due to an error
  8267. *
  8268. * @event Tech#vttjsloaded
  8269. * @type {Event}
  8270. */
  8271. this.trigger('vttjserror');
  8272. };
  8273. this.on('dispose', () => {
  8274. script.onload = null;
  8275. script.onerror = null;
  8276. });
  8277. // but have not loaded yet and we set it to true before the inject so that
  8278. // we don't overwrite the injected window.WebVTT if it loads right away
  8279. window.WebVTT = true;
  8280. this.el().parentNode.appendChild(script);
  8281. } else {
  8282. this.ready(this.addWebVttScript_);
  8283. }
  8284. }
  8285. /**
  8286. * Emulate texttracks
  8287. *
  8288. */
  8289. emulateTextTracks() {
  8290. const tracks = this.textTracks();
  8291. const remoteTracks = this.remoteTextTracks();
  8292. const handleAddTrack = e => tracks.addTrack(e.track);
  8293. const handleRemoveTrack = e => tracks.removeTrack(e.track);
  8294. remoteTracks.on('addtrack', handleAddTrack);
  8295. remoteTracks.on('removetrack', handleRemoveTrack);
  8296. this.addWebVttScript_();
  8297. const updateDisplay = () => this.trigger('texttrackchange');
  8298. const textTracksChanges = () => {
  8299. updateDisplay();
  8300. for (let i = 0; i < tracks.length; i++) {
  8301. const track = tracks[i];
  8302. track.removeEventListener('cuechange', updateDisplay);
  8303. if (track.mode === 'showing') {
  8304. track.addEventListener('cuechange', updateDisplay);
  8305. }
  8306. }
  8307. };
  8308. textTracksChanges();
  8309. tracks.addEventListener('change', textTracksChanges);
  8310. tracks.addEventListener('addtrack', textTracksChanges);
  8311. tracks.addEventListener('removetrack', textTracksChanges);
  8312. this.on('dispose', function () {
  8313. remoteTracks.off('addtrack', handleAddTrack);
  8314. remoteTracks.off('removetrack', handleRemoveTrack);
  8315. tracks.removeEventListener('change', textTracksChanges);
  8316. tracks.removeEventListener('addtrack', textTracksChanges);
  8317. tracks.removeEventListener('removetrack', textTracksChanges);
  8318. for (let i = 0; i < tracks.length; i++) {
  8319. const track = tracks[i];
  8320. track.removeEventListener('cuechange', updateDisplay);
  8321. }
  8322. });
  8323. }
  8324. /**
  8325. * Create and returns a remote {@link TextTrack} object.
  8326. *
  8327. * @param {string} kind
  8328. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  8329. *
  8330. * @param {string} [label]
  8331. * Label to identify the text track
  8332. *
  8333. * @param {string} [language]
  8334. * Two letter language abbreviation
  8335. *
  8336. * @return {TextTrack}
  8337. * The TextTrack that gets created.
  8338. */
  8339. addTextTrack(kind, label, language) {
  8340. if (!kind) {
  8341. throw new Error('TextTrack kind is required but was not provided');
  8342. }
  8343. return createTrackHelper(this, kind, label, language);
  8344. }
  8345. /**
  8346. * Create an emulated TextTrack for use by addRemoteTextTrack
  8347. *
  8348. * This is intended to be overridden by classes that inherit from
  8349. * Tech in order to create native or custom TextTracks.
  8350. *
  8351. * @param {Object} options
  8352. * The object should contain the options to initialize the TextTrack with.
  8353. *
  8354. * @param {string} [options.kind]
  8355. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  8356. *
  8357. * @param {string} [options.label].
  8358. * Label to identify the text track
  8359. *
  8360. * @param {string} [options.language]
  8361. * Two letter language abbreviation.
  8362. *
  8363. * @return {HTMLTrackElement}
  8364. * The track element that gets created.
  8365. */
  8366. createRemoteTextTrack(options) {
  8367. const track = merge$2(options, {
  8368. tech: this
  8369. });
  8370. return new REMOTE.remoteTextEl.TrackClass(track);
  8371. }
  8372. /**
  8373. * Creates a remote text track object and returns an html track element.
  8374. *
  8375. * > Note: This can be an emulated {@link HTMLTrackElement} or a native one.
  8376. *
  8377. * @param {Object} options
  8378. * See {@link Tech#createRemoteTextTrack} for more detailed properties.
  8379. *
  8380. * @param {boolean} [manualCleanup=false]
  8381. * - When false: the TextTrack will be automatically removed from the video
  8382. * element whenever the source changes
  8383. * - When True: The TextTrack will have to be cleaned up manually
  8384. *
  8385. * @return {HTMLTrackElement}
  8386. * An Html Track Element.
  8387. *
  8388. */
  8389. addRemoteTextTrack(options = {}, manualCleanup) {
  8390. const htmlTrackElement = this.createRemoteTextTrack(options);
  8391. if (typeof manualCleanup !== 'boolean') {
  8392. manualCleanup = false;
  8393. }
  8394. // store HTMLTrackElement and TextTrack to remote list
  8395. this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
  8396. this.remoteTextTracks().addTrack(htmlTrackElement.track);
  8397. if (manualCleanup === false) {
  8398. // create the TextTrackList if it doesn't exist
  8399. this.ready(() => this.autoRemoteTextTracks_.addTrack(htmlTrackElement.track));
  8400. }
  8401. return htmlTrackElement;
  8402. }
  8403. /**
  8404. * Remove a remote text track from the remote `TextTrackList`.
  8405. *
  8406. * @param {TextTrack} track
  8407. * `TextTrack` to remove from the `TextTrackList`
  8408. */
  8409. removeRemoteTextTrack(track) {
  8410. const trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);
  8411. // remove HTMLTrackElement and TextTrack from remote list
  8412. this.remoteTextTrackEls().removeTrackElement_(trackElement);
  8413. this.remoteTextTracks().removeTrack(track);
  8414. this.autoRemoteTextTracks_.removeTrack(track);
  8415. }
  8416. /**
  8417. * Gets available media playback quality metrics as specified by the W3C's Media
  8418. * Playback Quality API.
  8419. *
  8420. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  8421. *
  8422. * @return {Object}
  8423. * An object with supported media playback quality metrics
  8424. *
  8425. * @abstract
  8426. */
  8427. getVideoPlaybackQuality() {
  8428. return {};
  8429. }
  8430. /**
  8431. * Attempt to create a floating video window always on top of other windows
  8432. * so that users may continue consuming media while they interact with other
  8433. * content sites, or applications on their device.
  8434. *
  8435. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  8436. *
  8437. * @return {Promise|undefined}
  8438. * A promise with a Picture-in-Picture window if the browser supports
  8439. * Promises (or one was passed in as an option). It returns undefined
  8440. * otherwise.
  8441. *
  8442. * @abstract
  8443. */
  8444. requestPictureInPicture() {
  8445. return Promise.reject();
  8446. }
  8447. /**
  8448. * A method to check for the value of the 'disablePictureInPicture' <video> property.
  8449. * Defaults to true, as it should be considered disabled if the tech does not support pip
  8450. *
  8451. * @abstract
  8452. */
  8453. disablePictureInPicture() {
  8454. return true;
  8455. }
  8456. /**
  8457. * A method to set or unset the 'disablePictureInPicture' <video> property.
  8458. *
  8459. * @abstract
  8460. */
  8461. setDisablePictureInPicture() {}
  8462. /**
  8463. * A fallback implementation of requestVideoFrameCallback using requestAnimationFrame
  8464. *
  8465. * @param {function} cb
  8466. * @return {number} request id
  8467. */
  8468. requestVideoFrameCallback(cb) {
  8469. const id = newGUID();
  8470. if (!this.isReady_ || this.paused()) {
  8471. this.queuedHanders_.add(id);
  8472. this.one('playing', () => {
  8473. if (this.queuedHanders_.has(id)) {
  8474. this.queuedHanders_.delete(id);
  8475. cb();
  8476. }
  8477. });
  8478. } else {
  8479. this.requestNamedAnimationFrame(id, cb);
  8480. }
  8481. return id;
  8482. }
  8483. /**
  8484. * A fallback implementation of cancelVideoFrameCallback
  8485. *
  8486. * @param {number} id id of callback to be cancelled
  8487. */
  8488. cancelVideoFrameCallback(id) {
  8489. if (this.queuedHanders_.has(id)) {
  8490. this.queuedHanders_.delete(id);
  8491. } else {
  8492. this.cancelNamedAnimationFrame(id);
  8493. }
  8494. }
  8495. /**
  8496. * A method to set a poster from a `Tech`.
  8497. *
  8498. * @abstract
  8499. */
  8500. setPoster() {}
  8501. /**
  8502. * A method to check for the presence of the 'playsinline' <video> attribute.
  8503. *
  8504. * @abstract
  8505. */
  8506. playsinline() {}
  8507. /**
  8508. * A method to set or unset the 'playsinline' <video> attribute.
  8509. *
  8510. * @abstract
  8511. */
  8512. setPlaysinline() {}
  8513. /**
  8514. * Attempt to force override of native audio tracks.
  8515. *
  8516. * @param {boolean} override - If set to true native audio will be overridden,
  8517. * otherwise native audio will potentially be used.
  8518. *
  8519. * @abstract
  8520. */
  8521. overrideNativeAudioTracks(override) {}
  8522. /**
  8523. * Attempt to force override of native video tracks.
  8524. *
  8525. * @param {boolean} override - If set to true native video will be overridden,
  8526. * otherwise native video will potentially be used.
  8527. *
  8528. * @abstract
  8529. */
  8530. overrideNativeVideoTracks(override) {}
  8531. /**
  8532. * Check if the tech can support the given mime-type.
  8533. *
  8534. * The base tech does not support any type, but source handlers might
  8535. * overwrite this.
  8536. *
  8537. * @param {string} _type
  8538. * The mimetype to check for support
  8539. *
  8540. * @return {string}
  8541. * 'probably', 'maybe', or empty string
  8542. *
  8543. * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}
  8544. *
  8545. * @abstract
  8546. */
  8547. canPlayType(_type) {
  8548. return '';
  8549. }
  8550. /**
  8551. * Check if the type is supported by this tech.
  8552. *
  8553. * The base tech does not support any type, but source handlers might
  8554. * overwrite this.
  8555. *
  8556. * @param {string} _type
  8557. * The media type to check
  8558. * @return {string} Returns the native video element's response
  8559. */
  8560. static canPlayType(_type) {
  8561. return '';
  8562. }
  8563. /**
  8564. * Check if the tech can support the given source
  8565. *
  8566. * @param {Object} srcObj
  8567. * The source object
  8568. * @param {Object} options
  8569. * The options passed to the tech
  8570. * @return {string} 'probably', 'maybe', or '' (empty string)
  8571. */
  8572. static canPlaySource(srcObj, options) {
  8573. return Tech.canPlayType(srcObj.type);
  8574. }
  8575. /*
  8576. * Return whether the argument is a Tech or not.
  8577. * Can be passed either a Class like `Html5` or a instance like `player.tech_`
  8578. *
  8579. * @param {Object} component
  8580. * The item to check
  8581. *
  8582. * @return {boolean}
  8583. * Whether it is a tech or not
  8584. * - True if it is a tech
  8585. * - False if it is not
  8586. */
  8587. static isTech(component) {
  8588. return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
  8589. }
  8590. /**
  8591. * Registers a `Tech` into a shared list for videojs.
  8592. *
  8593. * @param {string} name
  8594. * Name of the `Tech` to register.
  8595. *
  8596. * @param {Object} tech
  8597. * The `Tech` class to register.
  8598. */
  8599. static registerTech(name, tech) {
  8600. if (!Tech.techs_) {
  8601. Tech.techs_ = {};
  8602. }
  8603. if (!Tech.isTech(tech)) {
  8604. throw new Error(`Tech ${name} must be a Tech`);
  8605. }
  8606. if (!Tech.canPlayType) {
  8607. throw new Error('Techs must have a static canPlayType method on them');
  8608. }
  8609. if (!Tech.canPlaySource) {
  8610. throw new Error('Techs must have a static canPlaySource method on them');
  8611. }
  8612. name = toTitleCase$1(name);
  8613. Tech.techs_[name] = tech;
  8614. Tech.techs_[toLowerCase(name)] = tech;
  8615. if (name !== 'Tech') {
  8616. // camel case the techName for use in techOrder
  8617. Tech.defaultTechOrder_.push(name);
  8618. }
  8619. return tech;
  8620. }
  8621. /**
  8622. * Get a `Tech` from the shared list by name.
  8623. *
  8624. * @param {string} name
  8625. * `camelCase` or `TitleCase` name of the Tech to get
  8626. *
  8627. * @return {Tech|undefined}
  8628. * The `Tech` or undefined if there was no tech with the name requested.
  8629. */
  8630. static getTech(name) {
  8631. if (!name) {
  8632. return;
  8633. }
  8634. if (Tech.techs_ && Tech.techs_[name]) {
  8635. return Tech.techs_[name];
  8636. }
  8637. name = toTitleCase$1(name);
  8638. if (window && window.videojs && window.videojs[name]) {
  8639. log$1.warn(`The ${name} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`);
  8640. return window.videojs[name];
  8641. }
  8642. }
  8643. }
  8644. /**
  8645. * Get the {@link VideoTrackList}
  8646. *
  8647. * @returns {VideoTrackList}
  8648. * @method Tech.prototype.videoTracks
  8649. */
  8650. /**
  8651. * Get the {@link AudioTrackList}
  8652. *
  8653. * @returns {AudioTrackList}
  8654. * @method Tech.prototype.audioTracks
  8655. */
  8656. /**
  8657. * Get the {@link TextTrackList}
  8658. *
  8659. * @returns {TextTrackList}
  8660. * @method Tech.prototype.textTracks
  8661. */
  8662. /**
  8663. * Get the remote element {@link TextTrackList}
  8664. *
  8665. * @returns {TextTrackList}
  8666. * @method Tech.prototype.remoteTextTracks
  8667. */
  8668. /**
  8669. * Get the remote element {@link HtmlTrackElementList}
  8670. *
  8671. * @returns {HtmlTrackElementList}
  8672. * @method Tech.prototype.remoteTextTrackEls
  8673. */
  8674. ALL.names.forEach(function (name) {
  8675. const props = ALL[name];
  8676. Tech.prototype[props.getterName] = function () {
  8677. this[props.privateName] = this[props.privateName] || new props.ListClass();
  8678. return this[props.privateName];
  8679. };
  8680. });
  8681. /**
  8682. * List of associated text tracks
  8683. *
  8684. * @type {TextTrackList}
  8685. * @private
  8686. * @property Tech#textTracks_
  8687. */
  8688. /**
  8689. * List of associated audio tracks.
  8690. *
  8691. * @type {AudioTrackList}
  8692. * @private
  8693. * @property Tech#audioTracks_
  8694. */
  8695. /**
  8696. * List of associated video tracks.
  8697. *
  8698. * @type {VideoTrackList}
  8699. * @private
  8700. * @property Tech#videoTracks_
  8701. */
  8702. /**
  8703. * Boolean indicating whether the `Tech` supports volume control.
  8704. *
  8705. * @type {boolean}
  8706. * @default
  8707. */
  8708. Tech.prototype.featuresVolumeControl = true;
  8709. /**
  8710. * Boolean indicating whether the `Tech` supports muting volume.
  8711. *
  8712. * @type {boolean}
  8713. * @default
  8714. */
  8715. Tech.prototype.featuresMuteControl = true;
  8716. /**
  8717. * Boolean indicating whether the `Tech` supports fullscreen resize control.
  8718. * Resizing plugins using request fullscreen reloads the plugin
  8719. *
  8720. * @type {boolean}
  8721. * @default
  8722. */
  8723. Tech.prototype.featuresFullscreenResize = false;
  8724. /**
  8725. * Boolean indicating whether the `Tech` supports changing the speed at which the video
  8726. * plays. Examples:
  8727. * - Set player to play 2x (twice) as fast
  8728. * - Set player to play 0.5x (half) as fast
  8729. *
  8730. * @type {boolean}
  8731. * @default
  8732. */
  8733. Tech.prototype.featuresPlaybackRate = false;
  8734. /**
  8735. * Boolean indicating whether the `Tech` supports the `progress` event.
  8736. * This will be used to determine if {@link Tech#manualProgressOn} should be called.
  8737. *
  8738. * @type {boolean}
  8739. * @default
  8740. */
  8741. Tech.prototype.featuresProgressEvents = false;
  8742. /**
  8743. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  8744. *
  8745. * A tech should set this to `true` and then use {@link Tech#triggerSourceset}
  8746. * to trigger a {@link Tech#event:sourceset} at the earliest time after getting
  8747. * a new source.
  8748. *
  8749. * @type {boolean}
  8750. * @default
  8751. */
  8752. Tech.prototype.featuresSourceset = false;
  8753. /**
  8754. * Boolean indicating whether the `Tech` supports the `timeupdate` event.
  8755. * This will be used to determine if {@link Tech#manualTimeUpdates} should be called.
  8756. *
  8757. * @type {boolean}
  8758. * @default
  8759. */
  8760. Tech.prototype.featuresTimeupdateEvents = false;
  8761. /**
  8762. * Boolean indicating whether the `Tech` supports the native `TextTrack`s.
  8763. * This will help us integrate with native `TextTrack`s if the browser supports them.
  8764. *
  8765. * @type {boolean}
  8766. * @default
  8767. */
  8768. Tech.prototype.featuresNativeTextTracks = false;
  8769. /**
  8770. * Boolean indicating whether the `Tech` supports `requestVideoFrameCallback`.
  8771. *
  8772. * @type {boolean}
  8773. * @default
  8774. */
  8775. Tech.prototype.featuresVideoFrameCallback = false;
  8776. /**
  8777. * A functional mixin for techs that want to use the Source Handler pattern.
  8778. * Source handlers are scripts for handling specific formats.
  8779. * The source handler pattern is used for adaptive formats (HLS, DASH) that
  8780. * manually load video data and feed it into a Source Buffer (Media Source Extensions)
  8781. * Example: `Tech.withSourceHandlers.call(MyTech);`
  8782. *
  8783. * @param {Tech} _Tech
  8784. * The tech to add source handler functions to.
  8785. *
  8786. * @mixes Tech~SourceHandlerAdditions
  8787. */
  8788. Tech.withSourceHandlers = function (_Tech) {
  8789. /**
  8790. * Register a source handler
  8791. *
  8792. * @param {Function} handler
  8793. * The source handler class
  8794. *
  8795. * @param {number} [index]
  8796. * Register it at the following index
  8797. */
  8798. _Tech.registerSourceHandler = function (handler, index) {
  8799. let handlers = _Tech.sourceHandlers;
  8800. if (!handlers) {
  8801. handlers = _Tech.sourceHandlers = [];
  8802. }
  8803. if (index === undefined) {
  8804. // add to the end of the list
  8805. index = handlers.length;
  8806. }
  8807. handlers.splice(index, 0, handler);
  8808. };
  8809. /**
  8810. * Check if the tech can support the given type. Also checks the
  8811. * Techs sourceHandlers.
  8812. *
  8813. * @param {string} type
  8814. * The mimetype to check.
  8815. *
  8816. * @return {string}
  8817. * 'probably', 'maybe', or '' (empty string)
  8818. */
  8819. _Tech.canPlayType = function (type) {
  8820. const handlers = _Tech.sourceHandlers || [];
  8821. let can;
  8822. for (let i = 0; i < handlers.length; i++) {
  8823. can = handlers[i].canPlayType(type);
  8824. if (can) {
  8825. return can;
  8826. }
  8827. }
  8828. return '';
  8829. };
  8830. /**
  8831. * Returns the first source handler that supports the source.
  8832. *
  8833. * TODO: Answer question: should 'probably' be prioritized over 'maybe'
  8834. *
  8835. * @param {Tech~SourceObject} source
  8836. * The source object
  8837. *
  8838. * @param {Object} options
  8839. * The options passed to the tech
  8840. *
  8841. * @return {SourceHandler|null}
  8842. * The first source handler that supports the source or null if
  8843. * no SourceHandler supports the source
  8844. */
  8845. _Tech.selectSourceHandler = function (source, options) {
  8846. const handlers = _Tech.sourceHandlers || [];
  8847. let can;
  8848. for (let i = 0; i < handlers.length; i++) {
  8849. can = handlers[i].canHandleSource(source, options);
  8850. if (can) {
  8851. return handlers[i];
  8852. }
  8853. }
  8854. return null;
  8855. };
  8856. /**
  8857. * Check if the tech can support the given source.
  8858. *
  8859. * @param {Tech~SourceObject} srcObj
  8860. * The source object
  8861. *
  8862. * @param {Object} options
  8863. * The options passed to the tech
  8864. *
  8865. * @return {string}
  8866. * 'probably', 'maybe', or '' (empty string)
  8867. */
  8868. _Tech.canPlaySource = function (srcObj, options) {
  8869. const sh = _Tech.selectSourceHandler(srcObj, options);
  8870. if (sh) {
  8871. return sh.canHandleSource(srcObj, options);
  8872. }
  8873. return '';
  8874. };
  8875. /**
  8876. * When using a source handler, prefer its implementation of
  8877. * any function normally provided by the tech.
  8878. */
  8879. const deferrable = ['seekable', 'seeking', 'duration'];
  8880. /**
  8881. * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable
  8882. * function if it exists, with a fallback to the Techs seekable function.
  8883. *
  8884. * @method _Tech.seekable
  8885. */
  8886. /**
  8887. * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration
  8888. * function if it exists, otherwise it will fallback to the techs duration function.
  8889. *
  8890. * @method _Tech.duration
  8891. */
  8892. deferrable.forEach(function (fnName) {
  8893. const originalFn = this[fnName];
  8894. if (typeof originalFn !== 'function') {
  8895. return;
  8896. }
  8897. this[fnName] = function () {
  8898. if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
  8899. return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
  8900. }
  8901. return originalFn.apply(this, arguments);
  8902. };
  8903. }, _Tech.prototype);
  8904. /**
  8905. * Create a function for setting the source using a source object
  8906. * and source handlers.
  8907. * Should never be called unless a source handler was found.
  8908. *
  8909. * @param {Tech~SourceObject} source
  8910. * A source object with src and type keys
  8911. */
  8912. _Tech.prototype.setSource = function (source) {
  8913. let sh = _Tech.selectSourceHandler(source, this.options_);
  8914. if (!sh) {
  8915. // Fall back to a native source handler when unsupported sources are
  8916. // deliberately set
  8917. if (_Tech.nativeSourceHandler) {
  8918. sh = _Tech.nativeSourceHandler;
  8919. } else {
  8920. log$1.error('No source handler found for the current source.');
  8921. }
  8922. }
  8923. // Dispose any existing source handler
  8924. this.disposeSourceHandler();
  8925. this.off('dispose', this.disposeSourceHandler_);
  8926. if (sh !== _Tech.nativeSourceHandler) {
  8927. this.currentSource_ = source;
  8928. }
  8929. this.sourceHandler_ = sh.handleSource(source, this, this.options_);
  8930. this.one('dispose', this.disposeSourceHandler_);
  8931. };
  8932. /**
  8933. * Clean up any existing SourceHandlers and listeners when the Tech is disposed.
  8934. *
  8935. * @listens Tech#dispose
  8936. */
  8937. _Tech.prototype.disposeSourceHandler = function () {
  8938. // if we have a source and get another one
  8939. // then we are loading something new
  8940. // than clear all of our current tracks
  8941. if (this.currentSource_) {
  8942. this.clearTracks(['audio', 'video']);
  8943. this.currentSource_ = null;
  8944. }
  8945. // always clean up auto-text tracks
  8946. this.cleanupAutoTextTracks();
  8947. if (this.sourceHandler_) {
  8948. if (this.sourceHandler_.dispose) {
  8949. this.sourceHandler_.dispose();
  8950. }
  8951. this.sourceHandler_ = null;
  8952. }
  8953. };
  8954. };
  8955. // The base Tech class needs to be registered as a Component. It is the only
  8956. // Tech that can be registered as a Component.
  8957. Component$1.registerComponent('Tech', Tech);
  8958. Tech.registerTech('Tech', Tech);
  8959. /**
  8960. * A list of techs that should be added to techOrder on Players
  8961. *
  8962. * @private
  8963. */
  8964. Tech.defaultTechOrder_ = [];
  8965. /**
  8966. * @file middleware.js
  8967. * @module middleware
  8968. */
  8969. const middlewares = {};
  8970. const middlewareInstances = {};
  8971. const TERMINATOR = {};
  8972. /**
  8973. * A middleware object is a plain JavaScript object that has methods that
  8974. * match the {@link Tech} methods found in the lists of allowed
  8975. * {@link module:middleware.allowedGetters|getters},
  8976. * {@link module:middleware.allowedSetters|setters}, and
  8977. * {@link module:middleware.allowedMediators|mediators}.
  8978. *
  8979. * @typedef {Object} MiddlewareObject
  8980. */
  8981. /**
  8982. * A middleware factory function that should return a
  8983. * {@link module:middleware~MiddlewareObject|MiddlewareObject}.
  8984. *
  8985. * This factory will be called for each player when needed, with the player
  8986. * passed in as an argument.
  8987. *
  8988. * @callback MiddlewareFactory
  8989. * @param { import('../player').default } player
  8990. * A Video.js player.
  8991. */
  8992. /**
  8993. * Define a middleware that the player should use by way of a factory function
  8994. * that returns a middleware object.
  8995. *
  8996. * @param {string} type
  8997. * The MIME type to match or `"*"` for all MIME types.
  8998. *
  8999. * @param {MiddlewareFactory} middleware
  9000. * A middleware factory function that will be executed for
  9001. * matching types.
  9002. */
  9003. function use(type, middleware) {
  9004. middlewares[type] = middlewares[type] || [];
  9005. middlewares[type].push(middleware);
  9006. }
  9007. /**
  9008. * Asynchronously sets a source using middleware by recursing through any
  9009. * matching middlewares and calling `setSource` on each, passing along the
  9010. * previous returned value each time.
  9011. *
  9012. * @param { import('../player').default } player
  9013. * A {@link Player} instance.
  9014. *
  9015. * @param {Tech~SourceObject} src
  9016. * A source object.
  9017. *
  9018. * @param {Function}
  9019. * The next middleware to run.
  9020. */
  9021. function setSource(player, src, next) {
  9022. player.setTimeout(() => setSourceHelper(src, middlewares[src.type], next, player), 1);
  9023. }
  9024. /**
  9025. * When the tech is set, passes the tech to each middleware's `setTech` method.
  9026. *
  9027. * @param {Object[]} middleware
  9028. * An array of middleware instances.
  9029. *
  9030. * @param { import('../tech/tech').default } tech
  9031. * A Video.js tech.
  9032. */
  9033. function setTech(middleware, tech) {
  9034. middleware.forEach(mw => mw.setTech && mw.setTech(tech));
  9035. }
  9036. /**
  9037. * Calls a getter on the tech first, through each middleware
  9038. * from right to left to the player.
  9039. *
  9040. * @param {Object[]} middleware
  9041. * An array of middleware instances.
  9042. *
  9043. * @param { import('../tech/tech').default } tech
  9044. * The current tech.
  9045. *
  9046. * @param {string} method
  9047. * A method name.
  9048. *
  9049. * @return {*}
  9050. * The final value from the tech after middleware has intercepted it.
  9051. */
  9052. function get(middleware, tech, method) {
  9053. return middleware.reduceRight(middlewareIterator(method), tech[method]());
  9054. }
  9055. /**
  9056. * Takes the argument given to the player and calls the setter method on each
  9057. * middleware from left to right to the tech.
  9058. *
  9059. * @param {Object[]} middleware
  9060. * An array of middleware instances.
  9061. *
  9062. * @param { import('../tech/tech').default } tech
  9063. * The current tech.
  9064. *
  9065. * @param {string} method
  9066. * A method name.
  9067. *
  9068. * @param {*} arg
  9069. * The value to set on the tech.
  9070. *
  9071. * @return {*}
  9072. * The return value of the `method` of the `tech`.
  9073. */
  9074. function set(middleware, tech, method, arg) {
  9075. return tech[method](middleware.reduce(middlewareIterator(method), arg));
  9076. }
  9077. /**
  9078. * Takes the argument given to the player and calls the `call` version of the
  9079. * method on each middleware from left to right.
  9080. *
  9081. * Then, call the passed in method on the tech and return the result unchanged
  9082. * back to the player, through middleware, this time from right to left.
  9083. *
  9084. * @param {Object[]} middleware
  9085. * An array of middleware instances.
  9086. *
  9087. * @param { import('../tech/tech').default } tech
  9088. * The current tech.
  9089. *
  9090. * @param {string} method
  9091. * A method name.
  9092. *
  9093. * @param {*} arg
  9094. * The value to set on the tech.
  9095. *
  9096. * @return {*}
  9097. * The return value of the `method` of the `tech`, regardless of the
  9098. * return values of middlewares.
  9099. */
  9100. function mediate(middleware, tech, method, arg = null) {
  9101. const callMethod = 'call' + toTitleCase$1(method);
  9102. const middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
  9103. const terminated = middlewareValue === TERMINATOR;
  9104. // deprecated. The `null` return value should instead return TERMINATOR to
  9105. // prevent confusion if a techs method actually returns null.
  9106. const returnValue = terminated ? null : tech[method](middlewareValue);
  9107. executeRight(middleware, method, returnValue, terminated);
  9108. return returnValue;
  9109. }
  9110. /**
  9111. * Enumeration of allowed getters where the keys are method names.
  9112. *
  9113. * @type {Object}
  9114. */
  9115. const allowedGetters = {
  9116. buffered: 1,
  9117. currentTime: 1,
  9118. duration: 1,
  9119. muted: 1,
  9120. played: 1,
  9121. paused: 1,
  9122. seekable: 1,
  9123. volume: 1,
  9124. ended: 1
  9125. };
  9126. /**
  9127. * Enumeration of allowed setters where the keys are method names.
  9128. *
  9129. * @type {Object}
  9130. */
  9131. const allowedSetters = {
  9132. setCurrentTime: 1,
  9133. setMuted: 1,
  9134. setVolume: 1
  9135. };
  9136. /**
  9137. * Enumeration of allowed mediators where the keys are method names.
  9138. *
  9139. * @type {Object}
  9140. */
  9141. const allowedMediators = {
  9142. play: 1,
  9143. pause: 1
  9144. };
  9145. function middlewareIterator(method) {
  9146. return (value, mw) => {
  9147. // if the previous middleware terminated, pass along the termination
  9148. if (value === TERMINATOR) {
  9149. return TERMINATOR;
  9150. }
  9151. if (mw[method]) {
  9152. return mw[method](value);
  9153. }
  9154. return value;
  9155. };
  9156. }
  9157. function executeRight(mws, method, value, terminated) {
  9158. for (let i = mws.length - 1; i >= 0; i--) {
  9159. const mw = mws[i];
  9160. if (mw[method]) {
  9161. mw[method](terminated, value);
  9162. }
  9163. }
  9164. }
  9165. /**
  9166. * Clear the middleware cache for a player.
  9167. *
  9168. * @param { import('../player').default } player
  9169. * A {@link Player} instance.
  9170. */
  9171. function clearCacheForPlayer(player) {
  9172. middlewareInstances[player.id()] = null;
  9173. }
  9174. /**
  9175. * {
  9176. * [playerId]: [[mwFactory, mwInstance], ...]
  9177. * }
  9178. *
  9179. * @private
  9180. */
  9181. function getOrCreateFactory(player, mwFactory) {
  9182. const mws = middlewareInstances[player.id()];
  9183. let mw = null;
  9184. if (mws === undefined || mws === null) {
  9185. mw = mwFactory(player);
  9186. middlewareInstances[player.id()] = [[mwFactory, mw]];
  9187. return mw;
  9188. }
  9189. for (let i = 0; i < mws.length; i++) {
  9190. const [mwf, mwi] = mws[i];
  9191. if (mwf !== mwFactory) {
  9192. continue;
  9193. }
  9194. mw = mwi;
  9195. }
  9196. if (mw === null) {
  9197. mw = mwFactory(player);
  9198. mws.push([mwFactory, mw]);
  9199. }
  9200. return mw;
  9201. }
  9202. function setSourceHelper(src = {}, middleware = [], next, player, acc = [], lastRun = false) {
  9203. const [mwFactory, ...mwrest] = middleware;
  9204. // if mwFactory is a string, then we're at a fork in the road
  9205. if (typeof mwFactory === 'string') {
  9206. setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun);
  9207. // if we have an mwFactory, call it with the player to get the mw,
  9208. // then call the mw's setSource method
  9209. } else if (mwFactory) {
  9210. const mw = getOrCreateFactory(player, mwFactory);
  9211. // if setSource isn't present, implicitly select this middleware
  9212. if (!mw.setSource) {
  9213. acc.push(mw);
  9214. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  9215. }
  9216. mw.setSource(Object.assign({}, src), function (err, _src) {
  9217. // something happened, try the next middleware on the current level
  9218. // make sure to use the old src
  9219. if (err) {
  9220. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  9221. }
  9222. // we've succeeded, now we need to go deeper
  9223. acc.push(mw);
  9224. // if it's the same type, continue down the current chain
  9225. // otherwise, we want to go down the new chain
  9226. setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
  9227. });
  9228. } else if (mwrest.length) {
  9229. setSourceHelper(src, mwrest, next, player, acc, lastRun);
  9230. } else if (lastRun) {
  9231. next(src, acc);
  9232. } else {
  9233. setSourceHelper(src, middlewares['*'], next, player, acc, true);
  9234. }
  9235. }
  9236. /**
  9237. * Mimetypes
  9238. *
  9239. * @see https://www.iana.org/assignments/media-types/media-types.xhtml
  9240. * @typedef Mimetypes~Kind
  9241. * @enum
  9242. */
  9243. const MimetypesKind = {
  9244. opus: 'video/ogg',
  9245. ogv: 'video/ogg',
  9246. mp4: 'video/mp4',
  9247. mov: 'video/mp4',
  9248. m4v: 'video/mp4',
  9249. mkv: 'video/x-matroska',
  9250. m4a: 'audio/mp4',
  9251. mp3: 'audio/mpeg',
  9252. aac: 'audio/aac',
  9253. caf: 'audio/x-caf',
  9254. flac: 'audio/flac',
  9255. oga: 'audio/ogg',
  9256. wav: 'audio/wav',
  9257. m3u8: 'application/x-mpegURL',
  9258. mpd: 'application/dash+xml',
  9259. jpg: 'image/jpeg',
  9260. jpeg: 'image/jpeg',
  9261. gif: 'image/gif',
  9262. png: 'image/png',
  9263. svg: 'image/svg+xml',
  9264. webp: 'image/webp'
  9265. };
  9266. /**
  9267. * Get the mimetype of a given src url if possible
  9268. *
  9269. * @param {string} src
  9270. * The url to the src
  9271. *
  9272. * @return {string}
  9273. * return the mimetype if it was known or empty string otherwise
  9274. */
  9275. const getMimetype = function (src = '') {
  9276. const ext = getFileExtension(src);
  9277. const mimetype = MimetypesKind[ext.toLowerCase()];
  9278. return mimetype || '';
  9279. };
  9280. /**
  9281. * Find the mime type of a given source string if possible. Uses the player
  9282. * source cache.
  9283. *
  9284. * @param { import('../player').default } player
  9285. * The player object
  9286. *
  9287. * @param {string} src
  9288. * The source string
  9289. *
  9290. * @return {string}
  9291. * The type that was found
  9292. */
  9293. const findMimetype = (player, src) => {
  9294. if (!src) {
  9295. return '';
  9296. }
  9297. // 1. check for the type in the `source` cache
  9298. if (player.cache_.source.src === src && player.cache_.source.type) {
  9299. return player.cache_.source.type;
  9300. }
  9301. // 2. see if we have this source in our `currentSources` cache
  9302. const matchingSources = player.cache_.sources.filter(s => s.src === src);
  9303. if (matchingSources.length) {
  9304. return matchingSources[0].type;
  9305. }
  9306. // 3. look for the src url in source elements and use the type there
  9307. const sources = player.$$('source');
  9308. for (let i = 0; i < sources.length; i++) {
  9309. const s = sources[i];
  9310. if (s.type && s.src && s.src === src) {
  9311. return s.type;
  9312. }
  9313. }
  9314. // 4. finally fallback to our list of mime types based on src url extension
  9315. return getMimetype(src);
  9316. };
  9317. /**
  9318. * @module filter-source
  9319. */
  9320. /**
  9321. * Filter out single bad source objects or multiple source objects in an
  9322. * array. Also flattens nested source object arrays into a 1 dimensional
  9323. * array of source objects.
  9324. *
  9325. * @param {Tech~SourceObject|Tech~SourceObject[]} src
  9326. * The src object to filter
  9327. *
  9328. * @return {Tech~SourceObject[]}
  9329. * An array of sourceobjects containing only valid sources
  9330. *
  9331. * @private
  9332. */
  9333. const filterSource = function (src) {
  9334. // traverse array
  9335. if (Array.isArray(src)) {
  9336. let newsrc = [];
  9337. src.forEach(function (srcobj) {
  9338. srcobj = filterSource(srcobj);
  9339. if (Array.isArray(srcobj)) {
  9340. newsrc = newsrc.concat(srcobj);
  9341. } else if (isObject$1(srcobj)) {
  9342. newsrc.push(srcobj);
  9343. }
  9344. });
  9345. src = newsrc;
  9346. } else if (typeof src === 'string' && src.trim()) {
  9347. // convert string into object
  9348. src = [fixSource({
  9349. src
  9350. })];
  9351. } else if (isObject$1(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
  9352. // src is already valid
  9353. src = [fixSource(src)];
  9354. } else {
  9355. // invalid source, turn it into an empty array
  9356. src = [];
  9357. }
  9358. return src;
  9359. };
  9360. /**
  9361. * Checks src mimetype, adding it when possible
  9362. *
  9363. * @param {Tech~SourceObject} src
  9364. * The src object to check
  9365. * @return {Tech~SourceObject}
  9366. * src Object with known type
  9367. */
  9368. function fixSource(src) {
  9369. if (!src.type) {
  9370. const mimetype = getMimetype(src.src);
  9371. if (mimetype) {
  9372. src.type = mimetype;
  9373. }
  9374. }
  9375. return src;
  9376. }
  9377. /**
  9378. * @file loader.js
  9379. */
  9380. /**
  9381. * The `MediaLoader` is the `Component` that decides which playback technology to load
  9382. * when a player is initialized.
  9383. *
  9384. * @extends Component
  9385. */
  9386. class MediaLoader extends Component$1 {
  9387. /**
  9388. * Create an instance of this class.
  9389. *
  9390. * @param { import('../player').default } player
  9391. * The `Player` that this class should attach to.
  9392. *
  9393. * @param {Object} [options]
  9394. * The key/value store of player options.
  9395. *
  9396. * @param {Function} [ready]
  9397. * The function that is run when this component is ready.
  9398. */
  9399. constructor(player, options, ready) {
  9400. // MediaLoader has no element
  9401. const options_ = merge$2({
  9402. createEl: false
  9403. }, options);
  9404. super(player, options_, ready);
  9405. // If there are no sources when the player is initialized,
  9406. // load the first supported playback technology.
  9407. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
  9408. for (let i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
  9409. const techName = toTitleCase$1(j[i]);
  9410. let tech = Tech.getTech(techName);
  9411. // Support old behavior of techs being registered as components.
  9412. // Remove once that deprecated behavior is removed.
  9413. if (!techName) {
  9414. tech = Component$1.getComponent(techName);
  9415. }
  9416. // Check if the browser supports this technology
  9417. if (tech && tech.isSupported()) {
  9418. player.loadTech_(techName);
  9419. break;
  9420. }
  9421. }
  9422. } else {
  9423. // Loop through playback technologies (e.g. HTML5) and check for support.
  9424. // Then load the best source.
  9425. // A few assumptions here:
  9426. // All playback technologies respect preload false.
  9427. player.src(options.playerOptions.sources);
  9428. }
  9429. }
  9430. }
  9431. Component$1.registerComponent('MediaLoader', MediaLoader);
  9432. /**
  9433. * @file clickable-component.js
  9434. */
  9435. /**
  9436. * Component which is clickable or keyboard actionable, but is not a
  9437. * native HTML button.
  9438. *
  9439. * @extends Component
  9440. */
  9441. class ClickableComponent extends Component$1 {
  9442. /**
  9443. * Creates an instance of this class.
  9444. *
  9445. * @param { import('./player').default } player
  9446. * The `Player` that this class should be attached to.
  9447. *
  9448. * @param {Object} [options]
  9449. * The key/value store of component options.
  9450. *
  9451. * @param {function} [options.clickHandler]
  9452. * The function to call when the button is clicked / activated
  9453. *
  9454. * @param {string} [options.controlText]
  9455. * The text to set on the button
  9456. *
  9457. * @param {string} [options.className]
  9458. * A class or space separated list of classes to add the component
  9459. *
  9460. */
  9461. constructor(player, options) {
  9462. super(player, options);
  9463. if (this.options_.controlText) {
  9464. this.controlText(this.options_.controlText);
  9465. }
  9466. this.handleMouseOver_ = e => this.handleMouseOver(e);
  9467. this.handleMouseOut_ = e => this.handleMouseOut(e);
  9468. this.handleClick_ = e => this.handleClick(e);
  9469. this.handleKeyDown_ = e => this.handleKeyDown(e);
  9470. this.emitTapEvents();
  9471. this.enable();
  9472. }
  9473. /**
  9474. * Create the `ClickableComponent`s DOM element.
  9475. *
  9476. * @param {string} [tag=div]
  9477. * The element's node type.
  9478. *
  9479. * @param {Object} [props={}]
  9480. * An object of properties that should be set on the element.
  9481. *
  9482. * @param {Object} [attributes={}]
  9483. * An object of attributes that should be set on the element.
  9484. *
  9485. * @return {Element}
  9486. * The element that gets created.
  9487. */
  9488. createEl(tag = 'div', props = {}, attributes = {}) {
  9489. props = Object.assign({
  9490. className: this.buildCSSClass(),
  9491. tabIndex: 0
  9492. }, props);
  9493. if (tag === 'button') {
  9494. log$1.error(`Creating a ClickableComponent with an HTML element of ${tag} is not supported; use a Button instead.`);
  9495. }
  9496. // Add ARIA attributes for clickable element which is not a native HTML button
  9497. attributes = Object.assign({
  9498. role: 'button'
  9499. }, attributes);
  9500. this.tabIndex_ = props.tabIndex;
  9501. const el = createEl(tag, props, attributes);
  9502. el.appendChild(createEl('span', {
  9503. className: 'vjs-icon-placeholder'
  9504. }, {
  9505. 'aria-hidden': true
  9506. }));
  9507. this.createControlTextEl(el);
  9508. return el;
  9509. }
  9510. dispose() {
  9511. // remove controlTextEl_ on dispose
  9512. this.controlTextEl_ = null;
  9513. super.dispose();
  9514. }
  9515. /**
  9516. * Create a control text element on this `ClickableComponent`
  9517. *
  9518. * @param {Element} [el]
  9519. * Parent element for the control text.
  9520. *
  9521. * @return {Element}
  9522. * The control text element that gets created.
  9523. */
  9524. createControlTextEl(el) {
  9525. this.controlTextEl_ = createEl('span', {
  9526. className: 'vjs-control-text'
  9527. }, {
  9528. // let the screen reader user know that the text of the element may change
  9529. 'aria-live': 'polite'
  9530. });
  9531. if (el) {
  9532. el.appendChild(this.controlTextEl_);
  9533. }
  9534. this.controlText(this.controlText_, el);
  9535. return this.controlTextEl_;
  9536. }
  9537. /**
  9538. * Get or set the localize text to use for the controls on the `ClickableComponent`.
  9539. *
  9540. * @param {string} [text]
  9541. * Control text for element.
  9542. *
  9543. * @param {Element} [el=this.el()]
  9544. * Element to set the title on.
  9545. *
  9546. * @return {string}
  9547. * - The control text when getting
  9548. */
  9549. controlText(text, el = this.el()) {
  9550. if (text === undefined) {
  9551. return this.controlText_ || 'Need Text';
  9552. }
  9553. const localizedText = this.localize(text);
  9554. /** @protected */
  9555. this.controlText_ = text;
  9556. textContent(this.controlTextEl_, localizedText);
  9557. if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {
  9558. // Set title attribute if only an icon is shown
  9559. el.setAttribute('title', localizedText);
  9560. }
  9561. }
  9562. /**
  9563. * Builds the default DOM `className`.
  9564. *
  9565. * @return {string}
  9566. * The DOM `className` for this object.
  9567. */
  9568. buildCSSClass() {
  9569. return `vjs-control vjs-button ${super.buildCSSClass()}`;
  9570. }
  9571. /**
  9572. * Enable this `ClickableComponent`
  9573. */
  9574. enable() {
  9575. if (!this.enabled_) {
  9576. this.enabled_ = true;
  9577. this.removeClass('vjs-disabled');
  9578. this.el_.setAttribute('aria-disabled', 'false');
  9579. if (typeof this.tabIndex_ !== 'undefined') {
  9580. this.el_.setAttribute('tabIndex', this.tabIndex_);
  9581. }
  9582. this.on(['tap', 'click'], this.handleClick_);
  9583. this.on('keydown', this.handleKeyDown_);
  9584. }
  9585. }
  9586. /**
  9587. * Disable this `ClickableComponent`
  9588. */
  9589. disable() {
  9590. this.enabled_ = false;
  9591. this.addClass('vjs-disabled');
  9592. this.el_.setAttribute('aria-disabled', 'true');
  9593. if (typeof this.tabIndex_ !== 'undefined') {
  9594. this.el_.removeAttribute('tabIndex');
  9595. }
  9596. this.off('mouseover', this.handleMouseOver_);
  9597. this.off('mouseout', this.handleMouseOut_);
  9598. this.off(['tap', 'click'], this.handleClick_);
  9599. this.off('keydown', this.handleKeyDown_);
  9600. }
  9601. /**
  9602. * Handles language change in ClickableComponent for the player in components
  9603. *
  9604. *
  9605. */
  9606. handleLanguagechange() {
  9607. this.controlText(this.controlText_);
  9608. }
  9609. /**
  9610. * Event handler that is called when a `ClickableComponent` receives a
  9611. * `click` or `tap` event.
  9612. *
  9613. * @param {Event} event
  9614. * The `tap` or `click` event that caused this function to be called.
  9615. *
  9616. * @listens tap
  9617. * @listens click
  9618. * @abstract
  9619. */
  9620. handleClick(event) {
  9621. if (this.options_.clickHandler) {
  9622. this.options_.clickHandler.call(this, arguments);
  9623. }
  9624. }
  9625. /**
  9626. * Event handler that is called when a `ClickableComponent` receives a
  9627. * `keydown` event.
  9628. *
  9629. * By default, if the key is Space or Enter, it will trigger a `click` event.
  9630. *
  9631. * @param {Event} event
  9632. * The `keydown` event that caused this function to be called.
  9633. *
  9634. * @listens keydown
  9635. */
  9636. handleKeyDown(event) {
  9637. // Support Space or Enter key operation to fire a click event. Also,
  9638. // prevent the event from propagating through the DOM and triggering
  9639. // Player hotkeys.
  9640. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  9641. event.preventDefault();
  9642. event.stopPropagation();
  9643. this.trigger('click');
  9644. } else {
  9645. // Pass keypress handling up for unsupported keys
  9646. super.handleKeyDown(event);
  9647. }
  9648. }
  9649. }
  9650. Component$1.registerComponent('ClickableComponent', ClickableComponent);
  9651. /**
  9652. * @file poster-image.js
  9653. */
  9654. /**
  9655. * A `ClickableComponent` that handles showing the poster image for the player.
  9656. *
  9657. * @extends ClickableComponent
  9658. */
  9659. class PosterImage extends ClickableComponent {
  9660. /**
  9661. * Create an instance of this class.
  9662. *
  9663. * @param { import('./player').default } player
  9664. * The `Player` that this class should attach to.
  9665. *
  9666. * @param {Object} [options]
  9667. * The key/value store of player options.
  9668. */
  9669. constructor(player, options) {
  9670. super(player, options);
  9671. this.update();
  9672. this.update_ = e => this.update(e);
  9673. player.on('posterchange', this.update_);
  9674. }
  9675. /**
  9676. * Clean up and dispose of the `PosterImage`.
  9677. */
  9678. dispose() {
  9679. this.player().off('posterchange', this.update_);
  9680. super.dispose();
  9681. }
  9682. /**
  9683. * Create the `PosterImage`s DOM element.
  9684. *
  9685. * @return {Element}
  9686. * The element that gets created.
  9687. */
  9688. createEl() {
  9689. // The el is an empty div to keep position in the DOM
  9690. // A picture and img el will be inserted when a source is set
  9691. return createEl('div', {
  9692. className: 'vjs-poster'
  9693. });
  9694. }
  9695. /**
  9696. * Get or set the `PosterImage`'s crossOrigin option.
  9697. *
  9698. * @param {string|null} [value]
  9699. * The value to set the crossOrigin to. If an argument is
  9700. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  9701. *
  9702. * @return {string|null}
  9703. * - The current crossOrigin value of the `Player` when getting.
  9704. * - undefined when setting
  9705. */
  9706. crossOrigin(value) {
  9707. // `null` can be set to unset a value
  9708. if (typeof value === 'undefined') {
  9709. if (this.$('img')) {
  9710. // If the poster's element exists, give its value
  9711. return this.$('img').crossOrigin;
  9712. } else if (this.player_.tech_ && this.player_.tech_.isReady_) {
  9713. // If not but the tech is ready, query the tech
  9714. return this.player_.crossOrigin();
  9715. }
  9716. // Otherwise check options as the poster is usually set before the state of crossorigin
  9717. // can be retrieved by the getter
  9718. return this.player_.options_.crossOrigin || this.player_.options_.crossorigin || null;
  9719. }
  9720. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  9721. this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  9722. return;
  9723. }
  9724. if (this.$('img')) {
  9725. this.$('img').crossOrigin = value;
  9726. }
  9727. return;
  9728. }
  9729. /**
  9730. * An {@link EventTarget~EventListener} for {@link Player#posterchange} events.
  9731. *
  9732. * @listens Player#posterchange
  9733. *
  9734. * @param {Event} [event]
  9735. * The `Player#posterchange` event that triggered this function.
  9736. */
  9737. update(event) {
  9738. const url = this.player().poster();
  9739. this.setSrc(url);
  9740. // If there's no poster source we should display:none on this component
  9741. // so it's not still clickable or right-clickable
  9742. if (url) {
  9743. this.show();
  9744. } else {
  9745. this.hide();
  9746. }
  9747. }
  9748. /**
  9749. * Set the source of the `PosterImage` depending on the display method. (Re)creates
  9750. * the inner picture and img elementss when needed.
  9751. *
  9752. * @param {string} [url]
  9753. * The URL to the source for the `PosterImage`. If not specified or falsy,
  9754. * any source and ant inner picture/img are removed.
  9755. */
  9756. setSrc(url) {
  9757. if (!url) {
  9758. this.el_.textContent = '';
  9759. return;
  9760. }
  9761. if (!this.$('img')) {
  9762. this.el_.appendChild(createEl('picture', {
  9763. className: 'vjs-poster',
  9764. // Don't want poster to be tabbable.
  9765. tabIndex: -1
  9766. }, {}, createEl('img', {
  9767. loading: 'lazy',
  9768. crossOrigin: this.crossOrigin()
  9769. }, {
  9770. alt: ''
  9771. })));
  9772. }
  9773. this.$('img').src = url;
  9774. }
  9775. /**
  9776. * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See
  9777. * {@link ClickableComponent#handleClick} for instances where this will be triggered.
  9778. *
  9779. * @listens tap
  9780. * @listens click
  9781. * @listens keydown
  9782. *
  9783. * @param {Event} event
  9784. + The `click`, `tap` or `keydown` event that caused this function to be called.
  9785. */
  9786. handleClick(event) {
  9787. // We don't want a click to trigger playback when controls are disabled
  9788. if (!this.player_.controls()) {
  9789. return;
  9790. }
  9791. if (this.player_.tech(true)) {
  9792. this.player_.tech(true).focus();
  9793. }
  9794. if (this.player_.paused()) {
  9795. silencePromise(this.player_.play());
  9796. } else {
  9797. this.player_.pause();
  9798. }
  9799. }
  9800. }
  9801. /**
  9802. * Get or set the `PosterImage`'s crossorigin option. For the HTML5 player, this
  9803. * sets the `crossOrigin` property on the `<img>` tag to control the CORS
  9804. * behavior.
  9805. *
  9806. * @param {string|null} [value]
  9807. * The value to set the `PosterImages`'s crossorigin to. If an argument is
  9808. * given, must be one of `anonymous` or `use-credentials`.
  9809. *
  9810. * @return {string|null|undefined}
  9811. * - The current crossorigin value of the `Player` when getting.
  9812. * - undefined when setting
  9813. */
  9814. PosterImage.prototype.crossorigin = PosterImage.prototype.crossOrigin;
  9815. Component$1.registerComponent('PosterImage', PosterImage);
  9816. /**
  9817. * @file text-track-display.js
  9818. */
  9819. const darkGray = '#222';
  9820. const lightGray = '#ccc';
  9821. const fontMap = {
  9822. monospace: 'monospace',
  9823. sansSerif: 'sans-serif',
  9824. serif: 'serif',
  9825. monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
  9826. monospaceSerif: '"Courier New", monospace',
  9827. proportionalSansSerif: 'sans-serif',
  9828. proportionalSerif: 'serif',
  9829. casual: '"Comic Sans MS", Impact, fantasy',
  9830. script: '"Monotype Corsiva", cursive',
  9831. smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
  9832. };
  9833. /**
  9834. * Construct an rgba color from a given hex color code.
  9835. *
  9836. * @param {number} color
  9837. * Hex number for color, like #f0e or #f604e2.
  9838. *
  9839. * @param {number} opacity
  9840. * Value for opacity, 0.0 - 1.0.
  9841. *
  9842. * @return {string}
  9843. * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
  9844. */
  9845. function constructColor(color, opacity) {
  9846. let hex;
  9847. if (color.length === 4) {
  9848. // color looks like "#f0e"
  9849. hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
  9850. } else if (color.length === 7) {
  9851. // color looks like "#f604e2"
  9852. hex = color.slice(1);
  9853. } else {
  9854. throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
  9855. }
  9856. return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';
  9857. }
  9858. /**
  9859. * Try to update the style of a DOM element. Some style changes will throw an error,
  9860. * particularly in IE8. Those should be noops.
  9861. *
  9862. * @param {Element} el
  9863. * The DOM element to be styled.
  9864. *
  9865. * @param {string} style
  9866. * The CSS property on the element that should be styled.
  9867. *
  9868. * @param {string} rule
  9869. * The style rule that should be applied to the property.
  9870. *
  9871. * @private
  9872. */
  9873. function tryUpdateStyle(el, style, rule) {
  9874. try {
  9875. el.style[style] = rule;
  9876. } catch (e) {
  9877. // Satisfies linter.
  9878. return;
  9879. }
  9880. }
  9881. /**
  9882. * The component for displaying text track cues.
  9883. *
  9884. * @extends Component
  9885. */
  9886. class TextTrackDisplay extends Component$1 {
  9887. /**
  9888. * Creates an instance of this class.
  9889. *
  9890. * @param { import('../player').default } player
  9891. * The `Player` that this class should be attached to.
  9892. *
  9893. * @param {Object} [options]
  9894. * The key/value store of player options.
  9895. *
  9896. * @param {Function} [ready]
  9897. * The function to call when `TextTrackDisplay` is ready.
  9898. */
  9899. constructor(player, options, ready) {
  9900. super(player, options, ready);
  9901. const updateDisplayHandler = e => this.updateDisplay(e);
  9902. player.on('loadstart', e => this.toggleDisplay(e));
  9903. player.on('texttrackchange', updateDisplayHandler);
  9904. player.on('loadedmetadata', e => this.preselectTrack(e));
  9905. // This used to be called during player init, but was causing an error
  9906. // if a track should show by default and the display hadn't loaded yet.
  9907. // Should probably be moved to an external track loader when we support
  9908. // tracks that don't need a display.
  9909. player.ready(bind_(this, function () {
  9910. if (player.tech_ && player.tech_.featuresNativeTextTracks) {
  9911. this.hide();
  9912. return;
  9913. }
  9914. player.on('fullscreenchange', updateDisplayHandler);
  9915. player.on('playerresize', updateDisplayHandler);
  9916. const screenOrientation = window.screen.orientation || window;
  9917. const changeOrientationEvent = window.screen.orientation ? 'change' : 'orientationchange';
  9918. screenOrientation.addEventListener(changeOrientationEvent, updateDisplayHandler);
  9919. player.on('dispose', () => screenOrientation.removeEventListener(changeOrientationEvent, updateDisplayHandler));
  9920. const tracks = this.options_.playerOptions.tracks || [];
  9921. for (let i = 0; i < tracks.length; i++) {
  9922. this.player_.addRemoteTextTrack(tracks[i], true);
  9923. }
  9924. this.preselectTrack();
  9925. }));
  9926. }
  9927. /**
  9928. * Preselect a track following this precedence:
  9929. * - matches the previously selected {@link TextTrack}'s language and kind
  9930. * - matches the previously selected {@link TextTrack}'s language only
  9931. * - is the first default captions track
  9932. * - is the first default descriptions track
  9933. *
  9934. * @listens Player#loadstart
  9935. */
  9936. preselectTrack() {
  9937. const modes = {
  9938. captions: 1,
  9939. subtitles: 1
  9940. };
  9941. const trackList = this.player_.textTracks();
  9942. const userPref = this.player_.cache_.selectedLanguage;
  9943. let firstDesc;
  9944. let firstCaptions;
  9945. let preferredTrack;
  9946. for (let i = 0; i < trackList.length; i++) {
  9947. const track = trackList[i];
  9948. if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {
  9949. // Always choose the track that matches both language and kind
  9950. if (track.kind === userPref.kind) {
  9951. preferredTrack = track;
  9952. // or choose the first track that matches language
  9953. } else if (!preferredTrack) {
  9954. preferredTrack = track;
  9955. }
  9956. // clear everything if offTextTrackMenuItem was clicked
  9957. } else if (userPref && !userPref.enabled) {
  9958. preferredTrack = null;
  9959. firstDesc = null;
  9960. firstCaptions = null;
  9961. } else if (track.default) {
  9962. if (track.kind === 'descriptions' && !firstDesc) {
  9963. firstDesc = track;
  9964. } else if (track.kind in modes && !firstCaptions) {
  9965. firstCaptions = track;
  9966. }
  9967. }
  9968. }
  9969. // The preferredTrack matches the user preference and takes
  9970. // precedence over all the other tracks.
  9971. // So, display the preferredTrack before the first default track
  9972. // and the subtitles/captions track before the descriptions track
  9973. if (preferredTrack) {
  9974. preferredTrack.mode = 'showing';
  9975. } else if (firstCaptions) {
  9976. firstCaptions.mode = 'showing';
  9977. } else if (firstDesc) {
  9978. firstDesc.mode = 'showing';
  9979. }
  9980. }
  9981. /**
  9982. * Turn display of {@link TextTrack}'s from the current state into the other state.
  9983. * There are only two states:
  9984. * - 'shown'
  9985. * - 'hidden'
  9986. *
  9987. * @listens Player#loadstart
  9988. */
  9989. toggleDisplay() {
  9990. if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
  9991. this.hide();
  9992. } else {
  9993. this.show();
  9994. }
  9995. }
  9996. /**
  9997. * Create the {@link Component}'s DOM element.
  9998. *
  9999. * @return {Element}
  10000. * The element that was created.
  10001. */
  10002. createEl() {
  10003. return super.createEl('div', {
  10004. className: 'vjs-text-track-display'
  10005. }, {
  10006. 'translate': 'yes',
  10007. 'aria-live': 'off',
  10008. 'aria-atomic': 'true'
  10009. });
  10010. }
  10011. /**
  10012. * Clear all displayed {@link TextTrack}s.
  10013. */
  10014. clearDisplay() {
  10015. if (typeof window.WebVTT === 'function') {
  10016. window.WebVTT.processCues(window, [], this.el_);
  10017. }
  10018. }
  10019. /**
  10020. * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or
  10021. * a {@link Player#fullscreenchange} is fired.
  10022. *
  10023. * @listens Player#texttrackchange
  10024. * @listens Player#fullscreenchange
  10025. */
  10026. updateDisplay() {
  10027. const tracks = this.player_.textTracks();
  10028. const allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;
  10029. this.clearDisplay();
  10030. if (allowMultipleShowingTracks) {
  10031. const showingTracks = [];
  10032. for (let i = 0; i < tracks.length; ++i) {
  10033. const track = tracks[i];
  10034. if (track.mode !== 'showing') {
  10035. continue;
  10036. }
  10037. showingTracks.push(track);
  10038. }
  10039. this.updateForTrack(showingTracks);
  10040. return;
  10041. }
  10042. // Track display prioritization model: if multiple tracks are 'showing',
  10043. // display the first 'subtitles' or 'captions' track which is 'showing',
  10044. // otherwise display the first 'descriptions' track which is 'showing'
  10045. let descriptionsTrack = null;
  10046. let captionsSubtitlesTrack = null;
  10047. let i = tracks.length;
  10048. while (i--) {
  10049. const track = tracks[i];
  10050. if (track.mode === 'showing') {
  10051. if (track.kind === 'descriptions') {
  10052. descriptionsTrack = track;
  10053. } else {
  10054. captionsSubtitlesTrack = track;
  10055. }
  10056. }
  10057. }
  10058. if (captionsSubtitlesTrack) {
  10059. if (this.getAttribute('aria-live') !== 'off') {
  10060. this.setAttribute('aria-live', 'off');
  10061. }
  10062. this.updateForTrack(captionsSubtitlesTrack);
  10063. } else if (descriptionsTrack) {
  10064. if (this.getAttribute('aria-live') !== 'assertive') {
  10065. this.setAttribute('aria-live', 'assertive');
  10066. }
  10067. this.updateForTrack(descriptionsTrack);
  10068. }
  10069. }
  10070. /**
  10071. * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}.
  10072. *
  10073. * @param {TextTrack} track
  10074. * Text track object containing active cues to style.
  10075. */
  10076. updateDisplayState(track) {
  10077. const overrides = this.player_.textTrackSettings.getValues();
  10078. const cues = track.activeCues;
  10079. let i = cues.length;
  10080. while (i--) {
  10081. const cue = cues[i];
  10082. if (!cue) {
  10083. continue;
  10084. }
  10085. const cueDiv = cue.displayState;
  10086. if (overrides.color) {
  10087. cueDiv.firstChild.style.color = overrides.color;
  10088. }
  10089. if (overrides.textOpacity) {
  10090. tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
  10091. }
  10092. if (overrides.backgroundColor) {
  10093. cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
  10094. }
  10095. if (overrides.backgroundOpacity) {
  10096. tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
  10097. }
  10098. if (overrides.windowColor) {
  10099. if (overrides.windowOpacity) {
  10100. tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
  10101. } else {
  10102. cueDiv.style.backgroundColor = overrides.windowColor;
  10103. }
  10104. }
  10105. if (overrides.edgeStyle) {
  10106. if (overrides.edgeStyle === 'dropshadow') {
  10107. cueDiv.firstChild.style.textShadow = `2px 2px 3px ${darkGray}, 2px 2px 4px ${darkGray}, 2px 2px 5px ${darkGray}`;
  10108. } else if (overrides.edgeStyle === 'raised') {
  10109. cueDiv.firstChild.style.textShadow = `1px 1px ${darkGray}, 2px 2px ${darkGray}, 3px 3px ${darkGray}`;
  10110. } else if (overrides.edgeStyle === 'depressed') {
  10111. cueDiv.firstChild.style.textShadow = `1px 1px ${lightGray}, 0 1px ${lightGray}, -1px -1px ${darkGray}, 0 -1px ${darkGray}`;
  10112. } else if (overrides.edgeStyle === 'uniform') {
  10113. cueDiv.firstChild.style.textShadow = `0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}`;
  10114. }
  10115. }
  10116. if (overrides.fontPercent && overrides.fontPercent !== 1) {
  10117. const fontSize = window.parseFloat(cueDiv.style.fontSize);
  10118. cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
  10119. cueDiv.style.height = 'auto';
  10120. cueDiv.style.top = 'auto';
  10121. }
  10122. if (overrides.fontFamily && overrides.fontFamily !== 'default') {
  10123. if (overrides.fontFamily === 'small-caps') {
  10124. cueDiv.firstChild.style.fontVariant = 'small-caps';
  10125. } else {
  10126. cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
  10127. }
  10128. }
  10129. }
  10130. }
  10131. /**
  10132. * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}.
  10133. *
  10134. * @param {TextTrack|TextTrack[]} tracks
  10135. * Text track object or text track array to be added to the list.
  10136. */
  10137. updateForTrack(tracks) {
  10138. if (!Array.isArray(tracks)) {
  10139. tracks = [tracks];
  10140. }
  10141. if (typeof window.WebVTT !== 'function' || tracks.every(track => {
  10142. return !track.activeCues;
  10143. })) {
  10144. return;
  10145. }
  10146. const cues = [];
  10147. // push all active track cues
  10148. for (let i = 0; i < tracks.length; ++i) {
  10149. const track = tracks[i];
  10150. for (let j = 0; j < track.activeCues.length; ++j) {
  10151. cues.push(track.activeCues[j]);
  10152. }
  10153. }
  10154. // removes all cues before it processes new ones
  10155. window.WebVTT.processCues(window, cues, this.el_);
  10156. // add unique class to each language text track & add settings styling if necessary
  10157. for (let i = 0; i < tracks.length; ++i) {
  10158. const track = tracks[i];
  10159. for (let j = 0; j < track.activeCues.length; ++j) {
  10160. const cueEl = track.activeCues[j].displayState;
  10161. addClass(cueEl, 'vjs-text-track-cue', 'vjs-text-track-cue-' + (track.language ? track.language : i));
  10162. if (track.language) {
  10163. setAttribute(cueEl, 'lang', track.language);
  10164. }
  10165. }
  10166. if (this.player_.textTrackSettings) {
  10167. this.updateDisplayState(track);
  10168. }
  10169. }
  10170. }
  10171. }
  10172. Component$1.registerComponent('TextTrackDisplay', TextTrackDisplay);
  10173. /**
  10174. * @file loading-spinner.js
  10175. */
  10176. /**
  10177. * A loading spinner for use during waiting/loading events.
  10178. *
  10179. * @extends Component
  10180. */
  10181. class LoadingSpinner extends Component$1 {
  10182. /**
  10183. * Create the `LoadingSpinner`s DOM element.
  10184. *
  10185. * @return {Element}
  10186. * The dom element that gets created.
  10187. */
  10188. createEl() {
  10189. const isAudio = this.player_.isAudio();
  10190. const playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
  10191. const controlText = createEl('span', {
  10192. className: 'vjs-control-text',
  10193. textContent: this.localize('{1} is loading.', [playerType])
  10194. });
  10195. const el = super.createEl('div', {
  10196. className: 'vjs-loading-spinner',
  10197. dir: 'ltr'
  10198. });
  10199. el.appendChild(controlText);
  10200. return el;
  10201. }
  10202. /**
  10203. * Update control text on languagechange
  10204. */
  10205. handleLanguagechange() {
  10206. this.$('.vjs-control-text').textContent = this.localize('{1} is loading.', [this.player_.isAudio() ? 'Audio Player' : 'Video Player']);
  10207. }
  10208. }
  10209. Component$1.registerComponent('LoadingSpinner', LoadingSpinner);
  10210. /**
  10211. * @file button.js
  10212. */
  10213. /**
  10214. * Base class for all buttons.
  10215. *
  10216. * @extends ClickableComponent
  10217. */
  10218. class Button extends ClickableComponent {
  10219. /**
  10220. * Create the `Button`s DOM element.
  10221. *
  10222. * @param {string} [tag="button"]
  10223. * The element's node type. This argument is IGNORED: no matter what
  10224. * is passed, it will always create a `button` element.
  10225. *
  10226. * @param {Object} [props={}]
  10227. * An object of properties that should be set on the element.
  10228. *
  10229. * @param {Object} [attributes={}]
  10230. * An object of attributes that should be set on the element.
  10231. *
  10232. * @return {Element}
  10233. * The element that gets created.
  10234. */
  10235. createEl(tag, props = {}, attributes = {}) {
  10236. tag = 'button';
  10237. props = Object.assign({
  10238. className: this.buildCSSClass()
  10239. }, props);
  10240. // Add attributes for button element
  10241. attributes = Object.assign({
  10242. // Necessary since the default button type is "submit"
  10243. type: 'button'
  10244. }, attributes);
  10245. const el = createEl(tag, props, attributes);
  10246. el.appendChild(createEl('span', {
  10247. className: 'vjs-icon-placeholder'
  10248. }, {
  10249. 'aria-hidden': true
  10250. }));
  10251. this.createControlTextEl(el);
  10252. return el;
  10253. }
  10254. /**
  10255. * Add a child `Component` inside of this `Button`.
  10256. *
  10257. * @param {string|Component} child
  10258. * The name or instance of a child to add.
  10259. *
  10260. * @param {Object} [options={}]
  10261. * The key/value store of options that will get passed to children of
  10262. * the child.
  10263. *
  10264. * @return {Component}
  10265. * The `Component` that gets added as a child. When using a string the
  10266. * `Component` will get created by this process.
  10267. *
  10268. * @deprecated since version 5
  10269. */
  10270. addChild(child, options = {}) {
  10271. const className = this.constructor.name;
  10272. log$1.warn(`Adding an actionable (user controllable) child to a Button (${className}) is not supported; use a ClickableComponent instead.`);
  10273. // Avoid the error message generated by ClickableComponent's addChild method
  10274. return Component$1.prototype.addChild.call(this, child, options);
  10275. }
  10276. /**
  10277. * Enable the `Button` element so that it can be activated or clicked. Use this with
  10278. * {@link Button#disable}.
  10279. */
  10280. enable() {
  10281. super.enable();
  10282. this.el_.removeAttribute('disabled');
  10283. }
  10284. /**
  10285. * Disable the `Button` element so that it cannot be activated or clicked. Use this with
  10286. * {@link Button#enable}.
  10287. */
  10288. disable() {
  10289. super.disable();
  10290. this.el_.setAttribute('disabled', 'disabled');
  10291. }
  10292. /**
  10293. * This gets called when a `Button` has focus and `keydown` is triggered via a key
  10294. * press.
  10295. *
  10296. * @param {Event} event
  10297. * The event that caused this function to get called.
  10298. *
  10299. * @listens keydown
  10300. */
  10301. handleKeyDown(event) {
  10302. // Ignore Space or Enter key operation, which is handled by the browser for
  10303. // a button - though not for its super class, ClickableComponent. Also,
  10304. // prevent the event from propagating through the DOM and triggering Player
  10305. // hotkeys. We do not preventDefault here because we _want_ the browser to
  10306. // handle it.
  10307. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  10308. event.stopPropagation();
  10309. return;
  10310. }
  10311. // Pass keypress handling up for unsupported keys
  10312. super.handleKeyDown(event);
  10313. }
  10314. }
  10315. Component$1.registerComponent('Button', Button);
  10316. /**
  10317. * @file big-play-button.js
  10318. */
  10319. /**
  10320. * The initial play button that shows before the video has played. The hiding of the
  10321. * `BigPlayButton` get done via CSS and `Player` states.
  10322. *
  10323. * @extends Button
  10324. */
  10325. class BigPlayButton extends Button {
  10326. constructor(player, options) {
  10327. super(player, options);
  10328. this.mouseused_ = false;
  10329. this.on('mousedown', e => this.handleMouseDown(e));
  10330. }
  10331. /**
  10332. * Builds the default DOM `className`.
  10333. *
  10334. * @return {string}
  10335. * The DOM `className` for this object. Always returns 'vjs-big-play-button'.
  10336. */
  10337. buildCSSClass() {
  10338. return 'vjs-big-play-button';
  10339. }
  10340. /**
  10341. * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent}
  10342. * for more detailed information on what a click can be.
  10343. *
  10344. * @param {KeyboardEvent} event
  10345. * The `keydown`, `tap`, or `click` event that caused this function to be
  10346. * called.
  10347. *
  10348. * @listens tap
  10349. * @listens click
  10350. */
  10351. handleClick(event) {
  10352. const playPromise = this.player_.play();
  10353. // exit early if clicked via the mouse
  10354. if (this.mouseused_ && event.clientX && event.clientY) {
  10355. silencePromise(playPromise);
  10356. if (this.player_.tech(true)) {
  10357. this.player_.tech(true).focus();
  10358. }
  10359. return;
  10360. }
  10361. const cb = this.player_.getChild('controlBar');
  10362. const playToggle = cb && cb.getChild('playToggle');
  10363. if (!playToggle) {
  10364. this.player_.tech(true).focus();
  10365. return;
  10366. }
  10367. const playFocus = () => playToggle.focus();
  10368. if (isPromise(playPromise)) {
  10369. playPromise.then(playFocus, () => {});
  10370. } else {
  10371. this.setTimeout(playFocus, 1);
  10372. }
  10373. }
  10374. handleKeyDown(event) {
  10375. this.mouseused_ = false;
  10376. super.handleKeyDown(event);
  10377. }
  10378. handleMouseDown(event) {
  10379. this.mouseused_ = true;
  10380. }
  10381. }
  10382. /**
  10383. * The text that should display over the `BigPlayButton`s controls. Added to for localization.
  10384. *
  10385. * @type {string}
  10386. * @protected
  10387. */
  10388. BigPlayButton.prototype.controlText_ = 'Play Video';
  10389. Component$1.registerComponent('BigPlayButton', BigPlayButton);
  10390. /**
  10391. * @file close-button.js
  10392. */
  10393. /**
  10394. * The `CloseButton` is a `{@link Button}` that fires a `close` event when
  10395. * it gets clicked.
  10396. *
  10397. * @extends Button
  10398. */
  10399. class CloseButton extends Button {
  10400. /**
  10401. * Creates an instance of the this class.
  10402. *
  10403. * @param { import('./player').default } player
  10404. * The `Player` that this class should be attached to.
  10405. *
  10406. * @param {Object} [options]
  10407. * The key/value store of player options.
  10408. */
  10409. constructor(player, options) {
  10410. super(player, options);
  10411. this.controlText(options && options.controlText || this.localize('Close'));
  10412. }
  10413. /**
  10414. * Builds the default DOM `className`.
  10415. *
  10416. * @return {string}
  10417. * The DOM `className` for this object.
  10418. */
  10419. buildCSSClass() {
  10420. return `vjs-close-button ${super.buildCSSClass()}`;
  10421. }
  10422. /**
  10423. * This gets called when a `CloseButton` gets clicked. See
  10424. * {@link ClickableComponent#handleClick} for more information on when
  10425. * this will be triggered
  10426. *
  10427. * @param {Event} event
  10428. * The `keydown`, `tap`, or `click` event that caused this function to be
  10429. * called.
  10430. *
  10431. * @listens tap
  10432. * @listens click
  10433. * @fires CloseButton#close
  10434. */
  10435. handleClick(event) {
  10436. /**
  10437. * Triggered when the a `CloseButton` is clicked.
  10438. *
  10439. * @event CloseButton#close
  10440. * @type {Event}
  10441. *
  10442. * @property {boolean} [bubbles=false]
  10443. * set to false so that the close event does not
  10444. * bubble up to parents if there is no listener
  10445. */
  10446. this.trigger({
  10447. type: 'close',
  10448. bubbles: false
  10449. });
  10450. }
  10451. /**
  10452. * Event handler that is called when a `CloseButton` receives a
  10453. * `keydown` event.
  10454. *
  10455. * By default, if the key is Esc, it will trigger a `click` event.
  10456. *
  10457. * @param {Event} event
  10458. * The `keydown` event that caused this function to be called.
  10459. *
  10460. * @listens keydown
  10461. */
  10462. handleKeyDown(event) {
  10463. // Esc button will trigger `click` event
  10464. if (keycode.isEventKey(event, 'Esc')) {
  10465. event.preventDefault();
  10466. event.stopPropagation();
  10467. this.trigger('click');
  10468. } else {
  10469. // Pass keypress handling up for unsupported keys
  10470. super.handleKeyDown(event);
  10471. }
  10472. }
  10473. }
  10474. Component$1.registerComponent('CloseButton', CloseButton);
  10475. /**
  10476. * @file play-toggle.js
  10477. */
  10478. /**
  10479. * Button to toggle between play and pause.
  10480. *
  10481. * @extends Button
  10482. */
  10483. class PlayToggle extends Button {
  10484. /**
  10485. * Creates an instance of this class.
  10486. *
  10487. * @param { import('./player').default } player
  10488. * The `Player` that this class should be attached to.
  10489. *
  10490. * @param {Object} [options={}]
  10491. * The key/value store of player options.
  10492. */
  10493. constructor(player, options = {}) {
  10494. super(player, options);
  10495. // show or hide replay icon
  10496. options.replay = options.replay === undefined || options.replay;
  10497. this.on(player, 'play', e => this.handlePlay(e));
  10498. this.on(player, 'pause', e => this.handlePause(e));
  10499. if (options.replay) {
  10500. this.on(player, 'ended', e => this.handleEnded(e));
  10501. }
  10502. }
  10503. /**
  10504. * Builds the default DOM `className`.
  10505. *
  10506. * @return {string}
  10507. * The DOM `className` for this object.
  10508. */
  10509. buildCSSClass() {
  10510. return `vjs-play-control ${super.buildCSSClass()}`;
  10511. }
  10512. /**
  10513. * This gets called when an `PlayToggle` is "clicked". See
  10514. * {@link ClickableComponent} for more detailed information on what a click can be.
  10515. *
  10516. * @param {Event} [event]
  10517. * The `keydown`, `tap`, or `click` event that caused this function to be
  10518. * called.
  10519. *
  10520. * @listens tap
  10521. * @listens click
  10522. */
  10523. handleClick(event) {
  10524. if (this.player_.paused()) {
  10525. silencePromise(this.player_.play());
  10526. } else {
  10527. this.player_.pause();
  10528. }
  10529. }
  10530. /**
  10531. * This gets called once after the video has ended and the user seeks so that
  10532. * we can change the replay button back to a play button.
  10533. *
  10534. * @param {Event} [event]
  10535. * The event that caused this function to run.
  10536. *
  10537. * @listens Player#seeked
  10538. */
  10539. handleSeeked(event) {
  10540. this.removeClass('vjs-ended');
  10541. if (this.player_.paused()) {
  10542. this.handlePause(event);
  10543. } else {
  10544. this.handlePlay(event);
  10545. }
  10546. }
  10547. /**
  10548. * Add the vjs-playing class to the element so it can change appearance.
  10549. *
  10550. * @param {Event} [event]
  10551. * The event that caused this function to run.
  10552. *
  10553. * @listens Player#play
  10554. */
  10555. handlePlay(event) {
  10556. this.removeClass('vjs-ended', 'vjs-paused');
  10557. this.addClass('vjs-playing');
  10558. // change the button text to "Pause"
  10559. this.controlText('Pause');
  10560. }
  10561. /**
  10562. * Add the vjs-paused class to the element so it can change appearance.
  10563. *
  10564. * @param {Event} [event]
  10565. * The event that caused this function to run.
  10566. *
  10567. * @listens Player#pause
  10568. */
  10569. handlePause(event) {
  10570. this.removeClass('vjs-playing');
  10571. this.addClass('vjs-paused');
  10572. // change the button text to "Play"
  10573. this.controlText('Play');
  10574. }
  10575. /**
  10576. * Add the vjs-ended class to the element so it can change appearance
  10577. *
  10578. * @param {Event} [event]
  10579. * The event that caused this function to run.
  10580. *
  10581. * @listens Player#ended
  10582. */
  10583. handleEnded(event) {
  10584. this.removeClass('vjs-playing');
  10585. this.addClass('vjs-ended');
  10586. // change the button text to "Replay"
  10587. this.controlText('Replay');
  10588. // on the next seek remove the replay button
  10589. this.one(this.player_, 'seeked', e => this.handleSeeked(e));
  10590. }
  10591. }
  10592. /**
  10593. * The text that should display over the `PlayToggle`s controls. Added for localization.
  10594. *
  10595. * @type {string}
  10596. * @protected
  10597. */
  10598. PlayToggle.prototype.controlText_ = 'Play';
  10599. Component$1.registerComponent('PlayToggle', PlayToggle);
  10600. /**
  10601. * @file time-display.js
  10602. */
  10603. /**
  10604. * Displays time information about the video
  10605. *
  10606. * @extends Component
  10607. */
  10608. class TimeDisplay extends Component$1 {
  10609. /**
  10610. * Creates an instance of this class.
  10611. *
  10612. * @param { import('../../player').default } player
  10613. * The `Player` that this class should be attached to.
  10614. *
  10615. * @param {Object} [options]
  10616. * The key/value store of player options.
  10617. */
  10618. constructor(player, options) {
  10619. super(player, options);
  10620. this.on(player, ['timeupdate', 'ended'], e => this.updateContent(e));
  10621. this.updateTextNode_();
  10622. }
  10623. /**
  10624. * Create the `Component`'s DOM element
  10625. *
  10626. * @return {Element}
  10627. * The element that was created.
  10628. */
  10629. createEl() {
  10630. const className = this.buildCSSClass();
  10631. const el = super.createEl('div', {
  10632. className: `${className} vjs-time-control vjs-control`
  10633. });
  10634. const span = createEl('span', {
  10635. className: 'vjs-control-text',
  10636. textContent: `${this.localize(this.labelText_)}\u00a0`
  10637. }, {
  10638. role: 'presentation'
  10639. });
  10640. el.appendChild(span);
  10641. this.contentEl_ = createEl('span', {
  10642. className: `${className}-display`
  10643. }, {
  10644. // span elements have no implicit role, but some screen readers (notably VoiceOver)
  10645. // treat them as a break between items in the DOM when using arrow keys
  10646. // (or left-to-right swipes on iOS) to read contents of a page. Using
  10647. // role='presentation' causes VoiceOver to NOT treat this span as a break.
  10648. role: 'presentation'
  10649. });
  10650. el.appendChild(this.contentEl_);
  10651. return el;
  10652. }
  10653. dispose() {
  10654. this.contentEl_ = null;
  10655. this.textNode_ = null;
  10656. super.dispose();
  10657. }
  10658. /**
  10659. * Updates the time display text node with a new time
  10660. *
  10661. * @param {number} [time=0] the time to update to
  10662. *
  10663. * @private
  10664. */
  10665. updateTextNode_(time = 0) {
  10666. time = formatTime(time);
  10667. if (this.formattedTime_ === time) {
  10668. return;
  10669. }
  10670. this.formattedTime_ = time;
  10671. this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_', () => {
  10672. if (!this.contentEl_) {
  10673. return;
  10674. }
  10675. let oldNode = this.textNode_;
  10676. if (oldNode && this.contentEl_.firstChild !== oldNode) {
  10677. oldNode = null;
  10678. 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.');
  10679. }
  10680. this.textNode_ = document.createTextNode(this.formattedTime_);
  10681. if (!this.textNode_) {
  10682. return;
  10683. }
  10684. if (oldNode) {
  10685. this.contentEl_.replaceChild(this.textNode_, oldNode);
  10686. } else {
  10687. this.contentEl_.appendChild(this.textNode_);
  10688. }
  10689. });
  10690. }
  10691. /**
  10692. * To be filled out in the child class, should update the displayed time
  10693. * in accordance with the fact that the current time has changed.
  10694. *
  10695. * @param {Event} [event]
  10696. * The `timeupdate` event that caused this to run.
  10697. *
  10698. * @listens Player#timeupdate
  10699. */
  10700. updateContent(event) {}
  10701. }
  10702. /**
  10703. * The text that is added to the `TimeDisplay` for screen reader users.
  10704. *
  10705. * @type {string}
  10706. * @private
  10707. */
  10708. TimeDisplay.prototype.labelText_ = 'Time';
  10709. /**
  10710. * The text that should display over the `TimeDisplay`s controls. Added to for localization.
  10711. *
  10712. * @type {string}
  10713. * @protected
  10714. *
  10715. * @deprecated in v7; controlText_ is not used in non-active display Components
  10716. */
  10717. TimeDisplay.prototype.controlText_ = 'Time';
  10718. Component$1.registerComponent('TimeDisplay', TimeDisplay);
  10719. /**
  10720. * @file current-time-display.js
  10721. */
  10722. /**
  10723. * Displays the current time
  10724. *
  10725. * @extends Component
  10726. */
  10727. class CurrentTimeDisplay extends TimeDisplay {
  10728. /**
  10729. * Builds the default DOM `className`.
  10730. *
  10731. * @return {string}
  10732. * The DOM `className` for this object.
  10733. */
  10734. buildCSSClass() {
  10735. return 'vjs-current-time';
  10736. }
  10737. /**
  10738. * Update current time display
  10739. *
  10740. * @param {Event} [event]
  10741. * The `timeupdate` event that caused this function to run.
  10742. *
  10743. * @listens Player#timeupdate
  10744. */
  10745. updateContent(event) {
  10746. // Allows for smooth scrubbing, when player can't keep up.
  10747. let time;
  10748. if (this.player_.ended()) {
  10749. time = this.player_.duration();
  10750. } else {
  10751. time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  10752. }
  10753. this.updateTextNode_(time);
  10754. }
  10755. }
  10756. /**
  10757. * The text that is added to the `CurrentTimeDisplay` for screen reader users.
  10758. *
  10759. * @type {string}
  10760. * @private
  10761. */
  10762. CurrentTimeDisplay.prototype.labelText_ = 'Current Time';
  10763. /**
  10764. * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
  10765. *
  10766. * @type {string}
  10767. * @protected
  10768. *
  10769. * @deprecated in v7; controlText_ is not used in non-active display Components
  10770. */
  10771. CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
  10772. Component$1.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
  10773. /**
  10774. * @file duration-display.js
  10775. */
  10776. /**
  10777. * Displays the duration
  10778. *
  10779. * @extends Component
  10780. */
  10781. class DurationDisplay extends TimeDisplay {
  10782. /**
  10783. * Creates an instance of this class.
  10784. *
  10785. * @param { import('../../player').default } player
  10786. * The `Player` that this class should be attached to.
  10787. *
  10788. * @param {Object} [options]
  10789. * The key/value store of player options.
  10790. */
  10791. constructor(player, options) {
  10792. super(player, options);
  10793. const updateContent = e => this.updateContent(e);
  10794. // we do not want to/need to throttle duration changes,
  10795. // as they should always display the changed duration as
  10796. // it has changed
  10797. this.on(player, 'durationchange', updateContent);
  10798. // Listen to loadstart because the player duration is reset when a new media element is loaded,
  10799. // but the durationchange on the user agent will not fire.
  10800. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  10801. this.on(player, 'loadstart', updateContent);
  10802. // Also listen for timeupdate (in the parent) and loadedmetadata because removing those
  10803. // listeners could have broken dependent applications/libraries. These
  10804. // can likely be removed for 7.0.
  10805. this.on(player, 'loadedmetadata', updateContent);
  10806. }
  10807. /**
  10808. * Builds the default DOM `className`.
  10809. *
  10810. * @return {string}
  10811. * The DOM `className` for this object.
  10812. */
  10813. buildCSSClass() {
  10814. return 'vjs-duration';
  10815. }
  10816. /**
  10817. * Update duration time display.
  10818. *
  10819. * @param {Event} [event]
  10820. * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
  10821. * this function to be called.
  10822. *
  10823. * @listens Player#durationchange
  10824. * @listens Player#timeupdate
  10825. * @listens Player#loadedmetadata
  10826. */
  10827. updateContent(event) {
  10828. const duration = this.player_.duration();
  10829. this.updateTextNode_(duration);
  10830. }
  10831. }
  10832. /**
  10833. * The text that is added to the `DurationDisplay` for screen reader users.
  10834. *
  10835. * @type {string}
  10836. * @private
  10837. */
  10838. DurationDisplay.prototype.labelText_ = 'Duration';
  10839. /**
  10840. * The text that should display over the `DurationDisplay`s controls. Added to for localization.
  10841. *
  10842. * @type {string}
  10843. * @protected
  10844. *
  10845. * @deprecated in v7; controlText_ is not used in non-active display Components
  10846. */
  10847. DurationDisplay.prototype.controlText_ = 'Duration';
  10848. Component$1.registerComponent('DurationDisplay', DurationDisplay);
  10849. /**
  10850. * @file time-divider.js
  10851. */
  10852. /**
  10853. * The separator between the current time and duration.
  10854. * Can be hidden if it's not needed in the design.
  10855. *
  10856. * @extends Component
  10857. */
  10858. class TimeDivider extends Component$1 {
  10859. /**
  10860. * Create the component's DOM element
  10861. *
  10862. * @return {Element}
  10863. * The element that was created.
  10864. */
  10865. createEl() {
  10866. const el = super.createEl('div', {
  10867. className: 'vjs-time-control vjs-time-divider'
  10868. }, {
  10869. // this element and its contents can be hidden from assistive techs since
  10870. // it is made extraneous by the announcement of the control text
  10871. // for the current time and duration displays
  10872. 'aria-hidden': true
  10873. });
  10874. const div = super.createEl('div');
  10875. const span = super.createEl('span', {
  10876. textContent: '/'
  10877. });
  10878. div.appendChild(span);
  10879. el.appendChild(div);
  10880. return el;
  10881. }
  10882. }
  10883. Component$1.registerComponent('TimeDivider', TimeDivider);
  10884. /**
  10885. * @file remaining-time-display.js
  10886. */
  10887. /**
  10888. * Displays the time left in the video
  10889. *
  10890. * @extends Component
  10891. */
  10892. class RemainingTimeDisplay extends TimeDisplay {
  10893. /**
  10894. * Creates an instance of this class.
  10895. *
  10896. * @param { import('../../player').default } player
  10897. * The `Player` that this class should be attached to.
  10898. *
  10899. * @param {Object} [options]
  10900. * The key/value store of player options.
  10901. */
  10902. constructor(player, options) {
  10903. super(player, options);
  10904. this.on(player, 'durationchange', e => this.updateContent(e));
  10905. }
  10906. /**
  10907. * Builds the default DOM `className`.
  10908. *
  10909. * @return {string}
  10910. * The DOM `className` for this object.
  10911. */
  10912. buildCSSClass() {
  10913. return 'vjs-remaining-time';
  10914. }
  10915. /**
  10916. * Create the `Component`'s DOM element with the "minus" character prepend to the time
  10917. *
  10918. * @return {Element}
  10919. * The element that was created.
  10920. */
  10921. createEl() {
  10922. const el = super.createEl();
  10923. if (this.options_.displayNegative !== false) {
  10924. el.insertBefore(createEl('span', {}, {
  10925. 'aria-hidden': true
  10926. }, '-'), this.contentEl_);
  10927. }
  10928. return el;
  10929. }
  10930. /**
  10931. * Update remaining time display.
  10932. *
  10933. * @param {Event} [event]
  10934. * The `timeupdate` or `durationchange` event that caused this to run.
  10935. *
  10936. * @listens Player#timeupdate
  10937. * @listens Player#durationchange
  10938. */
  10939. updateContent(event) {
  10940. if (typeof this.player_.duration() !== 'number') {
  10941. return;
  10942. }
  10943. let time;
  10944. // @deprecated We should only use remainingTimeDisplay
  10945. // as of video.js 7
  10946. if (this.player_.ended()) {
  10947. time = 0;
  10948. } else if (this.player_.remainingTimeDisplay) {
  10949. time = this.player_.remainingTimeDisplay();
  10950. } else {
  10951. time = this.player_.remainingTime();
  10952. }
  10953. this.updateTextNode_(time);
  10954. }
  10955. }
  10956. /**
  10957. * The text that is added to the `RemainingTimeDisplay` for screen reader users.
  10958. *
  10959. * @type {string}
  10960. * @private
  10961. */
  10962. RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';
  10963. /**
  10964. * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
  10965. *
  10966. * @type {string}
  10967. * @protected
  10968. *
  10969. * @deprecated in v7; controlText_ is not used in non-active display Components
  10970. */
  10971. RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
  10972. Component$1.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
  10973. /**
  10974. * @file live-display.js
  10975. */
  10976. // TODO - Future make it click to snap to live
  10977. /**
  10978. * Displays the live indicator when duration is Infinity.
  10979. *
  10980. * @extends Component
  10981. */
  10982. class LiveDisplay extends Component$1 {
  10983. /**
  10984. * Creates an instance of this class.
  10985. *
  10986. * @param { import('./player').default } player
  10987. * The `Player` that this class should be attached to.
  10988. *
  10989. * @param {Object} [options]
  10990. * The key/value store of player options.
  10991. */
  10992. constructor(player, options) {
  10993. super(player, options);
  10994. this.updateShowing();
  10995. this.on(this.player(), 'durationchange', e => this.updateShowing(e));
  10996. }
  10997. /**
  10998. * Create the `Component`'s DOM element
  10999. *
  11000. * @return {Element}
  11001. * The element that was created.
  11002. */
  11003. createEl() {
  11004. const el = super.createEl('div', {
  11005. className: 'vjs-live-control vjs-control'
  11006. });
  11007. this.contentEl_ = createEl('div', {
  11008. className: 'vjs-live-display'
  11009. }, {
  11010. 'aria-live': 'off'
  11011. });
  11012. this.contentEl_.appendChild(createEl('span', {
  11013. className: 'vjs-control-text',
  11014. textContent: `${this.localize('Stream Type')}\u00a0`
  11015. }));
  11016. this.contentEl_.appendChild(document.createTextNode(this.localize('LIVE')));
  11017. el.appendChild(this.contentEl_);
  11018. return el;
  11019. }
  11020. dispose() {
  11021. this.contentEl_ = null;
  11022. super.dispose();
  11023. }
  11024. /**
  11025. * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide
  11026. * it accordingly
  11027. *
  11028. * @param {Event} [event]
  11029. * The {@link Player#durationchange} event that caused this function to run.
  11030. *
  11031. * @listens Player#durationchange
  11032. */
  11033. updateShowing(event) {
  11034. if (this.player().duration() === Infinity) {
  11035. this.show();
  11036. } else {
  11037. this.hide();
  11038. }
  11039. }
  11040. }
  11041. Component$1.registerComponent('LiveDisplay', LiveDisplay);
  11042. /**
  11043. * @file seek-to-live.js
  11044. */
  11045. /**
  11046. * Displays the live indicator when duration is Infinity.
  11047. *
  11048. * @extends Component
  11049. */
  11050. class SeekToLive extends Button {
  11051. /**
  11052. * Creates an instance of this class.
  11053. *
  11054. * @param { import('./player').default } player
  11055. * The `Player` that this class should be attached to.
  11056. *
  11057. * @param {Object} [options]
  11058. * The key/value store of player options.
  11059. */
  11060. constructor(player, options) {
  11061. super(player, options);
  11062. this.updateLiveEdgeStatus();
  11063. if (this.player_.liveTracker) {
  11064. this.updateLiveEdgeStatusHandler_ = e => this.updateLiveEdgeStatus(e);
  11065. this.on(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  11066. }
  11067. }
  11068. /**
  11069. * Create the `Component`'s DOM element
  11070. *
  11071. * @return {Element}
  11072. * The element that was created.
  11073. */
  11074. createEl() {
  11075. const el = super.createEl('button', {
  11076. className: 'vjs-seek-to-live-control vjs-control'
  11077. });
  11078. this.textEl_ = createEl('span', {
  11079. className: 'vjs-seek-to-live-text',
  11080. textContent: this.localize('LIVE')
  11081. }, {
  11082. 'aria-hidden': 'true'
  11083. });
  11084. el.appendChild(this.textEl_);
  11085. return el;
  11086. }
  11087. /**
  11088. * Update the state of this button if we are at the live edge
  11089. * or not
  11090. */
  11091. updateLiveEdgeStatus() {
  11092. // default to live edge
  11093. if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {
  11094. this.setAttribute('aria-disabled', true);
  11095. this.addClass('vjs-at-live-edge');
  11096. this.controlText('Seek to live, currently playing live');
  11097. } else {
  11098. this.setAttribute('aria-disabled', false);
  11099. this.removeClass('vjs-at-live-edge');
  11100. this.controlText('Seek to live, currently behind live');
  11101. }
  11102. }
  11103. /**
  11104. * On click bring us as near to the live point as possible.
  11105. * This requires that we wait for the next `live-seekable-change`
  11106. * event which will happen every segment length seconds.
  11107. */
  11108. handleClick() {
  11109. this.player_.liveTracker.seekToLiveEdge();
  11110. }
  11111. /**
  11112. * Dispose of the element and stop tracking
  11113. */
  11114. dispose() {
  11115. if (this.player_.liveTracker) {
  11116. this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  11117. }
  11118. this.textEl_ = null;
  11119. super.dispose();
  11120. }
  11121. }
  11122. /**
  11123. * The text that should display over the `SeekToLive`s control. Added for localization.
  11124. *
  11125. * @type {string}
  11126. * @protected
  11127. */
  11128. SeekToLive.prototype.controlText_ = 'Seek to live, currently playing live';
  11129. Component$1.registerComponent('SeekToLive', SeekToLive);
  11130. /**
  11131. * @file num.js
  11132. * @module num
  11133. */
  11134. /**
  11135. * Keep a number between a min and a max value
  11136. *
  11137. * @param {number} number
  11138. * The number to clamp
  11139. *
  11140. * @param {number} min
  11141. * The minimum value
  11142. * @param {number} max
  11143. * The maximum value
  11144. *
  11145. * @return {number}
  11146. * the clamped number
  11147. */
  11148. function clamp(number, min, max) {
  11149. number = Number(number);
  11150. return Math.min(max, Math.max(min, isNaN(number) ? min : number));
  11151. }
  11152. var Num = /*#__PURE__*/Object.freeze({
  11153. __proto__: null,
  11154. clamp: clamp
  11155. });
  11156. /**
  11157. * @file slider.js
  11158. */
  11159. /**
  11160. * The base functionality for a slider. Can be vertical or horizontal.
  11161. * For instance the volume bar or the seek bar on a video is a slider.
  11162. *
  11163. * @extends Component
  11164. */
  11165. class Slider extends Component$1 {
  11166. /**
  11167. * Create an instance of this class
  11168. *
  11169. * @param { import('../player').default } player
  11170. * The `Player` that this class should be attached to.
  11171. *
  11172. * @param {Object} [options]
  11173. * The key/value store of player options.
  11174. */
  11175. constructor(player, options) {
  11176. super(player, options);
  11177. this.handleMouseDown_ = e => this.handleMouseDown(e);
  11178. this.handleMouseUp_ = e => this.handleMouseUp(e);
  11179. this.handleKeyDown_ = e => this.handleKeyDown(e);
  11180. this.handleClick_ = e => this.handleClick(e);
  11181. this.handleMouseMove_ = e => this.handleMouseMove(e);
  11182. this.update_ = e => this.update(e);
  11183. // Set property names to bar to match with the child Slider class is looking for
  11184. this.bar = this.getChild(this.options_.barName);
  11185. // Set a horizontal or vertical class on the slider depending on the slider type
  11186. this.vertical(!!this.options_.vertical);
  11187. this.enable();
  11188. }
  11189. /**
  11190. * Are controls are currently enabled for this slider or not.
  11191. *
  11192. * @return {boolean}
  11193. * true if controls are enabled, false otherwise
  11194. */
  11195. enabled() {
  11196. return this.enabled_;
  11197. }
  11198. /**
  11199. * Enable controls for this slider if they are disabled
  11200. */
  11201. enable() {
  11202. if (this.enabled()) {
  11203. return;
  11204. }
  11205. this.on('mousedown', this.handleMouseDown_);
  11206. this.on('touchstart', this.handleMouseDown_);
  11207. this.on('keydown', this.handleKeyDown_);
  11208. this.on('click', this.handleClick_);
  11209. // TODO: deprecated, controlsvisible does not seem to be fired
  11210. this.on(this.player_, 'controlsvisible', this.update);
  11211. if (this.playerEvent) {
  11212. this.on(this.player_, this.playerEvent, this.update);
  11213. }
  11214. this.removeClass('disabled');
  11215. this.setAttribute('tabindex', 0);
  11216. this.enabled_ = true;
  11217. }
  11218. /**
  11219. * Disable controls for this slider if they are enabled
  11220. */
  11221. disable() {
  11222. if (!this.enabled()) {
  11223. return;
  11224. }
  11225. const doc = this.bar.el_.ownerDocument;
  11226. this.off('mousedown', this.handleMouseDown_);
  11227. this.off('touchstart', this.handleMouseDown_);
  11228. this.off('keydown', this.handleKeyDown_);
  11229. this.off('click', this.handleClick_);
  11230. this.off(this.player_, 'controlsvisible', this.update_);
  11231. this.off(doc, 'mousemove', this.handleMouseMove_);
  11232. this.off(doc, 'mouseup', this.handleMouseUp_);
  11233. this.off(doc, 'touchmove', this.handleMouseMove_);
  11234. this.off(doc, 'touchend', this.handleMouseUp_);
  11235. this.removeAttribute('tabindex');
  11236. this.addClass('disabled');
  11237. if (this.playerEvent) {
  11238. this.off(this.player_, this.playerEvent, this.update);
  11239. }
  11240. this.enabled_ = false;
  11241. }
  11242. /**
  11243. * Create the `Slider`s DOM element.
  11244. *
  11245. * @param {string} type
  11246. * Type of element to create.
  11247. *
  11248. * @param {Object} [props={}]
  11249. * List of properties in Object form.
  11250. *
  11251. * @param {Object} [attributes={}]
  11252. * list of attributes in Object form.
  11253. *
  11254. * @return {Element}
  11255. * The element that gets created.
  11256. */
  11257. createEl(type, props = {}, attributes = {}) {
  11258. // Add the slider element class to all sub classes
  11259. props.className = props.className + ' vjs-slider';
  11260. props = Object.assign({
  11261. tabIndex: 0
  11262. }, props);
  11263. attributes = Object.assign({
  11264. 'role': 'slider',
  11265. 'aria-valuenow': 0,
  11266. 'aria-valuemin': 0,
  11267. 'aria-valuemax': 100
  11268. }, attributes);
  11269. return super.createEl(type, props, attributes);
  11270. }
  11271. /**
  11272. * Handle `mousedown` or `touchstart` events on the `Slider`.
  11273. *
  11274. * @param {MouseEvent} event
  11275. * `mousedown` or `touchstart` event that triggered this function
  11276. *
  11277. * @listens mousedown
  11278. * @listens touchstart
  11279. * @fires Slider#slideractive
  11280. */
  11281. handleMouseDown(event) {
  11282. const doc = this.bar.el_.ownerDocument;
  11283. if (event.type === 'mousedown') {
  11284. event.preventDefault();
  11285. }
  11286. // Do not call preventDefault() on touchstart in Chrome
  11287. // to avoid console warnings. Use a 'touch-action: none' style
  11288. // instead to prevent unintended scrolling.
  11289. // https://developers.google.com/web/updates/2017/01/scrolling-intervention
  11290. if (event.type === 'touchstart' && !IS_CHROME) {
  11291. event.preventDefault();
  11292. }
  11293. blockTextSelection();
  11294. this.addClass('vjs-sliding');
  11295. /**
  11296. * Triggered when the slider is in an active state
  11297. *
  11298. * @event Slider#slideractive
  11299. * @type {MouseEvent}
  11300. */
  11301. this.trigger('slideractive');
  11302. this.on(doc, 'mousemove', this.handleMouseMove_);
  11303. this.on(doc, 'mouseup', this.handleMouseUp_);
  11304. this.on(doc, 'touchmove', this.handleMouseMove_);
  11305. this.on(doc, 'touchend', this.handleMouseUp_);
  11306. this.handleMouseMove(event, true);
  11307. }
  11308. /**
  11309. * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.
  11310. * The `mousemove` and `touchmove` events will only only trigger this function during
  11311. * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and
  11312. * {@link Slider#handleMouseUp}.
  11313. *
  11314. * @param {MouseEvent} event
  11315. * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
  11316. * this function
  11317. * @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.
  11318. *
  11319. * @listens mousemove
  11320. * @listens touchmove
  11321. */
  11322. handleMouseMove(event) {}
  11323. /**
  11324. * Handle `mouseup` or `touchend` events on the `Slider`.
  11325. *
  11326. * @param {MouseEvent} event
  11327. * `mouseup` or `touchend` event that triggered this function.
  11328. *
  11329. * @listens touchend
  11330. * @listens mouseup
  11331. * @fires Slider#sliderinactive
  11332. */
  11333. handleMouseUp(event) {
  11334. const doc = this.bar.el_.ownerDocument;
  11335. unblockTextSelection();
  11336. this.removeClass('vjs-sliding');
  11337. /**
  11338. * Triggered when the slider is no longer in an active state.
  11339. *
  11340. * @event Slider#sliderinactive
  11341. * @type {Event}
  11342. */
  11343. this.trigger('sliderinactive');
  11344. this.off(doc, 'mousemove', this.handleMouseMove_);
  11345. this.off(doc, 'mouseup', this.handleMouseUp_);
  11346. this.off(doc, 'touchmove', this.handleMouseMove_);
  11347. this.off(doc, 'touchend', this.handleMouseUp_);
  11348. this.update();
  11349. }
  11350. /**
  11351. * Update the progress bar of the `Slider`.
  11352. *
  11353. * @return {number}
  11354. * The percentage of progress the progress bar represents as a
  11355. * number from 0 to 1.
  11356. */
  11357. update() {
  11358. // In VolumeBar init we have a setTimeout for update that pops and update
  11359. // to the end of the execution stack. The player is destroyed before then
  11360. // update will cause an error
  11361. // If there's no bar...
  11362. if (!this.el_ || !this.bar) {
  11363. return;
  11364. }
  11365. // clamp progress between 0 and 1
  11366. // and only round to four decimal places, as we round to two below
  11367. const progress = this.getProgress();
  11368. if (progress === this.progress_) {
  11369. return progress;
  11370. }
  11371. this.progress_ = progress;
  11372. this.requestNamedAnimationFrame('Slider#update', () => {
  11373. // Set the new bar width or height
  11374. const sizeKey = this.vertical() ? 'height' : 'width';
  11375. // Convert to a percentage for css value
  11376. this.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + '%';
  11377. });
  11378. return progress;
  11379. }
  11380. /**
  11381. * Get the percentage of the bar that should be filled
  11382. * but clamped and rounded.
  11383. *
  11384. * @return {number}
  11385. * percentage filled that the slider is
  11386. */
  11387. getProgress() {
  11388. return Number(clamp(this.getPercent(), 0, 1).toFixed(4));
  11389. }
  11390. /**
  11391. * Calculate distance for slider
  11392. *
  11393. * @param {Event} event
  11394. * The event that caused this function to run.
  11395. *
  11396. * @return {number}
  11397. * The current position of the Slider.
  11398. * - position.x for vertical `Slider`s
  11399. * - position.y for horizontal `Slider`s
  11400. */
  11401. calculateDistance(event) {
  11402. const position = getPointerPosition(this.el_, event);
  11403. if (this.vertical()) {
  11404. return position.y;
  11405. }
  11406. return position.x;
  11407. }
  11408. /**
  11409. * Handle a `keydown` event on the `Slider`. Watches for left, right, up, and down
  11410. * arrow keys. This function will only be called when the slider has focus. See
  11411. * {@link Slider#handleFocus} and {@link Slider#handleBlur}.
  11412. *
  11413. * @param {KeyboardEvent} event
  11414. * the `keydown` event that caused this function to run.
  11415. *
  11416. * @listens keydown
  11417. */
  11418. handleKeyDown(event) {
  11419. // Left and Down Arrows
  11420. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  11421. event.preventDefault();
  11422. event.stopPropagation();
  11423. this.stepBack();
  11424. // Up and Right Arrows
  11425. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  11426. event.preventDefault();
  11427. event.stopPropagation();
  11428. this.stepForward();
  11429. } else {
  11430. // Pass keydown handling up for unsupported keys
  11431. super.handleKeyDown(event);
  11432. }
  11433. }
  11434. /**
  11435. * Listener for click events on slider, used to prevent clicks
  11436. * from bubbling up to parent elements like button menus.
  11437. *
  11438. * @param {Object} event
  11439. * Event that caused this object to run
  11440. */
  11441. handleClick(event) {
  11442. event.stopPropagation();
  11443. event.preventDefault();
  11444. }
  11445. /**
  11446. * Get/set if slider is horizontal for vertical
  11447. *
  11448. * @param {boolean} [bool]
  11449. * - true if slider is vertical,
  11450. * - false is horizontal
  11451. *
  11452. * @return {boolean}
  11453. * - true if slider is vertical, and getting
  11454. * - false if the slider is horizontal, and getting
  11455. */
  11456. vertical(bool) {
  11457. if (bool === undefined) {
  11458. return this.vertical_ || false;
  11459. }
  11460. this.vertical_ = !!bool;
  11461. if (this.vertical_) {
  11462. this.addClass('vjs-slider-vertical');
  11463. } else {
  11464. this.addClass('vjs-slider-horizontal');
  11465. }
  11466. }
  11467. }
  11468. Component$1.registerComponent('Slider', Slider);
  11469. /**
  11470. * @file load-progress-bar.js
  11471. */
  11472. // get the percent width of a time compared to the total end
  11473. const percentify = (time, end) => clamp(time / end * 100, 0, 100).toFixed(2) + '%';
  11474. /**
  11475. * Shows loading progress
  11476. *
  11477. * @extends Component
  11478. */
  11479. class LoadProgressBar extends Component$1 {
  11480. /**
  11481. * Creates an instance of this class.
  11482. *
  11483. * @param { import('../../player').default } player
  11484. * The `Player` that this class should be attached to.
  11485. *
  11486. * @param {Object} [options]
  11487. * The key/value store of player options.
  11488. */
  11489. constructor(player, options) {
  11490. super(player, options);
  11491. this.partEls_ = [];
  11492. this.on(player, 'progress', e => this.update(e));
  11493. }
  11494. /**
  11495. * Create the `Component`'s DOM element
  11496. *
  11497. * @return {Element}
  11498. * The element that was created.
  11499. */
  11500. createEl() {
  11501. const el = super.createEl('div', {
  11502. className: 'vjs-load-progress'
  11503. });
  11504. const wrapper = createEl('span', {
  11505. className: 'vjs-control-text'
  11506. });
  11507. const loadedText = createEl('span', {
  11508. textContent: this.localize('Loaded')
  11509. });
  11510. const separator = document.createTextNode(': ');
  11511. this.percentageEl_ = createEl('span', {
  11512. className: 'vjs-control-text-loaded-percentage',
  11513. textContent: '0%'
  11514. });
  11515. el.appendChild(wrapper);
  11516. wrapper.appendChild(loadedText);
  11517. wrapper.appendChild(separator);
  11518. wrapper.appendChild(this.percentageEl_);
  11519. return el;
  11520. }
  11521. dispose() {
  11522. this.partEls_ = null;
  11523. this.percentageEl_ = null;
  11524. super.dispose();
  11525. }
  11526. /**
  11527. * Update progress bar
  11528. *
  11529. * @param {Event} [event]
  11530. * The `progress` event that caused this function to run.
  11531. *
  11532. * @listens Player#progress
  11533. */
  11534. update(event) {
  11535. this.requestNamedAnimationFrame('LoadProgressBar#update', () => {
  11536. const liveTracker = this.player_.liveTracker;
  11537. const buffered = this.player_.buffered();
  11538. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  11539. const bufferedEnd = this.player_.bufferedEnd();
  11540. const children = this.partEls_;
  11541. const percent = percentify(bufferedEnd, duration);
  11542. if (this.percent_ !== percent) {
  11543. // update the width of the progress bar
  11544. this.el_.style.width = percent;
  11545. // update the control-text
  11546. textContent(this.percentageEl_, percent);
  11547. this.percent_ = percent;
  11548. }
  11549. // add child elements to represent the individual buffered time ranges
  11550. for (let i = 0; i < buffered.length; i++) {
  11551. const start = buffered.start(i);
  11552. const end = buffered.end(i);
  11553. let part = children[i];
  11554. if (!part) {
  11555. part = this.el_.appendChild(createEl());
  11556. children[i] = part;
  11557. }
  11558. // only update if changed
  11559. if (part.dataset.start === start && part.dataset.end === end) {
  11560. continue;
  11561. }
  11562. part.dataset.start = start;
  11563. part.dataset.end = end;
  11564. // set the percent based on the width of the progress bar (bufferedEnd)
  11565. part.style.left = percentify(start, bufferedEnd);
  11566. part.style.width = percentify(end - start, bufferedEnd);
  11567. }
  11568. // remove unused buffered range elements
  11569. for (let i = children.length; i > buffered.length; i--) {
  11570. this.el_.removeChild(children[i - 1]);
  11571. }
  11572. children.length = buffered.length;
  11573. });
  11574. }
  11575. }
  11576. Component$1.registerComponent('LoadProgressBar', LoadProgressBar);
  11577. /**
  11578. * @file time-tooltip.js
  11579. */
  11580. /**
  11581. * Time tooltips display a time above the progress bar.
  11582. *
  11583. * @extends Component
  11584. */
  11585. class TimeTooltip extends Component$1 {
  11586. /**
  11587. * Creates an instance of this class.
  11588. *
  11589. * @param { import('../../player').default } player
  11590. * The {@link Player} that this class should be attached to.
  11591. *
  11592. * @param {Object} [options]
  11593. * The key/value store of player options.
  11594. */
  11595. constructor(player, options) {
  11596. super(player, options);
  11597. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  11598. }
  11599. /**
  11600. * Create the time tooltip DOM element
  11601. *
  11602. * @return {Element}
  11603. * The element that was created.
  11604. */
  11605. createEl() {
  11606. return super.createEl('div', {
  11607. className: 'vjs-time-tooltip'
  11608. }, {
  11609. 'aria-hidden': 'true'
  11610. });
  11611. }
  11612. /**
  11613. * Updates the position of the time tooltip relative to the `SeekBar`.
  11614. *
  11615. * @param {Object} seekBarRect
  11616. * The `ClientRect` for the {@link SeekBar} element.
  11617. *
  11618. * @param {number} seekBarPoint
  11619. * A number from 0 to 1, representing a horizontal reference point
  11620. * from the left edge of the {@link SeekBar}
  11621. */
  11622. update(seekBarRect, seekBarPoint, content) {
  11623. const tooltipRect = findPosition(this.el_);
  11624. const playerRect = getBoundingClientRect(this.player_.el());
  11625. const seekBarPointPx = seekBarRect.width * seekBarPoint;
  11626. // do nothing if either rect isn't available
  11627. // for example, if the player isn't in the DOM for testing
  11628. if (!playerRect || !tooltipRect) {
  11629. return;
  11630. }
  11631. // This is the space left of the `seekBarPoint` available within the bounds
  11632. // of the player. We calculate any gap between the left edge of the player
  11633. // and the left edge of the `SeekBar` and add the number of pixels in the
  11634. // `SeekBar` before hitting the `seekBarPoint`
  11635. const spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx;
  11636. // This is the space right of the `seekBarPoint` available within the bounds
  11637. // of the player. We calculate the number of pixels from the `seekBarPoint`
  11638. // to the right edge of the `SeekBar` and add to that any gap between the
  11639. // right edge of the `SeekBar` and the player.
  11640. const spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right);
  11641. // This is the number of pixels by which the tooltip will need to be pulled
  11642. // further to the right to center it over the `seekBarPoint`.
  11643. let pullTooltipBy = tooltipRect.width / 2;
  11644. // Adjust the `pullTooltipBy` distance to the left or right depending on
  11645. // the results of the space calculations above.
  11646. if (spaceLeftOfPoint < pullTooltipBy) {
  11647. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  11648. } else if (spaceRightOfPoint < pullTooltipBy) {
  11649. pullTooltipBy = spaceRightOfPoint;
  11650. }
  11651. // Due to the imprecision of decimal/ratio based calculations and varying
  11652. // rounding behaviors, there are cases where the spacing adjustment is off
  11653. // by a pixel or two. This adds insurance to these calculations.
  11654. if (pullTooltipBy < 0) {
  11655. pullTooltipBy = 0;
  11656. } else if (pullTooltipBy > tooltipRect.width) {
  11657. pullTooltipBy = tooltipRect.width;
  11658. }
  11659. // prevent small width fluctuations within 0.4px from
  11660. // changing the value below.
  11661. // This really helps for live to prevent the play
  11662. // progress time tooltip from jittering
  11663. pullTooltipBy = Math.round(pullTooltipBy);
  11664. this.el_.style.right = `-${pullTooltipBy}px`;
  11665. this.write(content);
  11666. }
  11667. /**
  11668. * Write the time to the tooltip DOM element.
  11669. *
  11670. * @param {string} content
  11671. * The formatted time for the tooltip.
  11672. */
  11673. write(content) {
  11674. textContent(this.el_, content);
  11675. }
  11676. /**
  11677. * Updates the position of the time tooltip relative to the `SeekBar`.
  11678. *
  11679. * @param {Object} seekBarRect
  11680. * The `ClientRect` for the {@link SeekBar} element.
  11681. *
  11682. * @param {number} seekBarPoint
  11683. * A number from 0 to 1, representing a horizontal reference point
  11684. * from the left edge of the {@link SeekBar}
  11685. *
  11686. * @param {number} time
  11687. * The time to update the tooltip to, not used during live playback
  11688. *
  11689. * @param {Function} cb
  11690. * A function that will be called during the request animation frame
  11691. * for tooltips that need to do additional animations from the default
  11692. */
  11693. updateTime(seekBarRect, seekBarPoint, time, cb) {
  11694. this.requestNamedAnimationFrame('TimeTooltip#updateTime', () => {
  11695. let content;
  11696. const duration = this.player_.duration();
  11697. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  11698. const liveWindow = this.player_.liveTracker.liveWindow();
  11699. const secondsBehind = liveWindow - seekBarPoint * liveWindow;
  11700. content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow);
  11701. } else {
  11702. content = formatTime(time, duration);
  11703. }
  11704. this.update(seekBarRect, seekBarPoint, content);
  11705. if (cb) {
  11706. cb();
  11707. }
  11708. });
  11709. }
  11710. }
  11711. Component$1.registerComponent('TimeTooltip', TimeTooltip);
  11712. /**
  11713. * @file play-progress-bar.js
  11714. */
  11715. /**
  11716. * Used by {@link SeekBar} to display media playback progress as part of the
  11717. * {@link ProgressControl}.
  11718. *
  11719. * @extends Component
  11720. */
  11721. class PlayProgressBar extends Component$1 {
  11722. /**
  11723. * Creates an instance of this class.
  11724. *
  11725. * @param { import('../../player').default } player
  11726. * The {@link Player} that this class should be attached to.
  11727. *
  11728. * @param {Object} [options]
  11729. * The key/value store of player options.
  11730. */
  11731. constructor(player, options) {
  11732. super(player, options);
  11733. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  11734. }
  11735. /**
  11736. * Create the the DOM element for this class.
  11737. *
  11738. * @return {Element}
  11739. * The element that was created.
  11740. */
  11741. createEl() {
  11742. return super.createEl('div', {
  11743. className: 'vjs-play-progress vjs-slider-bar'
  11744. }, {
  11745. 'aria-hidden': 'true'
  11746. });
  11747. }
  11748. /**
  11749. * Enqueues updates to its own DOM as well as the DOM of its
  11750. * {@link TimeTooltip} child.
  11751. *
  11752. * @param {Object} seekBarRect
  11753. * The `ClientRect` for the {@link SeekBar} element.
  11754. *
  11755. * @param {number} seekBarPoint
  11756. * A number from 0 to 1, representing a horizontal reference point
  11757. * from the left edge of the {@link SeekBar}
  11758. */
  11759. update(seekBarRect, seekBarPoint) {
  11760. const timeTooltip = this.getChild('timeTooltip');
  11761. if (!timeTooltip) {
  11762. return;
  11763. }
  11764. const time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  11765. timeTooltip.updateTime(seekBarRect, seekBarPoint, time);
  11766. }
  11767. }
  11768. /**
  11769. * Default options for {@link PlayProgressBar}.
  11770. *
  11771. * @type {Object}
  11772. * @private
  11773. */
  11774. PlayProgressBar.prototype.options_ = {
  11775. children: []
  11776. };
  11777. // Time tooltips should not be added to a player on mobile devices
  11778. if (!IS_IOS && !IS_ANDROID) {
  11779. PlayProgressBar.prototype.options_.children.push('timeTooltip');
  11780. }
  11781. Component$1.registerComponent('PlayProgressBar', PlayProgressBar);
  11782. /**
  11783. * @file mouse-time-display.js
  11784. */
  11785. /**
  11786. * The {@link MouseTimeDisplay} component tracks mouse movement over the
  11787. * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}
  11788. * indicating the time which is represented by a given point in the
  11789. * {@link ProgressControl}.
  11790. *
  11791. * @extends Component
  11792. */
  11793. class MouseTimeDisplay extends Component$1 {
  11794. /**
  11795. * Creates an instance of this class.
  11796. *
  11797. * @param { import('../../player').default } player
  11798. * The {@link Player} that this class should be attached to.
  11799. *
  11800. * @param {Object} [options]
  11801. * The key/value store of player options.
  11802. */
  11803. constructor(player, options) {
  11804. super(player, options);
  11805. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  11806. }
  11807. /**
  11808. * Create the DOM element for this class.
  11809. *
  11810. * @return {Element}
  11811. * The element that was created.
  11812. */
  11813. createEl() {
  11814. return super.createEl('div', {
  11815. className: 'vjs-mouse-display'
  11816. });
  11817. }
  11818. /**
  11819. * Enqueues updates to its own DOM as well as the DOM of its
  11820. * {@link TimeTooltip} child.
  11821. *
  11822. * @param {Object} seekBarRect
  11823. * The `ClientRect` for the {@link SeekBar} element.
  11824. *
  11825. * @param {number} seekBarPoint
  11826. * A number from 0 to 1, representing a horizontal reference point
  11827. * from the left edge of the {@link SeekBar}
  11828. */
  11829. update(seekBarRect, seekBarPoint) {
  11830. const time = seekBarPoint * this.player_.duration();
  11831. this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, () => {
  11832. this.el_.style.left = `${seekBarRect.width * seekBarPoint}px`;
  11833. });
  11834. }
  11835. }
  11836. /**
  11837. * Default options for `MouseTimeDisplay`
  11838. *
  11839. * @type {Object}
  11840. * @private
  11841. */
  11842. MouseTimeDisplay.prototype.options_ = {
  11843. children: ['timeTooltip']
  11844. };
  11845. Component$1.registerComponent('MouseTimeDisplay', MouseTimeDisplay);
  11846. /**
  11847. * @file seek-bar.js
  11848. */
  11849. // The number of seconds the `step*` functions move the timeline.
  11850. const STEP_SECONDS = 5;
  11851. // The multiplier of STEP_SECONDS that PgUp/PgDown move the timeline.
  11852. const PAGE_KEY_MULTIPLIER = 12;
  11853. /**
  11854. * Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
  11855. * as its `bar`.
  11856. *
  11857. * @extends Slider
  11858. */
  11859. class SeekBar extends Slider {
  11860. /**
  11861. * Creates an instance of this class.
  11862. *
  11863. * @param { import('../../player').default } player
  11864. * The `Player` that this class should be attached to.
  11865. *
  11866. * @param {Object} [options]
  11867. * The key/value store of player options.
  11868. */
  11869. constructor(player, options) {
  11870. super(player, options);
  11871. this.setEventHandlers_();
  11872. }
  11873. /**
  11874. * Sets the event handlers
  11875. *
  11876. * @private
  11877. */
  11878. setEventHandlers_() {
  11879. this.update_ = bind_(this, this.update);
  11880. this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);
  11881. this.on(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  11882. if (this.player_.liveTracker) {
  11883. this.on(this.player_.liveTracker, 'liveedgechange', this.update);
  11884. }
  11885. // when playing, let's ensure we smoothly update the play progress bar
  11886. // via an interval
  11887. this.updateInterval = null;
  11888. this.enableIntervalHandler_ = e => this.enableInterval_(e);
  11889. this.disableIntervalHandler_ = e => this.disableInterval_(e);
  11890. this.on(this.player_, ['playing'], this.enableIntervalHandler_);
  11891. this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  11892. // we don't need to update the play progress if the document is hidden,
  11893. // also, this causes the CPU to spike and eventually crash the page on IE11.
  11894. if ('hidden' in document && 'visibilityState' in document) {
  11895. this.on(document, 'visibilitychange', this.toggleVisibility_);
  11896. }
  11897. }
  11898. toggleVisibility_(e) {
  11899. if (document.visibilityState === 'hidden') {
  11900. this.cancelNamedAnimationFrame('SeekBar#update');
  11901. this.cancelNamedAnimationFrame('Slider#update');
  11902. this.disableInterval_(e);
  11903. } else {
  11904. if (!this.player_.ended() && !this.player_.paused()) {
  11905. this.enableInterval_();
  11906. }
  11907. // we just switched back to the page and someone may be looking, so, update ASAP
  11908. this.update();
  11909. }
  11910. }
  11911. enableInterval_() {
  11912. if (this.updateInterval) {
  11913. return;
  11914. }
  11915. this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);
  11916. }
  11917. disableInterval_(e) {
  11918. if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== 'ended') {
  11919. return;
  11920. }
  11921. if (!this.updateInterval) {
  11922. return;
  11923. }
  11924. this.clearInterval(this.updateInterval);
  11925. this.updateInterval = null;
  11926. }
  11927. /**
  11928. * Create the `Component`'s DOM element
  11929. *
  11930. * @return {Element}
  11931. * The element that was created.
  11932. */
  11933. createEl() {
  11934. return super.createEl('div', {
  11935. className: 'vjs-progress-holder'
  11936. }, {
  11937. 'aria-label': this.localize('Progress Bar')
  11938. });
  11939. }
  11940. /**
  11941. * This function updates the play progress bar and accessibility
  11942. * attributes to whatever is passed in.
  11943. *
  11944. * @param {Event} [event]
  11945. * The `timeupdate` or `ended` event that caused this to run.
  11946. *
  11947. * @listens Player#timeupdate
  11948. *
  11949. * @return {number}
  11950. * The current percent at a number from 0-1
  11951. */
  11952. update(event) {
  11953. // ignore updates while the tab is hidden
  11954. if (document.visibilityState === 'hidden') {
  11955. return;
  11956. }
  11957. const percent = super.update();
  11958. this.requestNamedAnimationFrame('SeekBar#update', () => {
  11959. const currentTime = this.player_.ended() ? this.player_.duration() : this.getCurrentTime_();
  11960. const liveTracker = this.player_.liveTracker;
  11961. let duration = this.player_.duration();
  11962. if (liveTracker && liveTracker.isLive()) {
  11963. duration = this.player_.liveTracker.liveCurrentTime();
  11964. }
  11965. if (this.percent_ !== percent) {
  11966. // machine readable value of progress bar (percentage complete)
  11967. this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
  11968. this.percent_ = percent;
  11969. }
  11970. if (this.currentTime_ !== currentTime || this.duration_ !== duration) {
  11971. // human readable value of progress bar (time complete)
  11972. this.el_.setAttribute('aria-valuetext', this.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));
  11973. this.currentTime_ = currentTime;
  11974. this.duration_ = duration;
  11975. }
  11976. // update the progress bar time tooltip with the current time
  11977. if (this.bar) {
  11978. this.bar.update(getBoundingClientRect(this.el()), this.getProgress());
  11979. }
  11980. });
  11981. return percent;
  11982. }
  11983. /**
  11984. * Prevent liveThreshold from causing seeks to seem like they
  11985. * are not happening from a user perspective.
  11986. *
  11987. * @param {number} ct
  11988. * current time to seek to
  11989. */
  11990. userSeek_(ct) {
  11991. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  11992. this.player_.liveTracker.nextSeekedFromUser();
  11993. }
  11994. this.player_.currentTime(ct);
  11995. }
  11996. /**
  11997. * Get the value of current time but allows for smooth scrubbing,
  11998. * when player can't keep up.
  11999. *
  12000. * @return {number}
  12001. * The current time value to display
  12002. *
  12003. * @private
  12004. */
  12005. getCurrentTime_() {
  12006. return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  12007. }
  12008. /**
  12009. * Get the percentage of media played so far.
  12010. *
  12011. * @return {number}
  12012. * The percentage of media played so far (0 to 1).
  12013. */
  12014. getPercent() {
  12015. const currentTime = this.getCurrentTime_();
  12016. let percent;
  12017. const liveTracker = this.player_.liveTracker;
  12018. if (liveTracker && liveTracker.isLive()) {
  12019. percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow();
  12020. // prevent the percent from changing at the live edge
  12021. if (liveTracker.atLiveEdge()) {
  12022. percent = 1;
  12023. }
  12024. } else {
  12025. percent = currentTime / this.player_.duration();
  12026. }
  12027. return percent;
  12028. }
  12029. /**
  12030. * Handle mouse down on seek bar
  12031. *
  12032. * @param {MouseEvent} event
  12033. * The `mousedown` event that caused this to run.
  12034. *
  12035. * @listens mousedown
  12036. */
  12037. handleMouseDown(event) {
  12038. if (!isSingleLeftClick(event)) {
  12039. return;
  12040. }
  12041. // Stop event propagation to prevent double fire in progress-control.js
  12042. event.stopPropagation();
  12043. this.videoWasPlaying = !this.player_.paused();
  12044. this.player_.pause();
  12045. super.handleMouseDown(event);
  12046. }
  12047. /**
  12048. * Handle mouse move on seek bar
  12049. *
  12050. * @param {MouseEvent} event
  12051. * The `mousemove` event that caused this to run.
  12052. * @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
  12053. *
  12054. * @listens mousemove
  12055. */
  12056. handleMouseMove(event, mouseDown = false) {
  12057. if (!isSingleLeftClick(event)) {
  12058. return;
  12059. }
  12060. if (!mouseDown && !this.player_.scrubbing()) {
  12061. this.player_.scrubbing(true);
  12062. }
  12063. let newTime;
  12064. const distance = this.calculateDistance(event);
  12065. const liveTracker = this.player_.liveTracker;
  12066. if (!liveTracker || !liveTracker.isLive()) {
  12067. newTime = distance * this.player_.duration();
  12068. // Don't let video end while scrubbing.
  12069. if (newTime === this.player_.duration()) {
  12070. newTime = newTime - 0.1;
  12071. }
  12072. } else {
  12073. if (distance >= 0.99) {
  12074. liveTracker.seekToLiveEdge();
  12075. return;
  12076. }
  12077. const seekableStart = liveTracker.seekableStart();
  12078. const seekableEnd = liveTracker.liveCurrentTime();
  12079. newTime = seekableStart + distance * liveTracker.liveWindow();
  12080. // Don't let video end while scrubbing.
  12081. if (newTime >= seekableEnd) {
  12082. newTime = seekableEnd;
  12083. }
  12084. // Compensate for precision differences so that currentTime is not less
  12085. // than seekable start
  12086. if (newTime <= seekableStart) {
  12087. newTime = seekableStart + 0.1;
  12088. }
  12089. // On android seekableEnd can be Infinity sometimes,
  12090. // this will cause newTime to be Infinity, which is
  12091. // not a valid currentTime.
  12092. if (newTime === Infinity) {
  12093. return;
  12094. }
  12095. }
  12096. // Set new time (tell player to seek to new time)
  12097. this.userSeek_(newTime);
  12098. }
  12099. enable() {
  12100. super.enable();
  12101. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  12102. if (!mouseTimeDisplay) {
  12103. return;
  12104. }
  12105. mouseTimeDisplay.show();
  12106. }
  12107. disable() {
  12108. super.disable();
  12109. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  12110. if (!mouseTimeDisplay) {
  12111. return;
  12112. }
  12113. mouseTimeDisplay.hide();
  12114. }
  12115. /**
  12116. * Handle mouse up on seek bar
  12117. *
  12118. * @param {MouseEvent} event
  12119. * The `mouseup` event that caused this to run.
  12120. *
  12121. * @listens mouseup
  12122. */
  12123. handleMouseUp(event) {
  12124. super.handleMouseUp(event);
  12125. // Stop event propagation to prevent double fire in progress-control.js
  12126. if (event) {
  12127. event.stopPropagation();
  12128. }
  12129. this.player_.scrubbing(false);
  12130. /**
  12131. * Trigger timeupdate because we're done seeking and the time has changed.
  12132. * This is particularly useful for if the player is paused to time the time displays.
  12133. *
  12134. * @event Tech#timeupdate
  12135. * @type {Event}
  12136. */
  12137. this.player_.trigger({
  12138. type: 'timeupdate',
  12139. target: this,
  12140. manuallyTriggered: true
  12141. });
  12142. if (this.videoWasPlaying) {
  12143. silencePromise(this.player_.play());
  12144. } else {
  12145. // We're done seeking and the time has changed.
  12146. // If the player is paused, make sure we display the correct time on the seek bar.
  12147. this.update_();
  12148. }
  12149. }
  12150. /**
  12151. * Move more quickly fast forward for keyboard-only users
  12152. */
  12153. stepForward() {
  12154. this.userSeek_(this.player_.currentTime() + STEP_SECONDS);
  12155. }
  12156. /**
  12157. * Move more quickly rewind for keyboard-only users
  12158. */
  12159. stepBack() {
  12160. this.userSeek_(this.player_.currentTime() - STEP_SECONDS);
  12161. }
  12162. /**
  12163. * Toggles the playback state of the player
  12164. * This gets called when enter or space is used on the seekbar
  12165. *
  12166. * @param {KeyboardEvent} event
  12167. * The `keydown` event that caused this function to be called
  12168. *
  12169. */
  12170. handleAction(event) {
  12171. if (this.player_.paused()) {
  12172. this.player_.play();
  12173. } else {
  12174. this.player_.pause();
  12175. }
  12176. }
  12177. /**
  12178. * Called when this SeekBar has focus and a key gets pressed down.
  12179. * Supports the following keys:
  12180. *
  12181. * Space or Enter key fire a click event
  12182. * Home key moves to start of the timeline
  12183. * End key moves to end of the timeline
  12184. * Digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline
  12185. * PageDown key moves back a larger step than ArrowDown
  12186. * PageUp key moves forward a large step
  12187. *
  12188. * @param {KeyboardEvent} event
  12189. * The `keydown` event that caused this function to be called.
  12190. *
  12191. * @listens keydown
  12192. */
  12193. handleKeyDown(event) {
  12194. const liveTracker = this.player_.liveTracker;
  12195. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  12196. event.preventDefault();
  12197. event.stopPropagation();
  12198. this.handleAction(event);
  12199. } else if (keycode.isEventKey(event, 'Home')) {
  12200. event.preventDefault();
  12201. event.stopPropagation();
  12202. this.userSeek_(0);
  12203. } else if (keycode.isEventKey(event, 'End')) {
  12204. event.preventDefault();
  12205. event.stopPropagation();
  12206. if (liveTracker && liveTracker.isLive()) {
  12207. this.userSeek_(liveTracker.liveCurrentTime());
  12208. } else {
  12209. this.userSeek_(this.player_.duration());
  12210. }
  12211. } else if (/^[0-9]$/.test(keycode(event))) {
  12212. event.preventDefault();
  12213. event.stopPropagation();
  12214. const gotoFraction = (keycode.codes[keycode(event)] - keycode.codes['0']) * 10.0 / 100.0;
  12215. if (liveTracker && liveTracker.isLive()) {
  12216. this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);
  12217. } else {
  12218. this.userSeek_(this.player_.duration() * gotoFraction);
  12219. }
  12220. } else if (keycode.isEventKey(event, 'PgDn')) {
  12221. event.preventDefault();
  12222. event.stopPropagation();
  12223. this.userSeek_(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  12224. } else if (keycode.isEventKey(event, 'PgUp')) {
  12225. event.preventDefault();
  12226. event.stopPropagation();
  12227. this.userSeek_(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  12228. } else {
  12229. // Pass keydown handling up for unsupported keys
  12230. super.handleKeyDown(event);
  12231. }
  12232. }
  12233. dispose() {
  12234. this.disableInterval_();
  12235. this.off(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  12236. if (this.player_.liveTracker) {
  12237. this.off(this.player_.liveTracker, 'liveedgechange', this.update);
  12238. }
  12239. this.off(this.player_, ['playing'], this.enableIntervalHandler_);
  12240. this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  12241. // we don't need to update the play progress if the document is hidden,
  12242. // also, this causes the CPU to spike and eventually crash the page on IE11.
  12243. if ('hidden' in document && 'visibilityState' in document) {
  12244. this.off(document, 'visibilitychange', this.toggleVisibility_);
  12245. }
  12246. super.dispose();
  12247. }
  12248. }
  12249. /**
  12250. * Default options for the `SeekBar`
  12251. *
  12252. * @type {Object}
  12253. * @private
  12254. */
  12255. SeekBar.prototype.options_ = {
  12256. children: ['loadProgressBar', 'playProgressBar'],
  12257. barName: 'playProgressBar'
  12258. };
  12259. // MouseTimeDisplay tooltips should not be added to a player on mobile devices
  12260. if (!IS_IOS && !IS_ANDROID) {
  12261. SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay');
  12262. }
  12263. Component$1.registerComponent('SeekBar', SeekBar);
  12264. /**
  12265. * @file progress-control.js
  12266. */
  12267. /**
  12268. * The Progress Control component contains the seek bar, load progress,
  12269. * and play progress.
  12270. *
  12271. * @extends Component
  12272. */
  12273. class ProgressControl extends Component$1 {
  12274. /**
  12275. * Creates an instance of this class.
  12276. *
  12277. * @param { import('../../player').default } player
  12278. * The `Player` that this class should be attached to.
  12279. *
  12280. * @param {Object} [options]
  12281. * The key/value store of player options.
  12282. */
  12283. constructor(player, options) {
  12284. super(player, options);
  12285. this.handleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  12286. this.throttledHandleMouseSeek = throttle(bind_(this, this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);
  12287. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  12288. this.handleMouseDownHandler_ = e => this.handleMouseDown(e);
  12289. this.enable();
  12290. }
  12291. /**
  12292. * Create the `Component`'s DOM element
  12293. *
  12294. * @return {Element}
  12295. * The element that was created.
  12296. */
  12297. createEl() {
  12298. return super.createEl('div', {
  12299. className: 'vjs-progress-control vjs-control'
  12300. });
  12301. }
  12302. /**
  12303. * When the mouse moves over the `ProgressControl`, the pointer position
  12304. * gets passed down to the `MouseTimeDisplay` component.
  12305. *
  12306. * @param {Event} event
  12307. * The `mousemove` event that caused this function to run.
  12308. *
  12309. * @listen mousemove
  12310. */
  12311. handleMouseMove(event) {
  12312. const seekBar = this.getChild('seekBar');
  12313. if (!seekBar) {
  12314. return;
  12315. }
  12316. const playProgressBar = seekBar.getChild('playProgressBar');
  12317. const mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');
  12318. if (!playProgressBar && !mouseTimeDisplay) {
  12319. return;
  12320. }
  12321. const seekBarEl = seekBar.el();
  12322. const seekBarRect = findPosition(seekBarEl);
  12323. let seekBarPoint = getPointerPosition(seekBarEl, event).x;
  12324. // The default skin has a gap on either side of the `SeekBar`. This means
  12325. // that it's possible to trigger this behavior outside the boundaries of
  12326. // the `SeekBar`. This ensures we stay within it at all times.
  12327. seekBarPoint = clamp(seekBarPoint, 0, 1);
  12328. if (mouseTimeDisplay) {
  12329. mouseTimeDisplay.update(seekBarRect, seekBarPoint);
  12330. }
  12331. if (playProgressBar) {
  12332. playProgressBar.update(seekBarRect, seekBar.getProgress());
  12333. }
  12334. }
  12335. /**
  12336. * A throttled version of the {@link ProgressControl#handleMouseSeek} listener.
  12337. *
  12338. * @method ProgressControl#throttledHandleMouseSeek
  12339. * @param {Event} event
  12340. * The `mousemove` event that caused this function to run.
  12341. *
  12342. * @listen mousemove
  12343. * @listen touchmove
  12344. */
  12345. /**
  12346. * Handle `mousemove` or `touchmove` events on the `ProgressControl`.
  12347. *
  12348. * @param {Event} event
  12349. * `mousedown` or `touchstart` event that triggered this function
  12350. *
  12351. * @listens mousemove
  12352. * @listens touchmove
  12353. */
  12354. handleMouseSeek(event) {
  12355. const seekBar = this.getChild('seekBar');
  12356. if (seekBar) {
  12357. seekBar.handleMouseMove(event);
  12358. }
  12359. }
  12360. /**
  12361. * Are controls are currently enabled for this progress control.
  12362. *
  12363. * @return {boolean}
  12364. * true if controls are enabled, false otherwise
  12365. */
  12366. enabled() {
  12367. return this.enabled_;
  12368. }
  12369. /**
  12370. * Disable all controls on the progress control and its children
  12371. */
  12372. disable() {
  12373. this.children().forEach(child => child.disable && child.disable());
  12374. if (!this.enabled()) {
  12375. return;
  12376. }
  12377. this.off(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  12378. this.off(this.el_, 'mousemove', this.handleMouseMove);
  12379. this.removeListenersAddedOnMousedownAndTouchstart();
  12380. this.addClass('disabled');
  12381. this.enabled_ = false;
  12382. // Restore normal playback state if controls are disabled while scrubbing
  12383. if (this.player_.scrubbing()) {
  12384. const seekBar = this.getChild('seekBar');
  12385. this.player_.scrubbing(false);
  12386. if (seekBar.videoWasPlaying) {
  12387. silencePromise(this.player_.play());
  12388. }
  12389. }
  12390. }
  12391. /**
  12392. * Enable all controls on the progress control and its children
  12393. */
  12394. enable() {
  12395. this.children().forEach(child => child.enable && child.enable());
  12396. if (this.enabled()) {
  12397. return;
  12398. }
  12399. this.on(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  12400. this.on(this.el_, 'mousemove', this.handleMouseMove);
  12401. this.removeClass('disabled');
  12402. this.enabled_ = true;
  12403. }
  12404. /**
  12405. * Cleanup listeners after the user finishes interacting with the progress controls
  12406. */
  12407. removeListenersAddedOnMousedownAndTouchstart() {
  12408. const doc = this.el_.ownerDocument;
  12409. this.off(doc, 'mousemove', this.throttledHandleMouseSeek);
  12410. this.off(doc, 'touchmove', this.throttledHandleMouseSeek);
  12411. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  12412. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  12413. }
  12414. /**
  12415. * Handle `mousedown` or `touchstart` events on the `ProgressControl`.
  12416. *
  12417. * @param {Event} event
  12418. * `mousedown` or `touchstart` event that triggered this function
  12419. *
  12420. * @listens mousedown
  12421. * @listens touchstart
  12422. */
  12423. handleMouseDown(event) {
  12424. const doc = this.el_.ownerDocument;
  12425. const seekBar = this.getChild('seekBar');
  12426. if (seekBar) {
  12427. seekBar.handleMouseDown(event);
  12428. }
  12429. this.on(doc, 'mousemove', this.throttledHandleMouseSeek);
  12430. this.on(doc, 'touchmove', this.throttledHandleMouseSeek);
  12431. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  12432. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  12433. }
  12434. /**
  12435. * Handle `mouseup` or `touchend` events on the `ProgressControl`.
  12436. *
  12437. * @param {Event} event
  12438. * `mouseup` or `touchend` event that triggered this function.
  12439. *
  12440. * @listens touchend
  12441. * @listens mouseup
  12442. */
  12443. handleMouseUp(event) {
  12444. const seekBar = this.getChild('seekBar');
  12445. if (seekBar) {
  12446. seekBar.handleMouseUp(event);
  12447. }
  12448. this.removeListenersAddedOnMousedownAndTouchstart();
  12449. }
  12450. }
  12451. /**
  12452. * Default options for `ProgressControl`
  12453. *
  12454. * @type {Object}
  12455. * @private
  12456. */
  12457. ProgressControl.prototype.options_ = {
  12458. children: ['seekBar']
  12459. };
  12460. Component$1.registerComponent('ProgressControl', ProgressControl);
  12461. /**
  12462. * @file picture-in-picture-toggle.js
  12463. */
  12464. /**
  12465. * Toggle Picture-in-Picture mode
  12466. *
  12467. * @extends Button
  12468. */
  12469. class PictureInPictureToggle extends Button {
  12470. /**
  12471. * Creates an instance of this class.
  12472. *
  12473. * @param { import('./player').default } player
  12474. * The `Player` that this class should be attached to.
  12475. *
  12476. * @param {Object} [options]
  12477. * The key/value store of player options.
  12478. *
  12479. * @listens Player#enterpictureinpicture
  12480. * @listens Player#leavepictureinpicture
  12481. */
  12482. constructor(player, options) {
  12483. super(player, options);
  12484. this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], e => this.handlePictureInPictureChange(e));
  12485. this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], e => this.handlePictureInPictureEnabledChange(e));
  12486. this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], () => {
  12487. // This audio detection will not detect HLS or DASH audio-only streams because there was no reliable way to detect them at the time
  12488. const isSourceAudio = player.currentType().substring(0, 5) === 'audio';
  12489. if (isSourceAudio || player.audioPosterMode() || player.audioOnlyMode()) {
  12490. if (player.isInPictureInPicture()) {
  12491. player.exitPictureInPicture();
  12492. }
  12493. this.hide();
  12494. } else {
  12495. this.show();
  12496. }
  12497. });
  12498. // TODO: Deactivate button on player emptied event.
  12499. this.disable();
  12500. }
  12501. /**
  12502. * Builds the default DOM `className`.
  12503. *
  12504. * @return {string}
  12505. * The DOM `className` for this object.
  12506. */
  12507. buildCSSClass() {
  12508. return `vjs-picture-in-picture-control ${super.buildCSSClass()}`;
  12509. }
  12510. /**
  12511. * Enables or disables button based on availability of a Picture-In-Picture mode.
  12512. *
  12513. * Enabled if
  12514. * - `player.options().enableDocumentPictureInPicture` is true and
  12515. * window.documentPictureInPicture is available; or
  12516. * - `player.disablePictureInPicture()` is false and
  12517. * element.requestPictureInPicture is available
  12518. */
  12519. handlePictureInPictureEnabledChange() {
  12520. if (document.pictureInPictureEnabled && this.player_.disablePictureInPicture() === false || this.player_.options_.enableDocumentPictureInPicture && 'documentPictureInPicture' in window) {
  12521. this.enable();
  12522. } else {
  12523. this.disable();
  12524. }
  12525. }
  12526. /**
  12527. * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.
  12528. *
  12529. * @param {Event} [event]
  12530. * The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be
  12531. * called.
  12532. *
  12533. * @listens Player#enterpictureinpicture
  12534. * @listens Player#leavepictureinpicture
  12535. */
  12536. handlePictureInPictureChange(event) {
  12537. if (this.player_.isInPictureInPicture()) {
  12538. this.controlText('Exit Picture-in-Picture');
  12539. } else {
  12540. this.controlText('Picture-in-Picture');
  12541. }
  12542. this.handlePictureInPictureEnabledChange();
  12543. }
  12544. /**
  12545. * This gets called when an `PictureInPictureToggle` is "clicked". See
  12546. * {@link ClickableComponent} for more detailed information on what a click can be.
  12547. *
  12548. * @param {Event} [event]
  12549. * The `keydown`, `tap`, or `click` event that caused this function to be
  12550. * called.
  12551. *
  12552. * @listens tap
  12553. * @listens click
  12554. */
  12555. handleClick(event) {
  12556. if (!this.player_.isInPictureInPicture()) {
  12557. this.player_.requestPictureInPicture();
  12558. } else {
  12559. this.player_.exitPictureInPicture();
  12560. }
  12561. }
  12562. }
  12563. /**
  12564. * The text that should display over the `PictureInPictureToggle`s controls. Added for localization.
  12565. *
  12566. * @type {string}
  12567. * @protected
  12568. */
  12569. PictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture';
  12570. Component$1.registerComponent('PictureInPictureToggle', PictureInPictureToggle);
  12571. /**
  12572. * @file fullscreen-toggle.js
  12573. */
  12574. /**
  12575. * Toggle fullscreen video
  12576. *
  12577. * @extends Button
  12578. */
  12579. class FullscreenToggle extends Button {
  12580. /**
  12581. * Creates an instance of this class.
  12582. *
  12583. * @param { import('./player').default } player
  12584. * The `Player` that this class should be attached to.
  12585. *
  12586. * @param {Object} [options]
  12587. * The key/value store of player options.
  12588. */
  12589. constructor(player, options) {
  12590. super(player, options);
  12591. this.on(player, 'fullscreenchange', e => this.handleFullscreenChange(e));
  12592. if (document[player.fsApi_.fullscreenEnabled] === false) {
  12593. this.disable();
  12594. }
  12595. }
  12596. /**
  12597. * Builds the default DOM `className`.
  12598. *
  12599. * @return {string}
  12600. * The DOM `className` for this object.
  12601. */
  12602. buildCSSClass() {
  12603. return `vjs-fullscreen-control ${super.buildCSSClass()}`;
  12604. }
  12605. /**
  12606. * Handles fullscreenchange on the player and change control text accordingly.
  12607. *
  12608. * @param {Event} [event]
  12609. * The {@link Player#fullscreenchange} event that caused this function to be
  12610. * called.
  12611. *
  12612. * @listens Player#fullscreenchange
  12613. */
  12614. handleFullscreenChange(event) {
  12615. if (this.player_.isFullscreen()) {
  12616. this.controlText('Exit Fullscreen');
  12617. } else {
  12618. this.controlText('Fullscreen');
  12619. }
  12620. }
  12621. /**
  12622. * This gets called when an `FullscreenToggle` is "clicked". See
  12623. * {@link ClickableComponent} for more detailed information on what a click can be.
  12624. *
  12625. * @param {Event} [event]
  12626. * The `keydown`, `tap`, or `click` event that caused this function to be
  12627. * called.
  12628. *
  12629. * @listens tap
  12630. * @listens click
  12631. */
  12632. handleClick(event) {
  12633. if (!this.player_.isFullscreen()) {
  12634. this.player_.requestFullscreen();
  12635. } else {
  12636. this.player_.exitFullscreen();
  12637. }
  12638. }
  12639. }
  12640. /**
  12641. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  12642. *
  12643. * @type {string}
  12644. * @protected
  12645. */
  12646. FullscreenToggle.prototype.controlText_ = 'Fullscreen';
  12647. Component$1.registerComponent('FullscreenToggle', FullscreenToggle);
  12648. /**
  12649. * Check if volume control is supported and if it isn't hide the
  12650. * `Component` that was passed using the `vjs-hidden` class.
  12651. *
  12652. * @param { import('../../component').default } self
  12653. * The component that should be hidden if volume is unsupported
  12654. *
  12655. * @param { import('../../player').default } player
  12656. * A reference to the player
  12657. *
  12658. * @private
  12659. */
  12660. const checkVolumeSupport = function (self, player) {
  12661. // hide volume controls when they're not supported by the current tech
  12662. if (player.tech_ && !player.tech_.featuresVolumeControl) {
  12663. self.addClass('vjs-hidden');
  12664. }
  12665. self.on(player, 'loadstart', function () {
  12666. if (!player.tech_.featuresVolumeControl) {
  12667. self.addClass('vjs-hidden');
  12668. } else {
  12669. self.removeClass('vjs-hidden');
  12670. }
  12671. });
  12672. };
  12673. /**
  12674. * @file volume-level.js
  12675. */
  12676. /**
  12677. * Shows volume level
  12678. *
  12679. * @extends Component
  12680. */
  12681. class VolumeLevel extends Component$1 {
  12682. /**
  12683. * Create the `Component`'s DOM element
  12684. *
  12685. * @return {Element}
  12686. * The element that was created.
  12687. */
  12688. createEl() {
  12689. const el = super.createEl('div', {
  12690. className: 'vjs-volume-level'
  12691. });
  12692. el.appendChild(super.createEl('span', {
  12693. className: 'vjs-control-text'
  12694. }));
  12695. return el;
  12696. }
  12697. }
  12698. Component$1.registerComponent('VolumeLevel', VolumeLevel);
  12699. /**
  12700. * @file volume-level-tooltip.js
  12701. */
  12702. /**
  12703. * Volume level tooltips display a volume above or side by side the volume bar.
  12704. *
  12705. * @extends Component
  12706. */
  12707. class VolumeLevelTooltip extends Component$1 {
  12708. /**
  12709. * Creates an instance of this class.
  12710. *
  12711. * @param { import('../../player').default } player
  12712. * The {@link Player} that this class should be attached to.
  12713. *
  12714. * @param {Object} [options]
  12715. * The key/value store of player options.
  12716. */
  12717. constructor(player, options) {
  12718. super(player, options);
  12719. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  12720. }
  12721. /**
  12722. * Create the volume tooltip DOM element
  12723. *
  12724. * @return {Element}
  12725. * The element that was created.
  12726. */
  12727. createEl() {
  12728. return super.createEl('div', {
  12729. className: 'vjs-volume-tooltip'
  12730. }, {
  12731. 'aria-hidden': 'true'
  12732. });
  12733. }
  12734. /**
  12735. * Updates the position of the tooltip relative to the `VolumeBar` and
  12736. * its content text.
  12737. *
  12738. * @param {Object} rangeBarRect
  12739. * The `ClientRect` for the {@link VolumeBar} element.
  12740. *
  12741. * @param {number} rangeBarPoint
  12742. * A number from 0 to 1, representing a horizontal/vertical reference point
  12743. * from the left edge of the {@link VolumeBar}
  12744. *
  12745. * @param {boolean} vertical
  12746. * Referees to the Volume control position
  12747. * in the control bar{@link VolumeControl}
  12748. *
  12749. */
  12750. update(rangeBarRect, rangeBarPoint, vertical, content) {
  12751. if (!vertical) {
  12752. const tooltipRect = getBoundingClientRect(this.el_);
  12753. const playerRect = getBoundingClientRect(this.player_.el());
  12754. const volumeBarPointPx = rangeBarRect.width * rangeBarPoint;
  12755. if (!playerRect || !tooltipRect) {
  12756. return;
  12757. }
  12758. const spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;
  12759. const spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);
  12760. let pullTooltipBy = tooltipRect.width / 2;
  12761. if (spaceLeftOfPoint < pullTooltipBy) {
  12762. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  12763. } else if (spaceRightOfPoint < pullTooltipBy) {
  12764. pullTooltipBy = spaceRightOfPoint;
  12765. }
  12766. if (pullTooltipBy < 0) {
  12767. pullTooltipBy = 0;
  12768. } else if (pullTooltipBy > tooltipRect.width) {
  12769. pullTooltipBy = tooltipRect.width;
  12770. }
  12771. this.el_.style.right = `-${pullTooltipBy}px`;
  12772. }
  12773. this.write(`${content}%`);
  12774. }
  12775. /**
  12776. * Write the volume to the tooltip DOM element.
  12777. *
  12778. * @param {string} content
  12779. * The formatted volume for the tooltip.
  12780. */
  12781. write(content) {
  12782. textContent(this.el_, content);
  12783. }
  12784. /**
  12785. * Updates the position of the volume tooltip relative to the `VolumeBar`.
  12786. *
  12787. * @param {Object} rangeBarRect
  12788. * The `ClientRect` for the {@link VolumeBar} element.
  12789. *
  12790. * @param {number} rangeBarPoint
  12791. * A number from 0 to 1, representing a horizontal/vertical reference point
  12792. * from the left edge of the {@link VolumeBar}
  12793. *
  12794. * @param {boolean} vertical
  12795. * Referees to the Volume control position
  12796. * in the control bar{@link VolumeControl}
  12797. *
  12798. * @param {number} volume
  12799. * The volume level to update the tooltip to
  12800. *
  12801. * @param {Function} cb
  12802. * A function that will be called during the request animation frame
  12803. * for tooltips that need to do additional animations from the default
  12804. */
  12805. updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {
  12806. this.requestNamedAnimationFrame('VolumeLevelTooltip#updateVolume', () => {
  12807. this.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));
  12808. if (cb) {
  12809. cb();
  12810. }
  12811. });
  12812. }
  12813. }
  12814. Component$1.registerComponent('VolumeLevelTooltip', VolumeLevelTooltip);
  12815. /**
  12816. * @file mouse-volume-level-display.js
  12817. */
  12818. /**
  12819. * The {@link MouseVolumeLevelDisplay} component tracks mouse movement over the
  12820. * {@link VolumeControl}. It displays an indicator and a {@link VolumeLevelTooltip}
  12821. * indicating the volume level which is represented by a given point in the
  12822. * {@link VolumeBar}.
  12823. *
  12824. * @extends Component
  12825. */
  12826. class MouseVolumeLevelDisplay extends Component$1 {
  12827. /**
  12828. * Creates an instance of this class.
  12829. *
  12830. * @param { import('../../player').default } player
  12831. * The {@link Player} that this class should be attached to.
  12832. *
  12833. * @param {Object} [options]
  12834. * The key/value store of player options.
  12835. */
  12836. constructor(player, options) {
  12837. super(player, options);
  12838. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  12839. }
  12840. /**
  12841. * Create the DOM element for this class.
  12842. *
  12843. * @return {Element}
  12844. * The element that was created.
  12845. */
  12846. createEl() {
  12847. return super.createEl('div', {
  12848. className: 'vjs-mouse-display'
  12849. });
  12850. }
  12851. /**
  12852. * Enquires updates to its own DOM as well as the DOM of its
  12853. * {@link VolumeLevelTooltip} child.
  12854. *
  12855. * @param {Object} rangeBarRect
  12856. * The `ClientRect` for the {@link VolumeBar} element.
  12857. *
  12858. * @param {number} rangeBarPoint
  12859. * A number from 0 to 1, representing a horizontal/vertical reference point
  12860. * from the left edge of the {@link VolumeBar}
  12861. *
  12862. * @param {boolean} vertical
  12863. * Referees to the Volume control position
  12864. * in the control bar{@link VolumeControl}
  12865. *
  12866. */
  12867. update(rangeBarRect, rangeBarPoint, vertical) {
  12868. const volume = 100 * rangeBarPoint;
  12869. this.getChild('volumeLevelTooltip').updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, () => {
  12870. if (vertical) {
  12871. this.el_.style.bottom = `${rangeBarRect.height * rangeBarPoint}px`;
  12872. } else {
  12873. this.el_.style.left = `${rangeBarRect.width * rangeBarPoint}px`;
  12874. }
  12875. });
  12876. }
  12877. }
  12878. /**
  12879. * Default options for `MouseVolumeLevelDisplay`
  12880. *
  12881. * @type {Object}
  12882. * @private
  12883. */
  12884. MouseVolumeLevelDisplay.prototype.options_ = {
  12885. children: ['volumeLevelTooltip']
  12886. };
  12887. Component$1.registerComponent('MouseVolumeLevelDisplay', MouseVolumeLevelDisplay);
  12888. /**
  12889. * @file volume-bar.js
  12890. */
  12891. /**
  12892. * The bar that contains the volume level and can be clicked on to adjust the level
  12893. *
  12894. * @extends Slider
  12895. */
  12896. class VolumeBar extends Slider {
  12897. /**
  12898. * Creates an instance of this class.
  12899. *
  12900. * @param { import('../../player').default } player
  12901. * The `Player` that this class should be attached to.
  12902. *
  12903. * @param {Object} [options]
  12904. * The key/value store of player options.
  12905. */
  12906. constructor(player, options) {
  12907. super(player, options);
  12908. this.on('slideractive', e => this.updateLastVolume_(e));
  12909. this.on(player, 'volumechange', e => this.updateARIAAttributes(e));
  12910. player.ready(() => this.updateARIAAttributes());
  12911. }
  12912. /**
  12913. * Create the `Component`'s DOM element
  12914. *
  12915. * @return {Element}
  12916. * The element that was created.
  12917. */
  12918. createEl() {
  12919. return super.createEl('div', {
  12920. className: 'vjs-volume-bar vjs-slider-bar'
  12921. }, {
  12922. 'aria-label': this.localize('Volume Level'),
  12923. 'aria-live': 'polite'
  12924. });
  12925. }
  12926. /**
  12927. * Handle mouse down on volume bar
  12928. *
  12929. * @param {Event} event
  12930. * The `mousedown` event that caused this to run.
  12931. *
  12932. * @listens mousedown
  12933. */
  12934. handleMouseDown(event) {
  12935. if (!isSingleLeftClick(event)) {
  12936. return;
  12937. }
  12938. super.handleMouseDown(event);
  12939. }
  12940. /**
  12941. * Handle movement events on the {@link VolumeMenuButton}.
  12942. *
  12943. * @param {Event} event
  12944. * The event that caused this function to run.
  12945. *
  12946. * @listens mousemove
  12947. */
  12948. handleMouseMove(event) {
  12949. const mouseVolumeLevelDisplay = this.getChild('mouseVolumeLevelDisplay');
  12950. if (mouseVolumeLevelDisplay) {
  12951. const volumeBarEl = this.el();
  12952. const volumeBarRect = getBoundingClientRect(volumeBarEl);
  12953. const vertical = this.vertical();
  12954. let volumeBarPoint = getPointerPosition(volumeBarEl, event);
  12955. volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x;
  12956. // The default skin has a gap on either side of the `VolumeBar`. This means
  12957. // that it's possible to trigger this behavior outside the boundaries of
  12958. // the `VolumeBar`. This ensures we stay within it at all times.
  12959. volumeBarPoint = clamp(volumeBarPoint, 0, 1);
  12960. mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);
  12961. }
  12962. if (!isSingleLeftClick(event)) {
  12963. return;
  12964. }
  12965. this.checkMuted();
  12966. this.player_.volume(this.calculateDistance(event));
  12967. }
  12968. /**
  12969. * If the player is muted unmute it.
  12970. */
  12971. checkMuted() {
  12972. if (this.player_.muted()) {
  12973. this.player_.muted(false);
  12974. }
  12975. }
  12976. /**
  12977. * Get percent of volume level
  12978. *
  12979. * @return {number}
  12980. * Volume level percent as a decimal number.
  12981. */
  12982. getPercent() {
  12983. if (this.player_.muted()) {
  12984. return 0;
  12985. }
  12986. return this.player_.volume();
  12987. }
  12988. /**
  12989. * Increase volume level for keyboard users
  12990. */
  12991. stepForward() {
  12992. this.checkMuted();
  12993. this.player_.volume(this.player_.volume() + 0.1);
  12994. }
  12995. /**
  12996. * Decrease volume level for keyboard users
  12997. */
  12998. stepBack() {
  12999. this.checkMuted();
  13000. this.player_.volume(this.player_.volume() - 0.1);
  13001. }
  13002. /**
  13003. * Update ARIA accessibility attributes
  13004. *
  13005. * @param {Event} [event]
  13006. * The `volumechange` event that caused this function to run.
  13007. *
  13008. * @listens Player#volumechange
  13009. */
  13010. updateARIAAttributes(event) {
  13011. const ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
  13012. this.el_.setAttribute('aria-valuenow', ariaValue);
  13013. this.el_.setAttribute('aria-valuetext', ariaValue + '%');
  13014. }
  13015. /**
  13016. * Returns the current value of the player volume as a percentage
  13017. *
  13018. * @private
  13019. */
  13020. volumeAsPercentage_() {
  13021. return Math.round(this.player_.volume() * 100);
  13022. }
  13023. /**
  13024. * When user starts dragging the VolumeBar, store the volume and listen for
  13025. * the end of the drag. When the drag ends, if the volume was set to zero,
  13026. * set lastVolume to the stored volume.
  13027. *
  13028. * @listens slideractive
  13029. * @private
  13030. */
  13031. updateLastVolume_() {
  13032. const volumeBeforeDrag = this.player_.volume();
  13033. this.one('sliderinactive', () => {
  13034. if (this.player_.volume() === 0) {
  13035. this.player_.lastVolume_(volumeBeforeDrag);
  13036. }
  13037. });
  13038. }
  13039. }
  13040. /**
  13041. * Default options for the `VolumeBar`
  13042. *
  13043. * @type {Object}
  13044. * @private
  13045. */
  13046. VolumeBar.prototype.options_ = {
  13047. children: ['volumeLevel'],
  13048. barName: 'volumeLevel'
  13049. };
  13050. // MouseVolumeLevelDisplay tooltip should not be added to a player on mobile devices
  13051. if (!IS_IOS && !IS_ANDROID) {
  13052. VolumeBar.prototype.options_.children.splice(0, 0, 'mouseVolumeLevelDisplay');
  13053. }
  13054. /**
  13055. * Call the update event for this Slider when this event happens on the player.
  13056. *
  13057. * @type {string}
  13058. */
  13059. VolumeBar.prototype.playerEvent = 'volumechange';
  13060. Component$1.registerComponent('VolumeBar', VolumeBar);
  13061. /**
  13062. * @file volume-control.js
  13063. */
  13064. /**
  13065. * The component for controlling the volume level
  13066. *
  13067. * @extends Component
  13068. */
  13069. class VolumeControl extends Component$1 {
  13070. /**
  13071. * Creates an instance of this class.
  13072. *
  13073. * @param { import('../../player').default } player
  13074. * The `Player` that this class should be attached to.
  13075. *
  13076. * @param {Object} [options={}]
  13077. * The key/value store of player options.
  13078. */
  13079. constructor(player, options = {}) {
  13080. options.vertical = options.vertical || false;
  13081. // Pass the vertical option down to the VolumeBar if
  13082. // the VolumeBar is turned on.
  13083. if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {
  13084. options.volumeBar = options.volumeBar || {};
  13085. options.volumeBar.vertical = options.vertical;
  13086. }
  13087. super(player, options);
  13088. // hide this control if volume support is missing
  13089. checkVolumeSupport(this, player);
  13090. this.throttledHandleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  13091. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  13092. this.on('mousedown', e => this.handleMouseDown(e));
  13093. this.on('touchstart', e => this.handleMouseDown(e));
  13094. this.on('mousemove', e => this.handleMouseMove(e));
  13095. // while the slider is active (the mouse has been pressed down and
  13096. // is dragging) or in focus we do not want to hide the VolumeBar
  13097. this.on(this.volumeBar, ['focus', 'slideractive'], () => {
  13098. this.volumeBar.addClass('vjs-slider-active');
  13099. this.addClass('vjs-slider-active');
  13100. this.trigger('slideractive');
  13101. });
  13102. this.on(this.volumeBar, ['blur', 'sliderinactive'], () => {
  13103. this.volumeBar.removeClass('vjs-slider-active');
  13104. this.removeClass('vjs-slider-active');
  13105. this.trigger('sliderinactive');
  13106. });
  13107. }
  13108. /**
  13109. * Create the `Component`'s DOM element
  13110. *
  13111. * @return {Element}
  13112. * The element that was created.
  13113. */
  13114. createEl() {
  13115. let orientationClass = 'vjs-volume-horizontal';
  13116. if (this.options_.vertical) {
  13117. orientationClass = 'vjs-volume-vertical';
  13118. }
  13119. return super.createEl('div', {
  13120. className: `vjs-volume-control vjs-control ${orientationClass}`
  13121. });
  13122. }
  13123. /**
  13124. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  13125. *
  13126. * @param {Event} event
  13127. * `mousedown` or `touchstart` event that triggered this function
  13128. *
  13129. * @listens mousedown
  13130. * @listens touchstart
  13131. */
  13132. handleMouseDown(event) {
  13133. const doc = this.el_.ownerDocument;
  13134. this.on(doc, 'mousemove', this.throttledHandleMouseMove);
  13135. this.on(doc, 'touchmove', this.throttledHandleMouseMove);
  13136. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  13137. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  13138. }
  13139. /**
  13140. * Handle `mouseup` or `touchend` events on the `VolumeControl`.
  13141. *
  13142. * @param {Event} event
  13143. * `mouseup` or `touchend` event that triggered this function.
  13144. *
  13145. * @listens touchend
  13146. * @listens mouseup
  13147. */
  13148. handleMouseUp(event) {
  13149. const doc = this.el_.ownerDocument;
  13150. this.off(doc, 'mousemove', this.throttledHandleMouseMove);
  13151. this.off(doc, 'touchmove', this.throttledHandleMouseMove);
  13152. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  13153. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  13154. }
  13155. /**
  13156. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  13157. *
  13158. * @param {Event} event
  13159. * `mousedown` or `touchstart` event that triggered this function
  13160. *
  13161. * @listens mousedown
  13162. * @listens touchstart
  13163. */
  13164. handleMouseMove(event) {
  13165. this.volumeBar.handleMouseMove(event);
  13166. }
  13167. }
  13168. /**
  13169. * Default options for the `VolumeControl`
  13170. *
  13171. * @type {Object}
  13172. * @private
  13173. */
  13174. VolumeControl.prototype.options_ = {
  13175. children: ['volumeBar']
  13176. };
  13177. Component$1.registerComponent('VolumeControl', VolumeControl);
  13178. /**
  13179. * Check if muting volume is supported and if it isn't hide the mute toggle
  13180. * button.
  13181. *
  13182. * @param { import('../../component').default } self
  13183. * A reference to the mute toggle button
  13184. *
  13185. * @param { import('../../player').default } player
  13186. * A reference to the player
  13187. *
  13188. * @private
  13189. */
  13190. const checkMuteSupport = function (self, player) {
  13191. // hide mute toggle button if it's not supported by the current tech
  13192. if (player.tech_ && !player.tech_.featuresMuteControl) {
  13193. self.addClass('vjs-hidden');
  13194. }
  13195. self.on(player, 'loadstart', function () {
  13196. if (!player.tech_.featuresMuteControl) {
  13197. self.addClass('vjs-hidden');
  13198. } else {
  13199. self.removeClass('vjs-hidden');
  13200. }
  13201. });
  13202. };
  13203. /**
  13204. * @file mute-toggle.js
  13205. */
  13206. /**
  13207. * A button component for muting the audio.
  13208. *
  13209. * @extends Button
  13210. */
  13211. class MuteToggle extends Button {
  13212. /**
  13213. * Creates an instance of this class.
  13214. *
  13215. * @param { import('./player').default } player
  13216. * The `Player` that this class should be attached to.
  13217. *
  13218. * @param {Object} [options]
  13219. * The key/value store of player options.
  13220. */
  13221. constructor(player, options) {
  13222. super(player, options);
  13223. // hide this control if volume support is missing
  13224. checkMuteSupport(this, player);
  13225. this.on(player, ['loadstart', 'volumechange'], e => this.update(e));
  13226. }
  13227. /**
  13228. * Builds the default DOM `className`.
  13229. *
  13230. * @return {string}
  13231. * The DOM `className` for this object.
  13232. */
  13233. buildCSSClass() {
  13234. return `vjs-mute-control ${super.buildCSSClass()}`;
  13235. }
  13236. /**
  13237. * This gets called when an `MuteToggle` is "clicked". See
  13238. * {@link ClickableComponent} for more detailed information on what a click can be.
  13239. *
  13240. * @param {Event} [event]
  13241. * The `keydown`, `tap`, or `click` event that caused this function to be
  13242. * called.
  13243. *
  13244. * @listens tap
  13245. * @listens click
  13246. */
  13247. handleClick(event) {
  13248. const vol = this.player_.volume();
  13249. const lastVolume = this.player_.lastVolume_();
  13250. if (vol === 0) {
  13251. const volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
  13252. this.player_.volume(volumeToSet);
  13253. this.player_.muted(false);
  13254. } else {
  13255. this.player_.muted(this.player_.muted() ? false : true);
  13256. }
  13257. }
  13258. /**
  13259. * Update the `MuteToggle` button based on the state of `volume` and `muted`
  13260. * on the player.
  13261. *
  13262. * @param {Event} [event]
  13263. * The {@link Player#loadstart} event if this function was called
  13264. * through an event.
  13265. *
  13266. * @listens Player#loadstart
  13267. * @listens Player#volumechange
  13268. */
  13269. update(event) {
  13270. this.updateIcon_();
  13271. this.updateControlText_();
  13272. }
  13273. /**
  13274. * Update the appearance of the `MuteToggle` icon.
  13275. *
  13276. * Possible states (given `level` variable below):
  13277. * - 0: crossed out
  13278. * - 1: zero bars of volume
  13279. * - 2: one bar of volume
  13280. * - 3: two bars of volume
  13281. *
  13282. * @private
  13283. */
  13284. updateIcon_() {
  13285. const vol = this.player_.volume();
  13286. let level = 3;
  13287. // in iOS when a player is loaded with muted attribute
  13288. // and volume is changed with a native mute button
  13289. // we want to make sure muted state is updated
  13290. if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {
  13291. this.player_.muted(this.player_.tech_.el_.muted);
  13292. }
  13293. if (vol === 0 || this.player_.muted()) {
  13294. level = 0;
  13295. } else if (vol < 0.33) {
  13296. level = 1;
  13297. } else if (vol < 0.67) {
  13298. level = 2;
  13299. }
  13300. removeClass(this.el_, [0, 1, 2, 3].reduce((str, i) => str + `${i ? ' ' : ''}vjs-vol-${i}`, ''));
  13301. addClass(this.el_, `vjs-vol-${level}`);
  13302. }
  13303. /**
  13304. * If `muted` has changed on the player, update the control text
  13305. * (`title` attribute on `vjs-mute-control` element and content of
  13306. * `vjs-control-text` element).
  13307. *
  13308. * @private
  13309. */
  13310. updateControlText_() {
  13311. const soundOff = this.player_.muted() || this.player_.volume() === 0;
  13312. const text = soundOff ? 'Unmute' : 'Mute';
  13313. if (this.controlText() !== text) {
  13314. this.controlText(text);
  13315. }
  13316. }
  13317. }
  13318. /**
  13319. * The text that should display over the `MuteToggle`s controls. Added for localization.
  13320. *
  13321. * @type {string}
  13322. * @protected
  13323. */
  13324. MuteToggle.prototype.controlText_ = 'Mute';
  13325. Component$1.registerComponent('MuteToggle', MuteToggle);
  13326. /**
  13327. * @file volume-control.js
  13328. */
  13329. /**
  13330. * A Component to contain the MuteToggle and VolumeControl so that
  13331. * they can work together.
  13332. *
  13333. * @extends Component
  13334. */
  13335. class VolumePanel extends Component$1 {
  13336. /**
  13337. * Creates an instance of this class.
  13338. *
  13339. * @param { import('./player').default } player
  13340. * The `Player` that this class should be attached to.
  13341. *
  13342. * @param {Object} [options={}]
  13343. * The key/value store of player options.
  13344. */
  13345. constructor(player, options = {}) {
  13346. if (typeof options.inline !== 'undefined') {
  13347. options.inline = options.inline;
  13348. } else {
  13349. options.inline = true;
  13350. }
  13351. // pass the inline option down to the VolumeControl as vertical if
  13352. // the VolumeControl is on.
  13353. if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {
  13354. options.volumeControl = options.volumeControl || {};
  13355. options.volumeControl.vertical = !options.inline;
  13356. }
  13357. super(player, options);
  13358. // this handler is used by mouse handler methods below
  13359. this.handleKeyPressHandler_ = e => this.handleKeyPress(e);
  13360. this.on(player, ['loadstart'], e => this.volumePanelState_(e));
  13361. this.on(this.muteToggle, 'keyup', e => this.handleKeyPress(e));
  13362. this.on(this.volumeControl, 'keyup', e => this.handleVolumeControlKeyUp(e));
  13363. this.on('keydown', e => this.handleKeyPress(e));
  13364. this.on('mouseover', e => this.handleMouseOver(e));
  13365. this.on('mouseout', e => this.handleMouseOut(e));
  13366. // while the slider is active (the mouse has been pressed down and
  13367. // is dragging) we do not want to hide the VolumeBar
  13368. this.on(this.volumeControl, ['slideractive'], this.sliderActive_);
  13369. this.on(this.volumeControl, ['sliderinactive'], this.sliderInactive_);
  13370. }
  13371. /**
  13372. * Add vjs-slider-active class to the VolumePanel
  13373. *
  13374. * @listens VolumeControl#slideractive
  13375. * @private
  13376. */
  13377. sliderActive_() {
  13378. this.addClass('vjs-slider-active');
  13379. }
  13380. /**
  13381. * Removes vjs-slider-active class to the VolumePanel
  13382. *
  13383. * @listens VolumeControl#sliderinactive
  13384. * @private
  13385. */
  13386. sliderInactive_() {
  13387. this.removeClass('vjs-slider-active');
  13388. }
  13389. /**
  13390. * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel
  13391. * depending on MuteToggle and VolumeControl state
  13392. *
  13393. * @listens Player#loadstart
  13394. * @private
  13395. */
  13396. volumePanelState_() {
  13397. // hide volume panel if neither volume control or mute toggle
  13398. // are displayed
  13399. if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {
  13400. this.addClass('vjs-hidden');
  13401. }
  13402. // if only mute toggle is visible we don't want
  13403. // volume panel expanding when hovered or active
  13404. if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {
  13405. this.addClass('vjs-mute-toggle-only');
  13406. }
  13407. }
  13408. /**
  13409. * Create the `Component`'s DOM element
  13410. *
  13411. * @return {Element}
  13412. * The element that was created.
  13413. */
  13414. createEl() {
  13415. let orientationClass = 'vjs-volume-panel-horizontal';
  13416. if (!this.options_.inline) {
  13417. orientationClass = 'vjs-volume-panel-vertical';
  13418. }
  13419. return super.createEl('div', {
  13420. className: `vjs-volume-panel vjs-control ${orientationClass}`
  13421. });
  13422. }
  13423. /**
  13424. * Dispose of the `volume-panel` and all child components.
  13425. */
  13426. dispose() {
  13427. this.handleMouseOut();
  13428. super.dispose();
  13429. }
  13430. /**
  13431. * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes
  13432. * the volume panel and sets focus on `MuteToggle`.
  13433. *
  13434. * @param {Event} event
  13435. * The `keyup` event that caused this function to be called.
  13436. *
  13437. * @listens keyup
  13438. */
  13439. handleVolumeControlKeyUp(event) {
  13440. if (keycode.isEventKey(event, 'Esc')) {
  13441. this.muteToggle.focus();
  13442. }
  13443. }
  13444. /**
  13445. * This gets called when a `VolumePanel` gains hover via a `mouseover` event.
  13446. * Turns on listening for `mouseover` event. When they happen it
  13447. * calls `this.handleMouseOver`.
  13448. *
  13449. * @param {Event} event
  13450. * The `mouseover` event that caused this function to be called.
  13451. *
  13452. * @listens mouseover
  13453. */
  13454. handleMouseOver(event) {
  13455. this.addClass('vjs-hover');
  13456. on(document, 'keyup', this.handleKeyPressHandler_);
  13457. }
  13458. /**
  13459. * This gets called when a `VolumePanel` gains hover via a `mouseout` event.
  13460. * Turns on listening for `mouseout` event. When they happen it
  13461. * calls `this.handleMouseOut`.
  13462. *
  13463. * @param {Event} event
  13464. * The `mouseout` event that caused this function to be called.
  13465. *
  13466. * @listens mouseout
  13467. */
  13468. handleMouseOut(event) {
  13469. this.removeClass('vjs-hover');
  13470. off(document, 'keyup', this.handleKeyPressHandler_);
  13471. }
  13472. /**
  13473. * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`,
  13474. * looking for ESC, which hides the `VolumeControl`.
  13475. *
  13476. * @param {Event} event
  13477. * The keypress that triggered this event.
  13478. *
  13479. * @listens keydown | keyup
  13480. */
  13481. handleKeyPress(event) {
  13482. if (keycode.isEventKey(event, 'Esc')) {
  13483. this.handleMouseOut();
  13484. }
  13485. }
  13486. }
  13487. /**
  13488. * Default options for the `VolumeControl`
  13489. *
  13490. * @type {Object}
  13491. * @private
  13492. */
  13493. VolumePanel.prototype.options_ = {
  13494. children: ['muteToggle', 'volumeControl']
  13495. };
  13496. Component$1.registerComponent('VolumePanel', VolumePanel);
  13497. /**
  13498. * Button to skip forward a configurable amount of time
  13499. * through a video. Renders in the control bar.
  13500. *
  13501. * e.g. options: {controlBar: {skipButtons: forward: 5}}
  13502. *
  13503. * @extends Button
  13504. */
  13505. class SkipForward extends Button {
  13506. constructor(player, options) {
  13507. super(player, options);
  13508. this.validOptions = [5, 10, 30];
  13509. this.skipTime = this.getSkipForwardTime();
  13510. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  13511. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  13512. this.show();
  13513. } else {
  13514. this.hide();
  13515. }
  13516. }
  13517. getSkipForwardTime() {
  13518. const playerOptions = this.options_.playerOptions;
  13519. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.forward;
  13520. }
  13521. buildCSSClass() {
  13522. return `vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`;
  13523. }
  13524. /**
  13525. * On click, skips forward in the duration/seekable range by a configurable amount of seconds.
  13526. * If the time left in the duration/seekable range is less than the configured 'skip forward' time,
  13527. * skips to end of duration/seekable range.
  13528. *
  13529. * Handle a click on a `SkipForward` button
  13530. *
  13531. * @param {EventTarget~Event} event
  13532. * The `click` event that caused this function
  13533. * to be called
  13534. */
  13535. handleClick(event) {
  13536. const currentVideoTime = this.player_.currentTime();
  13537. const liveTracker = this.player_.liveTracker;
  13538. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  13539. let newTime;
  13540. if (currentVideoTime + this.skipTime <= duration) {
  13541. newTime = currentVideoTime + this.skipTime;
  13542. } else {
  13543. newTime = duration;
  13544. }
  13545. this.player_.currentTime(newTime);
  13546. }
  13547. /**
  13548. * Update control text on languagechange
  13549. */
  13550. handleLanguagechange() {
  13551. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  13552. }
  13553. }
  13554. Component$1.registerComponent('SkipForward', SkipForward);
  13555. /**
  13556. * Button to skip backward a configurable amount of time
  13557. * through a video. Renders in the control bar.
  13558. *
  13559. * * e.g. options: {controlBar: {skipButtons: backward: 5}}
  13560. *
  13561. * @extends Button
  13562. */
  13563. class SkipBackward extends Button {
  13564. constructor(player, options) {
  13565. super(player, options);
  13566. this.validOptions = [5, 10, 30];
  13567. this.skipTime = this.getSkipBackwardTime();
  13568. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  13569. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  13570. this.show();
  13571. } else {
  13572. this.hide();
  13573. }
  13574. }
  13575. getSkipBackwardTime() {
  13576. const playerOptions = this.options_.playerOptions;
  13577. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.backward;
  13578. }
  13579. buildCSSClass() {
  13580. return `vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`;
  13581. }
  13582. /**
  13583. * On click, skips backward in the video by a configurable amount of seconds.
  13584. * If the current time in the video is less than the configured 'skip backward' time,
  13585. * skips to beginning of video or seekable range.
  13586. *
  13587. * Handle a click on a `SkipBackward` button
  13588. *
  13589. * @param {EventTarget~Event} event
  13590. * The `click` event that caused this function
  13591. * to be called
  13592. */
  13593. handleClick(event) {
  13594. const currentVideoTime = this.player_.currentTime();
  13595. const liveTracker = this.player_.liveTracker;
  13596. const seekableStart = liveTracker && liveTracker.isLive() && liveTracker.seekableStart();
  13597. let newTime;
  13598. if (seekableStart && currentVideoTime - this.skipTime <= seekableStart) {
  13599. newTime = seekableStart;
  13600. } else if (currentVideoTime >= this.skipTime) {
  13601. newTime = currentVideoTime - this.skipTime;
  13602. } else {
  13603. newTime = 0;
  13604. }
  13605. this.player_.currentTime(newTime);
  13606. }
  13607. /**
  13608. * Update control text on languagechange
  13609. */
  13610. handleLanguagechange() {
  13611. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  13612. }
  13613. }
  13614. SkipBackward.prototype.controlText_ = 'Skip Backward';
  13615. Component$1.registerComponent('SkipBackward', SkipBackward);
  13616. /**
  13617. * @file menu.js
  13618. */
  13619. /**
  13620. * The Menu component is used to build popup menus, including subtitle and
  13621. * captions selection menus.
  13622. *
  13623. * @extends Component
  13624. */
  13625. class Menu extends Component$1 {
  13626. /**
  13627. * Create an instance of this class.
  13628. *
  13629. * @param { import('../player').default } player
  13630. * the player that this component should attach to
  13631. *
  13632. * @param {Object} [options]
  13633. * Object of option names and values
  13634. *
  13635. */
  13636. constructor(player, options) {
  13637. super(player, options);
  13638. if (options) {
  13639. this.menuButton_ = options.menuButton;
  13640. }
  13641. this.focusedChild_ = -1;
  13642. this.on('keydown', e => this.handleKeyDown(e));
  13643. // All the menu item instances share the same blur handler provided by the menu container.
  13644. this.boundHandleBlur_ = e => this.handleBlur(e);
  13645. this.boundHandleTapClick_ = e => this.handleTapClick(e);
  13646. }
  13647. /**
  13648. * Add event listeners to the {@link MenuItem}.
  13649. *
  13650. * @param {Object} component
  13651. * The instance of the `MenuItem` to add listeners to.
  13652. *
  13653. */
  13654. addEventListenerForItem(component) {
  13655. if (!(component instanceof Component$1)) {
  13656. return;
  13657. }
  13658. this.on(component, 'blur', this.boundHandleBlur_);
  13659. this.on(component, ['tap', 'click'], this.boundHandleTapClick_);
  13660. }
  13661. /**
  13662. * Remove event listeners from the {@link MenuItem}.
  13663. *
  13664. * @param {Object} component
  13665. * The instance of the `MenuItem` to remove listeners.
  13666. *
  13667. */
  13668. removeEventListenerForItem(component) {
  13669. if (!(component instanceof Component$1)) {
  13670. return;
  13671. }
  13672. this.off(component, 'blur', this.boundHandleBlur_);
  13673. this.off(component, ['tap', 'click'], this.boundHandleTapClick_);
  13674. }
  13675. /**
  13676. * This method will be called indirectly when the component has been added
  13677. * before the component adds to the new menu instance by `addItem`.
  13678. * In this case, the original menu instance will remove the component
  13679. * by calling `removeChild`.
  13680. *
  13681. * @param {Object} component
  13682. * The instance of the `MenuItem`
  13683. */
  13684. removeChild(component) {
  13685. if (typeof component === 'string') {
  13686. component = this.getChild(component);
  13687. }
  13688. this.removeEventListenerForItem(component);
  13689. super.removeChild(component);
  13690. }
  13691. /**
  13692. * Add a {@link MenuItem} to the menu.
  13693. *
  13694. * @param {Object|string} component
  13695. * The name or instance of the `MenuItem` to add.
  13696. *
  13697. */
  13698. addItem(component) {
  13699. const childComponent = this.addChild(component);
  13700. if (childComponent) {
  13701. this.addEventListenerForItem(childComponent);
  13702. }
  13703. }
  13704. /**
  13705. * Create the `Menu`s DOM element.
  13706. *
  13707. * @return {Element}
  13708. * the element that was created
  13709. */
  13710. createEl() {
  13711. const contentElType = this.options_.contentElType || 'ul';
  13712. this.contentEl_ = createEl(contentElType, {
  13713. className: 'vjs-menu-content'
  13714. });
  13715. this.contentEl_.setAttribute('role', 'menu');
  13716. const el = super.createEl('div', {
  13717. append: this.contentEl_,
  13718. className: 'vjs-menu'
  13719. });
  13720. el.appendChild(this.contentEl_);
  13721. // Prevent clicks from bubbling up. Needed for Menu Buttons,
  13722. // where a click on the parent is significant
  13723. on(el, 'click', function (event) {
  13724. event.preventDefault();
  13725. event.stopImmediatePropagation();
  13726. });
  13727. return el;
  13728. }
  13729. dispose() {
  13730. this.contentEl_ = null;
  13731. this.boundHandleBlur_ = null;
  13732. this.boundHandleTapClick_ = null;
  13733. super.dispose();
  13734. }
  13735. /**
  13736. * Called when a `MenuItem` loses focus.
  13737. *
  13738. * @param {Event} event
  13739. * The `blur` event that caused this function to be called.
  13740. *
  13741. * @listens blur
  13742. */
  13743. handleBlur(event) {
  13744. const relatedTarget = event.relatedTarget || document.activeElement;
  13745. // Close menu popup when a user clicks outside the menu
  13746. if (!this.children().some(element => {
  13747. return element.el() === relatedTarget;
  13748. })) {
  13749. const btn = this.menuButton_;
  13750. if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {
  13751. btn.unpressButton();
  13752. }
  13753. }
  13754. }
  13755. /**
  13756. * Called when a `MenuItem` gets clicked or tapped.
  13757. *
  13758. * @param {Event} event
  13759. * The `click` or `tap` event that caused this function to be called.
  13760. *
  13761. * @listens click,tap
  13762. */
  13763. handleTapClick(event) {
  13764. // Unpress the associated MenuButton, and move focus back to it
  13765. if (this.menuButton_) {
  13766. this.menuButton_.unpressButton();
  13767. const childComponents = this.children();
  13768. if (!Array.isArray(childComponents)) {
  13769. return;
  13770. }
  13771. const foundComponent = childComponents.filter(component => component.el() === event.target)[0];
  13772. if (!foundComponent) {
  13773. return;
  13774. }
  13775. // don't focus menu button if item is a caption settings item
  13776. // because focus will move elsewhere
  13777. if (foundComponent.name() !== 'CaptionSettingsMenuItem') {
  13778. this.menuButton_.focus();
  13779. }
  13780. }
  13781. }
  13782. /**
  13783. * Handle a `keydown` event on this menu. This listener is added in the constructor.
  13784. *
  13785. * @param {Event} event
  13786. * A `keydown` event that happened on the menu.
  13787. *
  13788. * @listens keydown
  13789. */
  13790. handleKeyDown(event) {
  13791. // Left and Down Arrows
  13792. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  13793. event.preventDefault();
  13794. event.stopPropagation();
  13795. this.stepForward();
  13796. // Up and Right Arrows
  13797. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  13798. event.preventDefault();
  13799. event.stopPropagation();
  13800. this.stepBack();
  13801. }
  13802. }
  13803. /**
  13804. * Move to next (lower) menu item for keyboard users.
  13805. */
  13806. stepForward() {
  13807. let stepChild = 0;
  13808. if (this.focusedChild_ !== undefined) {
  13809. stepChild = this.focusedChild_ + 1;
  13810. }
  13811. this.focus(stepChild);
  13812. }
  13813. /**
  13814. * Move to previous (higher) menu item for keyboard users.
  13815. */
  13816. stepBack() {
  13817. let stepChild = 0;
  13818. if (this.focusedChild_ !== undefined) {
  13819. stepChild = this.focusedChild_ - 1;
  13820. }
  13821. this.focus(stepChild);
  13822. }
  13823. /**
  13824. * Set focus on a {@link MenuItem} in the `Menu`.
  13825. *
  13826. * @param {Object|string} [item=0]
  13827. * Index of child item set focus on.
  13828. */
  13829. focus(item = 0) {
  13830. const children = this.children().slice();
  13831. const haveTitle = children.length && children[0].hasClass('vjs-menu-title');
  13832. if (haveTitle) {
  13833. children.shift();
  13834. }
  13835. if (children.length > 0) {
  13836. if (item < 0) {
  13837. item = 0;
  13838. } else if (item >= children.length) {
  13839. item = children.length - 1;
  13840. }
  13841. this.focusedChild_ = item;
  13842. children[item].el_.focus();
  13843. }
  13844. }
  13845. }
  13846. Component$1.registerComponent('Menu', Menu);
  13847. /**
  13848. * @file menu-button.js
  13849. */
  13850. /**
  13851. * A `MenuButton` class for any popup {@link Menu}.
  13852. *
  13853. * @extends Component
  13854. */
  13855. class MenuButton extends Component$1 {
  13856. /**
  13857. * Creates an instance of this class.
  13858. *
  13859. * @param { import('../player').default } player
  13860. * The `Player` that this class should be attached to.
  13861. *
  13862. * @param {Object} [options={}]
  13863. * The key/value store of player options.
  13864. */
  13865. constructor(player, options = {}) {
  13866. super(player, options);
  13867. this.menuButton_ = new Button(player, options);
  13868. this.menuButton_.controlText(this.controlText_);
  13869. this.menuButton_.el_.setAttribute('aria-haspopup', 'true');
  13870. // Add buildCSSClass values to the button, not the wrapper
  13871. const buttonClass = Button.prototype.buildCSSClass();
  13872. this.menuButton_.el_.className = this.buildCSSClass() + ' ' + buttonClass;
  13873. this.menuButton_.removeClass('vjs-control');
  13874. this.addChild(this.menuButton_);
  13875. this.update();
  13876. this.enabled_ = true;
  13877. const handleClick = e => this.handleClick(e);
  13878. this.handleMenuKeyUp_ = e => this.handleMenuKeyUp(e);
  13879. this.on(this.menuButton_, 'tap', handleClick);
  13880. this.on(this.menuButton_, 'click', handleClick);
  13881. this.on(this.menuButton_, 'keydown', e => this.handleKeyDown(e));
  13882. this.on(this.menuButton_, 'mouseenter', () => {
  13883. this.addClass('vjs-hover');
  13884. this.menu.show();
  13885. on(document, 'keyup', this.handleMenuKeyUp_);
  13886. });
  13887. this.on('mouseleave', e => this.handleMouseLeave(e));
  13888. this.on('keydown', e => this.handleSubmenuKeyDown(e));
  13889. }
  13890. /**
  13891. * Update the menu based on the current state of its items.
  13892. */
  13893. update() {
  13894. const menu = this.createMenu();
  13895. if (this.menu) {
  13896. this.menu.dispose();
  13897. this.removeChild(this.menu);
  13898. }
  13899. this.menu = menu;
  13900. this.addChild(menu);
  13901. /**
  13902. * Track the state of the menu button
  13903. *
  13904. * @type {Boolean}
  13905. * @private
  13906. */
  13907. this.buttonPressed_ = false;
  13908. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  13909. if (this.items && this.items.length <= this.hideThreshold_) {
  13910. this.hide();
  13911. this.menu.contentEl_.removeAttribute('role');
  13912. } else {
  13913. this.show();
  13914. this.menu.contentEl_.setAttribute('role', 'menu');
  13915. }
  13916. }
  13917. /**
  13918. * Create the menu and add all items to it.
  13919. *
  13920. * @return {Menu}
  13921. * The constructed menu
  13922. */
  13923. createMenu() {
  13924. const menu = new Menu(this.player_, {
  13925. menuButton: this
  13926. });
  13927. /**
  13928. * Hide the menu if the number of items is less than or equal to this threshold. This defaults
  13929. * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list
  13930. * it here because every time we run `createMenu` we need to reset the value.
  13931. *
  13932. * @protected
  13933. * @type {Number}
  13934. */
  13935. this.hideThreshold_ = 0;
  13936. // Add a title list item to the top
  13937. if (this.options_.title) {
  13938. const titleEl = createEl('li', {
  13939. className: 'vjs-menu-title',
  13940. textContent: toTitleCase$1(this.options_.title),
  13941. tabIndex: -1
  13942. });
  13943. const titleComponent = new Component$1(this.player_, {
  13944. el: titleEl
  13945. });
  13946. menu.addItem(titleComponent);
  13947. }
  13948. this.items = this.createItems();
  13949. if (this.items) {
  13950. // Add menu items to the menu
  13951. for (let i = 0; i < this.items.length; i++) {
  13952. menu.addItem(this.items[i]);
  13953. }
  13954. }
  13955. return menu;
  13956. }
  13957. /**
  13958. * Create the list of menu items. Specific to each subclass.
  13959. *
  13960. * @abstract
  13961. */
  13962. createItems() {}
  13963. /**
  13964. * Create the `MenuButtons`s DOM element.
  13965. *
  13966. * @return {Element}
  13967. * The element that gets created.
  13968. */
  13969. createEl() {
  13970. return super.createEl('div', {
  13971. className: this.buildWrapperCSSClass()
  13972. }, {});
  13973. }
  13974. /**
  13975. * Allow sub components to stack CSS class names for the wrapper element
  13976. *
  13977. * @return {string}
  13978. * The constructed wrapper DOM `className`
  13979. */
  13980. buildWrapperCSSClass() {
  13981. let menuButtonClass = 'vjs-menu-button';
  13982. // If the inline option is passed, we want to use different styles altogether.
  13983. if (this.options_.inline === true) {
  13984. menuButtonClass += '-inline';
  13985. } else {
  13986. menuButtonClass += '-popup';
  13987. }
  13988. // TODO: Fix the CSS so that this isn't necessary
  13989. const buttonClass = Button.prototype.buildCSSClass();
  13990. return `vjs-menu-button ${menuButtonClass} ${buttonClass} ${super.buildCSSClass()}`;
  13991. }
  13992. /**
  13993. * Builds the default DOM `className`.
  13994. *
  13995. * @return {string}
  13996. * The DOM `className` for this object.
  13997. */
  13998. buildCSSClass() {
  13999. let menuButtonClass = 'vjs-menu-button';
  14000. // If the inline option is passed, we want to use different styles altogether.
  14001. if (this.options_.inline === true) {
  14002. menuButtonClass += '-inline';
  14003. } else {
  14004. menuButtonClass += '-popup';
  14005. }
  14006. return `vjs-menu-button ${menuButtonClass} ${super.buildCSSClass()}`;
  14007. }
  14008. /**
  14009. * Get or set the localized control text that will be used for accessibility.
  14010. *
  14011. * > NOTE: This will come from the internal `menuButton_` element.
  14012. *
  14013. * @param {string} [text]
  14014. * Control text for element.
  14015. *
  14016. * @param {Element} [el=this.menuButton_.el()]
  14017. * Element to set the title on.
  14018. *
  14019. * @return {string}
  14020. * - The control text when getting
  14021. */
  14022. controlText(text, el = this.menuButton_.el()) {
  14023. return this.menuButton_.controlText(text, el);
  14024. }
  14025. /**
  14026. * Dispose of the `menu-button` and all child components.
  14027. */
  14028. dispose() {
  14029. this.handleMouseLeave();
  14030. super.dispose();
  14031. }
  14032. /**
  14033. * Handle a click on a `MenuButton`.
  14034. * See {@link ClickableComponent#handleClick} for instances where this is called.
  14035. *
  14036. * @param {Event} event
  14037. * The `keydown`, `tap`, or `click` event that caused this function to be
  14038. * called.
  14039. *
  14040. * @listens tap
  14041. * @listens click
  14042. */
  14043. handleClick(event) {
  14044. if (this.buttonPressed_) {
  14045. this.unpressButton();
  14046. } else {
  14047. this.pressButton();
  14048. }
  14049. }
  14050. /**
  14051. * Handle `mouseleave` for `MenuButton`.
  14052. *
  14053. * @param {Event} event
  14054. * The `mouseleave` event that caused this function to be called.
  14055. *
  14056. * @listens mouseleave
  14057. */
  14058. handleMouseLeave(event) {
  14059. this.removeClass('vjs-hover');
  14060. off(document, 'keyup', this.handleMenuKeyUp_);
  14061. }
  14062. /**
  14063. * Set the focus to the actual button, not to this element
  14064. */
  14065. focus() {
  14066. this.menuButton_.focus();
  14067. }
  14068. /**
  14069. * Remove the focus from the actual button, not this element
  14070. */
  14071. blur() {
  14072. this.menuButton_.blur();
  14073. }
  14074. /**
  14075. * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See
  14076. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  14077. *
  14078. * @param {Event} event
  14079. * The `keydown` event that caused this function to be called.
  14080. *
  14081. * @listens keydown
  14082. */
  14083. handleKeyDown(event) {
  14084. // Escape or Tab unpress the 'button'
  14085. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  14086. if (this.buttonPressed_) {
  14087. this.unpressButton();
  14088. }
  14089. // Don't preventDefault for Tab key - we still want to lose focus
  14090. if (!keycode.isEventKey(event, 'Tab')) {
  14091. event.preventDefault();
  14092. // Set focus back to the menu button's button
  14093. this.menuButton_.focus();
  14094. }
  14095. // Up Arrow or Down Arrow also 'press' the button to open the menu
  14096. } else if (keycode.isEventKey(event, 'Up') || keycode.isEventKey(event, 'Down')) {
  14097. if (!this.buttonPressed_) {
  14098. event.preventDefault();
  14099. this.pressButton();
  14100. }
  14101. }
  14102. }
  14103. /**
  14104. * Handle a `keyup` event on a `MenuButton`. The listener for this is added in
  14105. * the constructor.
  14106. *
  14107. * @param {Event} event
  14108. * Key press event
  14109. *
  14110. * @listens keyup
  14111. */
  14112. handleMenuKeyUp(event) {
  14113. // Escape hides popup menu
  14114. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  14115. this.removeClass('vjs-hover');
  14116. }
  14117. }
  14118. /**
  14119. * This method name now delegates to `handleSubmenuKeyDown`. This means
  14120. * anyone calling `handleSubmenuKeyPress` will not see their method calls
  14121. * stop working.
  14122. *
  14123. * @param {Event} event
  14124. * The event that caused this function to be called.
  14125. */
  14126. handleSubmenuKeyPress(event) {
  14127. this.handleSubmenuKeyDown(event);
  14128. }
  14129. /**
  14130. * Handle a `keydown` event on a sub-menu. The listener for this is added in
  14131. * the constructor.
  14132. *
  14133. * @param {Event} event
  14134. * Key press event
  14135. *
  14136. * @listens keydown
  14137. */
  14138. handleSubmenuKeyDown(event) {
  14139. // Escape or Tab unpress the 'button'
  14140. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  14141. if (this.buttonPressed_) {
  14142. this.unpressButton();
  14143. }
  14144. // Don't preventDefault for Tab key - we still want to lose focus
  14145. if (!keycode.isEventKey(event, 'Tab')) {
  14146. event.preventDefault();
  14147. // Set focus back to the menu button's button
  14148. this.menuButton_.focus();
  14149. }
  14150. }
  14151. }
  14152. /**
  14153. * Put the current `MenuButton` into a pressed state.
  14154. */
  14155. pressButton() {
  14156. if (this.enabled_) {
  14157. this.buttonPressed_ = true;
  14158. this.menu.show();
  14159. this.menu.lockShowing();
  14160. this.menuButton_.el_.setAttribute('aria-expanded', 'true');
  14161. // set the focus into the submenu, except on iOS where it is resulting in
  14162. // undesired scrolling behavior when the player is in an iframe
  14163. if (IS_IOS && isInFrame()) {
  14164. // Return early so that the menu isn't focused
  14165. return;
  14166. }
  14167. this.menu.focus();
  14168. }
  14169. }
  14170. /**
  14171. * Take the current `MenuButton` out of a pressed state.
  14172. */
  14173. unpressButton() {
  14174. if (this.enabled_) {
  14175. this.buttonPressed_ = false;
  14176. this.menu.unlockShowing();
  14177. this.menu.hide();
  14178. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  14179. }
  14180. }
  14181. /**
  14182. * Disable the `MenuButton`. Don't allow it to be clicked.
  14183. */
  14184. disable() {
  14185. this.unpressButton();
  14186. this.enabled_ = false;
  14187. this.addClass('vjs-disabled');
  14188. this.menuButton_.disable();
  14189. }
  14190. /**
  14191. * Enable the `MenuButton`. Allow it to be clicked.
  14192. */
  14193. enable() {
  14194. this.enabled_ = true;
  14195. this.removeClass('vjs-disabled');
  14196. this.menuButton_.enable();
  14197. }
  14198. }
  14199. Component$1.registerComponent('MenuButton', MenuButton);
  14200. /**
  14201. * @file track-button.js
  14202. */
  14203. /**
  14204. * The base class for buttons that toggle specific track types (e.g. subtitles).
  14205. *
  14206. * @extends MenuButton
  14207. */
  14208. class TrackButton extends MenuButton {
  14209. /**
  14210. * Creates an instance of this class.
  14211. *
  14212. * @param { import('./player').default } player
  14213. * The `Player` that this class should be attached to.
  14214. *
  14215. * @param {Object} [options]
  14216. * The key/value store of player options.
  14217. */
  14218. constructor(player, options) {
  14219. const tracks = options.tracks;
  14220. super(player, options);
  14221. if (this.items.length <= 1) {
  14222. this.hide();
  14223. }
  14224. if (!tracks) {
  14225. return;
  14226. }
  14227. const updateHandler = bind_(this, this.update);
  14228. tracks.addEventListener('removetrack', updateHandler);
  14229. tracks.addEventListener('addtrack', updateHandler);
  14230. tracks.addEventListener('labelchange', updateHandler);
  14231. this.player_.on('ready', updateHandler);
  14232. this.player_.on('dispose', function () {
  14233. tracks.removeEventListener('removetrack', updateHandler);
  14234. tracks.removeEventListener('addtrack', updateHandler);
  14235. tracks.removeEventListener('labelchange', updateHandler);
  14236. });
  14237. }
  14238. }
  14239. Component$1.registerComponent('TrackButton', TrackButton);
  14240. /**
  14241. * @file menu-keys.js
  14242. */
  14243. /**
  14244. * All keys used for operation of a menu (`MenuButton`, `Menu`, and `MenuItem`)
  14245. * Note that 'Enter' and 'Space' are not included here (otherwise they would
  14246. * prevent the `MenuButton` and `MenuItem` from being keyboard-clickable)
  14247. *
  14248. * @typedef MenuKeys
  14249. * @array
  14250. */
  14251. const MenuKeys = ['Tab', 'Esc', 'Up', 'Down', 'Right', 'Left'];
  14252. /**
  14253. * @file menu-item.js
  14254. */
  14255. /**
  14256. * The component for a menu item. `<li>`
  14257. *
  14258. * @extends ClickableComponent
  14259. */
  14260. class MenuItem extends ClickableComponent {
  14261. /**
  14262. * Creates an instance of the this class.
  14263. *
  14264. * @param { import('../player').default } player
  14265. * The `Player` that this class should be attached to.
  14266. *
  14267. * @param {Object} [options={}]
  14268. * The key/value store of player options.
  14269. *
  14270. */
  14271. constructor(player, options) {
  14272. super(player, options);
  14273. this.selectable = options.selectable;
  14274. this.isSelected_ = options.selected || false;
  14275. this.multiSelectable = options.multiSelectable;
  14276. this.selected(this.isSelected_);
  14277. if (this.selectable) {
  14278. if (this.multiSelectable) {
  14279. this.el_.setAttribute('role', 'menuitemcheckbox');
  14280. } else {
  14281. this.el_.setAttribute('role', 'menuitemradio');
  14282. }
  14283. } else {
  14284. this.el_.setAttribute('role', 'menuitem');
  14285. }
  14286. }
  14287. /**
  14288. * Create the `MenuItem's DOM element
  14289. *
  14290. * @param {string} [type=li]
  14291. * Element's node type, not actually used, always set to `li`.
  14292. *
  14293. * @param {Object} [props={}]
  14294. * An object of properties that should be set on the element
  14295. *
  14296. * @param {Object} [attrs={}]
  14297. * An object of attributes that should be set on the element
  14298. *
  14299. * @return {Element}
  14300. * The element that gets created.
  14301. */
  14302. createEl(type, props, attrs) {
  14303. // The control is textual, not just an icon
  14304. this.nonIconControl = true;
  14305. const el = super.createEl('li', Object.assign({
  14306. className: 'vjs-menu-item',
  14307. tabIndex: -1
  14308. }, props), attrs);
  14309. // swap icon with menu item text.
  14310. el.replaceChild(createEl('span', {
  14311. className: 'vjs-menu-item-text',
  14312. textContent: this.localize(this.options_.label)
  14313. }), el.querySelector('.vjs-icon-placeholder'));
  14314. return el;
  14315. }
  14316. /**
  14317. * Ignore keys which are used by the menu, but pass any other ones up. See
  14318. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  14319. *
  14320. * @param {Event} event
  14321. * The `keydown` event that caused this function to be called.
  14322. *
  14323. * @listens keydown
  14324. */
  14325. handleKeyDown(event) {
  14326. if (!MenuKeys.some(key => keycode.isEventKey(event, key))) {
  14327. // Pass keydown handling up for unused keys
  14328. super.handleKeyDown(event);
  14329. }
  14330. }
  14331. /**
  14332. * Any click on a `MenuItem` puts it into the selected state.
  14333. * See {@link ClickableComponent#handleClick} for instances where this is called.
  14334. *
  14335. * @param {Event} event
  14336. * The `keydown`, `tap`, or `click` event that caused this function to be
  14337. * called.
  14338. *
  14339. * @listens tap
  14340. * @listens click
  14341. */
  14342. handleClick(event) {
  14343. this.selected(true);
  14344. }
  14345. /**
  14346. * Set the state for this menu item as selected or not.
  14347. *
  14348. * @param {boolean} selected
  14349. * if the menu item is selected or not
  14350. */
  14351. selected(selected) {
  14352. if (this.selectable) {
  14353. if (selected) {
  14354. this.addClass('vjs-selected');
  14355. this.el_.setAttribute('aria-checked', 'true');
  14356. // aria-checked isn't fully supported by browsers/screen readers,
  14357. // so indicate selected state to screen reader in the control text.
  14358. this.controlText(', selected');
  14359. this.isSelected_ = true;
  14360. } else {
  14361. this.removeClass('vjs-selected');
  14362. this.el_.setAttribute('aria-checked', 'false');
  14363. // Indicate un-selected state to screen reader
  14364. this.controlText('');
  14365. this.isSelected_ = false;
  14366. }
  14367. }
  14368. }
  14369. }
  14370. Component$1.registerComponent('MenuItem', MenuItem);
  14371. /**
  14372. * @file text-track-menu-item.js
  14373. */
  14374. /**
  14375. * The specific menu item type for selecting a language within a text track kind
  14376. *
  14377. * @extends MenuItem
  14378. */
  14379. class TextTrackMenuItem extends MenuItem {
  14380. /**
  14381. * Creates an instance of this class.
  14382. *
  14383. * @param { import('../../player').default } player
  14384. * The `Player` that this class should be attached to.
  14385. *
  14386. * @param {Object} [options]
  14387. * The key/value store of player options.
  14388. */
  14389. constructor(player, options) {
  14390. const track = options.track;
  14391. const tracks = player.textTracks();
  14392. // Modify options for parent MenuItem class's init.
  14393. options.label = track.label || track.language || 'Unknown';
  14394. options.selected = track.mode === 'showing';
  14395. super(player, options);
  14396. this.track = track;
  14397. // Determine the relevant kind(s) of tracks for this component and filter
  14398. // out empty kinds.
  14399. this.kinds = (options.kinds || [options.kind || this.track.kind]).filter(Boolean);
  14400. const changeHandler = (...args) => {
  14401. this.handleTracksChange.apply(this, args);
  14402. };
  14403. const selectedLanguageChangeHandler = (...args) => {
  14404. this.handleSelectedLanguageChange.apply(this, args);
  14405. };
  14406. player.on(['loadstart', 'texttrackchange'], changeHandler);
  14407. tracks.addEventListener('change', changeHandler);
  14408. tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  14409. this.on('dispose', function () {
  14410. player.off(['loadstart', 'texttrackchange'], changeHandler);
  14411. tracks.removeEventListener('change', changeHandler);
  14412. tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  14413. });
  14414. // iOS7 doesn't dispatch change events to TextTrackLists when an
  14415. // associated track's mode changes. Without something like
  14416. // Object.observe() (also not present on iOS7), it's not
  14417. // possible to detect changes to the mode attribute and polyfill
  14418. // the change event. As a poor substitute, we manually dispatch
  14419. // change events whenever the controls modify the mode.
  14420. if (tracks.onchange === undefined) {
  14421. let event;
  14422. this.on(['tap', 'click'], function () {
  14423. if (typeof window.Event !== 'object') {
  14424. // Android 2.3 throws an Illegal Constructor error for window.Event
  14425. try {
  14426. event = new window.Event('change');
  14427. } catch (err) {
  14428. // continue regardless of error
  14429. }
  14430. }
  14431. if (!event) {
  14432. event = document.createEvent('Event');
  14433. event.initEvent('change', true, true);
  14434. }
  14435. tracks.dispatchEvent(event);
  14436. });
  14437. }
  14438. // set the default state based on current tracks
  14439. this.handleTracksChange();
  14440. }
  14441. /**
  14442. * This gets called when an `TextTrackMenuItem` is "clicked". See
  14443. * {@link ClickableComponent} for more detailed information on what a click can be.
  14444. *
  14445. * @param {Event} event
  14446. * The `keydown`, `tap`, or `click` event that caused this function to be
  14447. * called.
  14448. *
  14449. * @listens tap
  14450. * @listens click
  14451. */
  14452. handleClick(event) {
  14453. const referenceTrack = this.track;
  14454. const tracks = this.player_.textTracks();
  14455. super.handleClick(event);
  14456. if (!tracks) {
  14457. return;
  14458. }
  14459. for (let i = 0; i < tracks.length; i++) {
  14460. const track = tracks[i];
  14461. // If the track from the text tracks list is not of the right kind,
  14462. // skip it. We do not want to affect tracks of incompatible kind(s).
  14463. if (this.kinds.indexOf(track.kind) === -1) {
  14464. continue;
  14465. }
  14466. // If this text track is the component's track and it is not showing,
  14467. // set it to showing.
  14468. if (track === referenceTrack) {
  14469. if (track.mode !== 'showing') {
  14470. track.mode = 'showing';
  14471. }
  14472. // If this text track is not the component's track and it is not
  14473. // disabled, set it to disabled.
  14474. } else if (track.mode !== 'disabled') {
  14475. track.mode = 'disabled';
  14476. }
  14477. }
  14478. }
  14479. /**
  14480. * Handle text track list change
  14481. *
  14482. * @param {Event} event
  14483. * The `change` event that caused this function to be called.
  14484. *
  14485. * @listens TextTrackList#change
  14486. */
  14487. handleTracksChange(event) {
  14488. const shouldBeSelected = this.track.mode === 'showing';
  14489. // Prevent redundant selected() calls because they may cause
  14490. // screen readers to read the appended control text unnecessarily
  14491. if (shouldBeSelected !== this.isSelected_) {
  14492. this.selected(shouldBeSelected);
  14493. }
  14494. }
  14495. handleSelectedLanguageChange(event) {
  14496. if (this.track.mode === 'showing') {
  14497. const selectedLanguage = this.player_.cache_.selectedLanguage;
  14498. // Don't replace the kind of track across the same language
  14499. if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
  14500. return;
  14501. }
  14502. this.player_.cache_.selectedLanguage = {
  14503. enabled: true,
  14504. language: this.track.language,
  14505. kind: this.track.kind
  14506. };
  14507. }
  14508. }
  14509. dispose() {
  14510. // remove reference to track object on dispose
  14511. this.track = null;
  14512. super.dispose();
  14513. }
  14514. }
  14515. Component$1.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
  14516. /**
  14517. * @file off-text-track-menu-item.js
  14518. */
  14519. /**
  14520. * A special menu item for turning of a specific type of text track
  14521. *
  14522. * @extends TextTrackMenuItem
  14523. */
  14524. class OffTextTrackMenuItem extends TextTrackMenuItem {
  14525. /**
  14526. * Creates an instance of this class.
  14527. *
  14528. * @param { import('../../player').default } player
  14529. * The `Player` that this class should be attached to.
  14530. *
  14531. * @param {Object} [options]
  14532. * The key/value store of player options.
  14533. */
  14534. constructor(player, options) {
  14535. // Create pseudo track info
  14536. // Requires options['kind']
  14537. options.track = {
  14538. player,
  14539. // it is no longer necessary to store `kind` or `kinds` on the track itself
  14540. // since they are now stored in the `kinds` property of all instances of
  14541. // TextTrackMenuItem, but this will remain for backwards compatibility
  14542. kind: options.kind,
  14543. kinds: options.kinds,
  14544. default: false,
  14545. mode: 'disabled'
  14546. };
  14547. if (!options.kinds) {
  14548. options.kinds = [options.kind];
  14549. }
  14550. if (options.label) {
  14551. options.track.label = options.label;
  14552. } else {
  14553. options.track.label = options.kinds.join(' and ') + ' off';
  14554. }
  14555. // MenuItem is selectable
  14556. options.selectable = true;
  14557. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14558. options.multiSelectable = false;
  14559. super(player, options);
  14560. }
  14561. /**
  14562. * Handle text track change
  14563. *
  14564. * @param {Event} event
  14565. * The event that caused this function to run
  14566. */
  14567. handleTracksChange(event) {
  14568. const tracks = this.player().textTracks();
  14569. let shouldBeSelected = true;
  14570. for (let i = 0, l = tracks.length; i < l; i++) {
  14571. const track = tracks[i];
  14572. if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {
  14573. shouldBeSelected = false;
  14574. break;
  14575. }
  14576. }
  14577. // Prevent redundant selected() calls because they may cause
  14578. // screen readers to read the appended control text unnecessarily
  14579. if (shouldBeSelected !== this.isSelected_) {
  14580. this.selected(shouldBeSelected);
  14581. }
  14582. }
  14583. handleSelectedLanguageChange(event) {
  14584. const tracks = this.player().textTracks();
  14585. let allHidden = true;
  14586. for (let i = 0, l = tracks.length; i < l; i++) {
  14587. const track = tracks[i];
  14588. if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {
  14589. allHidden = false;
  14590. break;
  14591. }
  14592. }
  14593. if (allHidden) {
  14594. this.player_.cache_.selectedLanguage = {
  14595. enabled: false
  14596. };
  14597. }
  14598. }
  14599. /**
  14600. * Update control text and label on languagechange
  14601. */
  14602. handleLanguagechange() {
  14603. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.label);
  14604. super.handleLanguagechange();
  14605. }
  14606. }
  14607. Component$1.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
  14608. /**
  14609. * @file text-track-button.js
  14610. */
  14611. /**
  14612. * The base class for buttons that toggle specific text track types (e.g. subtitles)
  14613. *
  14614. * @extends MenuButton
  14615. */
  14616. class TextTrackButton extends TrackButton {
  14617. /**
  14618. * Creates an instance of this class.
  14619. *
  14620. * @param { import('../../player').default } player
  14621. * The `Player` that this class should be attached to.
  14622. *
  14623. * @param {Object} [options={}]
  14624. * The key/value store of player options.
  14625. */
  14626. constructor(player, options = {}) {
  14627. options.tracks = player.textTracks();
  14628. super(player, options);
  14629. }
  14630. /**
  14631. * Create a menu item for each text track
  14632. *
  14633. * @param {TextTrackMenuItem[]} [items=[]]
  14634. * Existing array of items to use during creation
  14635. *
  14636. * @return {TextTrackMenuItem[]}
  14637. * Array of menu items that were created
  14638. */
  14639. createItems(items = [], TrackMenuItem = TextTrackMenuItem) {
  14640. // Label is an override for the [track] off label
  14641. // USed to localise captions/subtitles
  14642. let label;
  14643. if (this.label_) {
  14644. label = `${this.label_} off`;
  14645. }
  14646. // Add an OFF menu item to turn all tracks off
  14647. items.push(new OffTextTrackMenuItem(this.player_, {
  14648. kinds: this.kinds_,
  14649. kind: this.kind_,
  14650. label
  14651. }));
  14652. this.hideThreshold_ += 1;
  14653. const tracks = this.player_.textTracks();
  14654. if (!Array.isArray(this.kinds_)) {
  14655. this.kinds_ = [this.kind_];
  14656. }
  14657. for (let i = 0; i < tracks.length; i++) {
  14658. const track = tracks[i];
  14659. // only add tracks that are of an appropriate kind and have a label
  14660. if (this.kinds_.indexOf(track.kind) > -1) {
  14661. const item = new TrackMenuItem(this.player_, {
  14662. track,
  14663. kinds: this.kinds_,
  14664. kind: this.kind_,
  14665. // MenuItem is selectable
  14666. selectable: true,
  14667. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14668. multiSelectable: false
  14669. });
  14670. item.addClass(`vjs-${track.kind}-menu-item`);
  14671. items.push(item);
  14672. }
  14673. }
  14674. return items;
  14675. }
  14676. }
  14677. Component$1.registerComponent('TextTrackButton', TextTrackButton);
  14678. /**
  14679. * @file chapters-track-menu-item.js
  14680. */
  14681. /**
  14682. * The chapter track menu item
  14683. *
  14684. * @extends MenuItem
  14685. */
  14686. class ChaptersTrackMenuItem extends MenuItem {
  14687. /**
  14688. * Creates an instance of this class.
  14689. *
  14690. * @param { import('../../player').default } player
  14691. * The `Player` that this class should be attached to.
  14692. *
  14693. * @param {Object} [options]
  14694. * The key/value store of player options.
  14695. */
  14696. constructor(player, options) {
  14697. const track = options.track;
  14698. const cue = options.cue;
  14699. const currentTime = player.currentTime();
  14700. // Modify options for parent MenuItem class's init.
  14701. options.selectable = true;
  14702. options.multiSelectable = false;
  14703. options.label = cue.text;
  14704. options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
  14705. super(player, options);
  14706. this.track = track;
  14707. this.cue = cue;
  14708. }
  14709. /**
  14710. * This gets called when an `ChaptersTrackMenuItem` is "clicked". See
  14711. * {@link ClickableComponent} for more detailed information on what a click can be.
  14712. *
  14713. * @param {Event} [event]
  14714. * The `keydown`, `tap`, or `click` event that caused this function to be
  14715. * called.
  14716. *
  14717. * @listens tap
  14718. * @listens click
  14719. */
  14720. handleClick(event) {
  14721. super.handleClick();
  14722. this.player_.currentTime(this.cue.startTime);
  14723. }
  14724. }
  14725. Component$1.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
  14726. /**
  14727. * @file chapters-button.js
  14728. */
  14729. /**
  14730. * The button component for toggling and selecting chapters
  14731. * Chapters act much differently than other text tracks
  14732. * Cues are navigation vs. other tracks of alternative languages
  14733. *
  14734. * @extends TextTrackButton
  14735. */
  14736. class ChaptersButton extends TextTrackButton {
  14737. /**
  14738. * Creates an instance of this class.
  14739. *
  14740. * @param { import('../../player').default } player
  14741. * The `Player` that this class should be attached to.
  14742. *
  14743. * @param {Object} [options]
  14744. * The key/value store of player options.
  14745. *
  14746. * @param {Function} [ready]
  14747. * The function to call when this function is ready.
  14748. */
  14749. constructor(player, options, ready) {
  14750. super(player, options, ready);
  14751. this.selectCurrentItem_ = () => {
  14752. this.items.forEach(item => {
  14753. item.selected(this.track_.activeCues[0] === item.cue);
  14754. });
  14755. };
  14756. }
  14757. /**
  14758. * Builds the default DOM `className`.
  14759. *
  14760. * @return {string}
  14761. * The DOM `className` for this object.
  14762. */
  14763. buildCSSClass() {
  14764. return `vjs-chapters-button ${super.buildCSSClass()}`;
  14765. }
  14766. buildWrapperCSSClass() {
  14767. return `vjs-chapters-button ${super.buildWrapperCSSClass()}`;
  14768. }
  14769. /**
  14770. * Update the menu based on the current state of its items.
  14771. *
  14772. * @param {Event} [event]
  14773. * An event that triggered this function to run.
  14774. *
  14775. * @listens TextTrackList#addtrack
  14776. * @listens TextTrackList#removetrack
  14777. * @listens TextTrackList#change
  14778. */
  14779. update(event) {
  14780. if (event && event.track && event.track.kind !== 'chapters') {
  14781. return;
  14782. }
  14783. const track = this.findChaptersTrack();
  14784. if (track !== this.track_) {
  14785. this.setTrack(track);
  14786. super.update();
  14787. } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
  14788. // Update the menu initially or if the number of cues has changed since set
  14789. super.update();
  14790. }
  14791. }
  14792. /**
  14793. * Set the currently selected track for the chapters button.
  14794. *
  14795. * @param {TextTrack} track
  14796. * The new track to select. Nothing will change if this is the currently selected
  14797. * track.
  14798. */
  14799. setTrack(track) {
  14800. if (this.track_ === track) {
  14801. return;
  14802. }
  14803. if (!this.updateHandler_) {
  14804. this.updateHandler_ = this.update.bind(this);
  14805. }
  14806. // here this.track_ refers to the old track instance
  14807. if (this.track_) {
  14808. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  14809. if (remoteTextTrackEl) {
  14810. remoteTextTrackEl.removeEventListener('load', this.updateHandler_);
  14811. }
  14812. this.track_.removeEventListener('cuechange', this.selectCurrentItem_);
  14813. this.track_ = null;
  14814. }
  14815. this.track_ = track;
  14816. // here this.track_ refers to the new track instance
  14817. if (this.track_) {
  14818. this.track_.mode = 'hidden';
  14819. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  14820. if (remoteTextTrackEl) {
  14821. remoteTextTrackEl.addEventListener('load', this.updateHandler_);
  14822. }
  14823. this.track_.addEventListener('cuechange', this.selectCurrentItem_);
  14824. }
  14825. }
  14826. /**
  14827. * Find the track object that is currently in use by this ChaptersButton
  14828. *
  14829. * @return {TextTrack|undefined}
  14830. * The current track or undefined if none was found.
  14831. */
  14832. findChaptersTrack() {
  14833. const tracks = this.player_.textTracks() || [];
  14834. for (let i = tracks.length - 1; i >= 0; i--) {
  14835. // We will always choose the last track as our chaptersTrack
  14836. const track = tracks[i];
  14837. if (track.kind === this.kind_) {
  14838. return track;
  14839. }
  14840. }
  14841. }
  14842. /**
  14843. * Get the caption for the ChaptersButton based on the track label. This will also
  14844. * use the current tracks localized kind as a fallback if a label does not exist.
  14845. *
  14846. * @return {string}
  14847. * The tracks current label or the localized track kind.
  14848. */
  14849. getMenuCaption() {
  14850. if (this.track_ && this.track_.label) {
  14851. return this.track_.label;
  14852. }
  14853. return this.localize(toTitleCase$1(this.kind_));
  14854. }
  14855. /**
  14856. * Create menu from chapter track
  14857. *
  14858. * @return { import('../../menu/menu').default }
  14859. * New menu for the chapter buttons
  14860. */
  14861. createMenu() {
  14862. this.options_.title = this.getMenuCaption();
  14863. return super.createMenu();
  14864. }
  14865. /**
  14866. * Create a menu item for each text track
  14867. *
  14868. * @return { import('./text-track-menu-item').default[] }
  14869. * Array of menu items
  14870. */
  14871. createItems() {
  14872. const items = [];
  14873. if (!this.track_) {
  14874. return items;
  14875. }
  14876. const cues = this.track_.cues;
  14877. if (!cues) {
  14878. return items;
  14879. }
  14880. for (let i = 0, l = cues.length; i < l; i++) {
  14881. const cue = cues[i];
  14882. const mi = new ChaptersTrackMenuItem(this.player_, {
  14883. track: this.track_,
  14884. cue
  14885. });
  14886. items.push(mi);
  14887. }
  14888. return items;
  14889. }
  14890. }
  14891. /**
  14892. * `kind` of TextTrack to look for to associate it with this menu.
  14893. *
  14894. * @type {string}
  14895. * @private
  14896. */
  14897. ChaptersButton.prototype.kind_ = 'chapters';
  14898. /**
  14899. * The text that should display over the `ChaptersButton`s controls. Added for localization.
  14900. *
  14901. * @type {string}
  14902. * @protected
  14903. */
  14904. ChaptersButton.prototype.controlText_ = 'Chapters';
  14905. Component$1.registerComponent('ChaptersButton', ChaptersButton);
  14906. /**
  14907. * @file descriptions-button.js
  14908. */
  14909. /**
  14910. * The button component for toggling and selecting descriptions
  14911. *
  14912. * @extends TextTrackButton
  14913. */
  14914. class DescriptionsButton extends TextTrackButton {
  14915. /**
  14916. * Creates an instance of this class.
  14917. *
  14918. * @param { import('../../player').default } player
  14919. * The `Player` that this class should be attached to.
  14920. *
  14921. * @param {Object} [options]
  14922. * The key/value store of player options.
  14923. *
  14924. * @param {Function} [ready]
  14925. * The function to call when this component is ready.
  14926. */
  14927. constructor(player, options, ready) {
  14928. super(player, options, ready);
  14929. const tracks = player.textTracks();
  14930. const changeHandler = bind_(this, this.handleTracksChange);
  14931. tracks.addEventListener('change', changeHandler);
  14932. this.on('dispose', function () {
  14933. tracks.removeEventListener('change', changeHandler);
  14934. });
  14935. }
  14936. /**
  14937. * Handle text track change
  14938. *
  14939. * @param {Event} event
  14940. * The event that caused this function to run
  14941. *
  14942. * @listens TextTrackList#change
  14943. */
  14944. handleTracksChange(event) {
  14945. const tracks = this.player().textTracks();
  14946. let disabled = false;
  14947. // Check whether a track of a different kind is showing
  14948. for (let i = 0, l = tracks.length; i < l; i++) {
  14949. const track = tracks[i];
  14950. if (track.kind !== this.kind_ && track.mode === 'showing') {
  14951. disabled = true;
  14952. break;
  14953. }
  14954. }
  14955. // If another track is showing, disable this menu button
  14956. if (disabled) {
  14957. this.disable();
  14958. } else {
  14959. this.enable();
  14960. }
  14961. }
  14962. /**
  14963. * Builds the default DOM `className`.
  14964. *
  14965. * @return {string}
  14966. * The DOM `className` for this object.
  14967. */
  14968. buildCSSClass() {
  14969. return `vjs-descriptions-button ${super.buildCSSClass()}`;
  14970. }
  14971. buildWrapperCSSClass() {
  14972. return `vjs-descriptions-button ${super.buildWrapperCSSClass()}`;
  14973. }
  14974. }
  14975. /**
  14976. * `kind` of TextTrack to look for to associate it with this menu.
  14977. *
  14978. * @type {string}
  14979. * @private
  14980. */
  14981. DescriptionsButton.prototype.kind_ = 'descriptions';
  14982. /**
  14983. * The text that should display over the `DescriptionsButton`s controls. Added for localization.
  14984. *
  14985. * @type {string}
  14986. * @protected
  14987. */
  14988. DescriptionsButton.prototype.controlText_ = 'Descriptions';
  14989. Component$1.registerComponent('DescriptionsButton', DescriptionsButton);
  14990. /**
  14991. * @file subtitles-button.js
  14992. */
  14993. /**
  14994. * The button component for toggling and selecting subtitles
  14995. *
  14996. * @extends TextTrackButton
  14997. */
  14998. class SubtitlesButton extends TextTrackButton {
  14999. /**
  15000. * Creates an instance of this class.
  15001. *
  15002. * @param { import('../../player').default } player
  15003. * The `Player` that this class should be attached to.
  15004. *
  15005. * @param {Object} [options]
  15006. * The key/value store of player options.
  15007. *
  15008. * @param {Function} [ready]
  15009. * The function to call when this component is ready.
  15010. */
  15011. constructor(player, options, ready) {
  15012. super(player, options, ready);
  15013. }
  15014. /**
  15015. * Builds the default DOM `className`.
  15016. *
  15017. * @return {string}
  15018. * The DOM `className` for this object.
  15019. */
  15020. buildCSSClass() {
  15021. return `vjs-subtitles-button ${super.buildCSSClass()}`;
  15022. }
  15023. buildWrapperCSSClass() {
  15024. return `vjs-subtitles-button ${super.buildWrapperCSSClass()}`;
  15025. }
  15026. }
  15027. /**
  15028. * `kind` of TextTrack to look for to associate it with this menu.
  15029. *
  15030. * @type {string}
  15031. * @private
  15032. */
  15033. SubtitlesButton.prototype.kind_ = 'subtitles';
  15034. /**
  15035. * The text that should display over the `SubtitlesButton`s controls. Added for localization.
  15036. *
  15037. * @type {string}
  15038. * @protected
  15039. */
  15040. SubtitlesButton.prototype.controlText_ = 'Subtitles';
  15041. Component$1.registerComponent('SubtitlesButton', SubtitlesButton);
  15042. /**
  15043. * @file caption-settings-menu-item.js
  15044. */
  15045. /**
  15046. * The menu item for caption track settings menu
  15047. *
  15048. * @extends TextTrackMenuItem
  15049. */
  15050. class CaptionSettingsMenuItem extends TextTrackMenuItem {
  15051. /**
  15052. * Creates an instance of this class.
  15053. *
  15054. * @param { import('../../player').default } player
  15055. * The `Player` that this class should be attached to.
  15056. *
  15057. * @param {Object} [options]
  15058. * The key/value store of player options.
  15059. */
  15060. constructor(player, options) {
  15061. options.track = {
  15062. player,
  15063. kind: options.kind,
  15064. label: options.kind + ' settings',
  15065. selectable: false,
  15066. default: false,
  15067. mode: 'disabled'
  15068. };
  15069. // CaptionSettingsMenuItem has no concept of 'selected'
  15070. options.selectable = false;
  15071. options.name = 'CaptionSettingsMenuItem';
  15072. super(player, options);
  15073. this.addClass('vjs-texttrack-settings');
  15074. this.controlText(', opens ' + options.kind + ' settings dialog');
  15075. }
  15076. /**
  15077. * This gets called when an `CaptionSettingsMenuItem` is "clicked". See
  15078. * {@link ClickableComponent} for more detailed information on what a click can be.
  15079. *
  15080. * @param {Event} [event]
  15081. * The `keydown`, `tap`, or `click` event that caused this function to be
  15082. * called.
  15083. *
  15084. * @listens tap
  15085. * @listens click
  15086. */
  15087. handleClick(event) {
  15088. this.player().getChild('textTrackSettings').open();
  15089. }
  15090. /**
  15091. * Update control text and label on languagechange
  15092. */
  15093. handleLanguagechange() {
  15094. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.kind + ' settings');
  15095. super.handleLanguagechange();
  15096. }
  15097. }
  15098. Component$1.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
  15099. /**
  15100. * @file captions-button.js
  15101. */
  15102. /**
  15103. * The button component for toggling and selecting captions
  15104. *
  15105. * @extends TextTrackButton
  15106. */
  15107. class CaptionsButton extends TextTrackButton {
  15108. /**
  15109. * Creates an instance of this class.
  15110. *
  15111. * @param { import('../../player').default } player
  15112. * The `Player` that this class should be attached to.
  15113. *
  15114. * @param {Object} [options]
  15115. * The key/value store of player options.
  15116. *
  15117. * @param {Function} [ready]
  15118. * The function to call when this component is ready.
  15119. */
  15120. constructor(player, options, ready) {
  15121. super(player, options, ready);
  15122. }
  15123. /**
  15124. * Builds the default DOM `className`.
  15125. *
  15126. * @return {string}
  15127. * The DOM `className` for this object.
  15128. */
  15129. buildCSSClass() {
  15130. return `vjs-captions-button ${super.buildCSSClass()}`;
  15131. }
  15132. buildWrapperCSSClass() {
  15133. return `vjs-captions-button ${super.buildWrapperCSSClass()}`;
  15134. }
  15135. /**
  15136. * Create caption menu items
  15137. *
  15138. * @return {CaptionSettingsMenuItem[]}
  15139. * The array of current menu items.
  15140. */
  15141. createItems() {
  15142. const items = [];
  15143. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  15144. items.push(new CaptionSettingsMenuItem(this.player_, {
  15145. kind: this.kind_
  15146. }));
  15147. this.hideThreshold_ += 1;
  15148. }
  15149. return super.createItems(items);
  15150. }
  15151. }
  15152. /**
  15153. * `kind` of TextTrack to look for to associate it with this menu.
  15154. *
  15155. * @type {string}
  15156. * @private
  15157. */
  15158. CaptionsButton.prototype.kind_ = 'captions';
  15159. /**
  15160. * The text that should display over the `CaptionsButton`s controls. Added for localization.
  15161. *
  15162. * @type {string}
  15163. * @protected
  15164. */
  15165. CaptionsButton.prototype.controlText_ = 'Captions';
  15166. Component$1.registerComponent('CaptionsButton', CaptionsButton);
  15167. /**
  15168. * @file subs-caps-menu-item.js
  15169. */
  15170. /**
  15171. * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
  15172. * in the SubsCapsMenu.
  15173. *
  15174. * @extends TextTrackMenuItem
  15175. */
  15176. class SubsCapsMenuItem extends TextTrackMenuItem {
  15177. createEl(type, props, attrs) {
  15178. const el = super.createEl(type, props, attrs);
  15179. const parentSpan = el.querySelector('.vjs-menu-item-text');
  15180. if (this.options_.track.kind === 'captions') {
  15181. parentSpan.appendChild(createEl('span', {
  15182. className: 'vjs-icon-placeholder'
  15183. }, {
  15184. 'aria-hidden': true
  15185. }));
  15186. parentSpan.appendChild(createEl('span', {
  15187. className: 'vjs-control-text',
  15188. // space added as the text will visually flow with the
  15189. // label
  15190. textContent: ` ${this.localize('Captions')}`
  15191. }));
  15192. }
  15193. return el;
  15194. }
  15195. }
  15196. Component$1.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);
  15197. /**
  15198. * @file sub-caps-button.js
  15199. */
  15200. /**
  15201. * The button component for toggling and selecting captions and/or subtitles
  15202. *
  15203. * @extends TextTrackButton
  15204. */
  15205. class SubsCapsButton extends TextTrackButton {
  15206. /**
  15207. * Creates an instance of this class.
  15208. *
  15209. * @param { import('../../player').default } player
  15210. * The `Player` that this class should be attached to.
  15211. *
  15212. * @param {Object} [options]
  15213. * The key/value store of player options.
  15214. *
  15215. * @param {Function} [ready]
  15216. * The function to call when this component is ready.
  15217. */
  15218. constructor(player, options = {}) {
  15219. super(player, options);
  15220. // Although North America uses "captions" in most cases for
  15221. // "captions and subtitles" other locales use "subtitles"
  15222. this.label_ = 'subtitles';
  15223. if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(this.player_.language_) > -1) {
  15224. this.label_ = 'captions';
  15225. }
  15226. this.menuButton_.controlText(toTitleCase$1(this.label_));
  15227. }
  15228. /**
  15229. * Builds the default DOM `className`.
  15230. *
  15231. * @return {string}
  15232. * The DOM `className` for this object.
  15233. */
  15234. buildCSSClass() {
  15235. return `vjs-subs-caps-button ${super.buildCSSClass()}`;
  15236. }
  15237. buildWrapperCSSClass() {
  15238. return `vjs-subs-caps-button ${super.buildWrapperCSSClass()}`;
  15239. }
  15240. /**
  15241. * Create caption/subtitles menu items
  15242. *
  15243. * @return {CaptionSettingsMenuItem[]}
  15244. * The array of current menu items.
  15245. */
  15246. createItems() {
  15247. let items = [];
  15248. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  15249. items.push(new CaptionSettingsMenuItem(this.player_, {
  15250. kind: this.label_
  15251. }));
  15252. this.hideThreshold_ += 1;
  15253. }
  15254. items = super.createItems(items, SubsCapsMenuItem);
  15255. return items;
  15256. }
  15257. }
  15258. /**
  15259. * `kind`s of TextTrack to look for to associate it with this menu.
  15260. *
  15261. * @type {array}
  15262. * @private
  15263. */
  15264. SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];
  15265. /**
  15266. * The text that should display over the `SubsCapsButton`s controls.
  15267. *
  15268. *
  15269. * @type {string}
  15270. * @protected
  15271. */
  15272. SubsCapsButton.prototype.controlText_ = 'Subtitles';
  15273. Component$1.registerComponent('SubsCapsButton', SubsCapsButton);
  15274. /**
  15275. * @file audio-track-menu-item.js
  15276. */
  15277. /**
  15278. * An {@link AudioTrack} {@link MenuItem}
  15279. *
  15280. * @extends MenuItem
  15281. */
  15282. class AudioTrackMenuItem extends MenuItem {
  15283. /**
  15284. * Creates an instance of this class.
  15285. *
  15286. * @param { import('../../player').default } player
  15287. * The `Player` that this class should be attached to.
  15288. *
  15289. * @param {Object} [options]
  15290. * The key/value store of player options.
  15291. */
  15292. constructor(player, options) {
  15293. const track = options.track;
  15294. const tracks = player.audioTracks();
  15295. // Modify options for parent MenuItem class's init.
  15296. options.label = track.label || track.language || 'Unknown';
  15297. options.selected = track.enabled;
  15298. super(player, options);
  15299. this.track = track;
  15300. this.addClass(`vjs-${track.kind}-menu-item`);
  15301. const changeHandler = (...args) => {
  15302. this.handleTracksChange.apply(this, args);
  15303. };
  15304. tracks.addEventListener('change', changeHandler);
  15305. this.on('dispose', () => {
  15306. tracks.removeEventListener('change', changeHandler);
  15307. });
  15308. }
  15309. createEl(type, props, attrs) {
  15310. const el = super.createEl(type, props, attrs);
  15311. const parentSpan = el.querySelector('.vjs-menu-item-text');
  15312. if (this.options_.track.kind === 'main-desc') {
  15313. parentSpan.appendChild(createEl('span', {
  15314. className: 'vjs-icon-placeholder'
  15315. }, {
  15316. 'aria-hidden': true
  15317. }));
  15318. parentSpan.appendChild(createEl('span', {
  15319. className: 'vjs-control-text',
  15320. textContent: ' ' + this.localize('Descriptions')
  15321. }));
  15322. }
  15323. return el;
  15324. }
  15325. /**
  15326. * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent}
  15327. * for more detailed information on what a click can be.
  15328. *
  15329. * @param {Event} [event]
  15330. * The `keydown`, `tap`, or `click` event that caused this function to be
  15331. * called.
  15332. *
  15333. * @listens tap
  15334. * @listens click
  15335. */
  15336. handleClick(event) {
  15337. super.handleClick(event);
  15338. // the audio track list will automatically toggle other tracks
  15339. // off for us.
  15340. this.track.enabled = true;
  15341. // when native audio tracks are used, we want to make sure that other tracks are turned off
  15342. if (this.player_.tech_.featuresNativeAudioTracks) {
  15343. const tracks = this.player_.audioTracks();
  15344. for (let i = 0; i < tracks.length; i++) {
  15345. const track = tracks[i];
  15346. // skip the current track since we enabled it above
  15347. if (track === this.track) {
  15348. continue;
  15349. }
  15350. track.enabled = track === this.track;
  15351. }
  15352. }
  15353. }
  15354. /**
  15355. * Handle any {@link AudioTrack} change.
  15356. *
  15357. * @param {Event} [event]
  15358. * The {@link AudioTrackList#change} event that caused this to run.
  15359. *
  15360. * @listens AudioTrackList#change
  15361. */
  15362. handleTracksChange(event) {
  15363. this.selected(this.track.enabled);
  15364. }
  15365. }
  15366. Component$1.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);
  15367. /**
  15368. * @file audio-track-button.js
  15369. */
  15370. /**
  15371. * The base class for buttons that toggle specific {@link AudioTrack} types.
  15372. *
  15373. * @extends TrackButton
  15374. */
  15375. class AudioTrackButton extends TrackButton {
  15376. /**
  15377. * Creates an instance of this class.
  15378. *
  15379. * @param {Player} player
  15380. * The `Player` that this class should be attached to.
  15381. *
  15382. * @param {Object} [options={}]
  15383. * The key/value store of player options.
  15384. */
  15385. constructor(player, options = {}) {
  15386. options.tracks = player.audioTracks();
  15387. super(player, options);
  15388. }
  15389. /**
  15390. * Builds the default DOM `className`.
  15391. *
  15392. * @return {string}
  15393. * The DOM `className` for this object.
  15394. */
  15395. buildCSSClass() {
  15396. return `vjs-audio-button ${super.buildCSSClass()}`;
  15397. }
  15398. buildWrapperCSSClass() {
  15399. return `vjs-audio-button ${super.buildWrapperCSSClass()}`;
  15400. }
  15401. /**
  15402. * Create a menu item for each audio track
  15403. *
  15404. * @param {AudioTrackMenuItem[]} [items=[]]
  15405. * An array of existing menu items to use.
  15406. *
  15407. * @return {AudioTrackMenuItem[]}
  15408. * An array of menu items
  15409. */
  15410. createItems(items = []) {
  15411. // if there's only one audio track, there no point in showing it
  15412. this.hideThreshold_ = 1;
  15413. const tracks = this.player_.audioTracks();
  15414. for (let i = 0; i < tracks.length; i++) {
  15415. const track = tracks[i];
  15416. items.push(new AudioTrackMenuItem(this.player_, {
  15417. track,
  15418. // MenuItem is selectable
  15419. selectable: true,
  15420. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  15421. multiSelectable: false
  15422. }));
  15423. }
  15424. return items;
  15425. }
  15426. }
  15427. /**
  15428. * The text that should display over the `AudioTrackButton`s controls. Added for localization.
  15429. *
  15430. * @type {string}
  15431. * @protected
  15432. */
  15433. AudioTrackButton.prototype.controlText_ = 'Audio Track';
  15434. Component$1.registerComponent('AudioTrackButton', AudioTrackButton);
  15435. /**
  15436. * @file playback-rate-menu-item.js
  15437. */
  15438. /**
  15439. * The specific menu item type for selecting a playback rate.
  15440. *
  15441. * @extends MenuItem
  15442. */
  15443. class PlaybackRateMenuItem extends MenuItem {
  15444. /**
  15445. * Creates an instance of this class.
  15446. *
  15447. * @param { import('../../player').default } player
  15448. * The `Player` that this class should be attached to.
  15449. *
  15450. * @param {Object} [options]
  15451. * The key/value store of player options.
  15452. */
  15453. constructor(player, options) {
  15454. const label = options.rate;
  15455. const rate = parseFloat(label, 10);
  15456. // Modify options for parent MenuItem class's init.
  15457. options.label = label;
  15458. options.selected = rate === player.playbackRate();
  15459. options.selectable = true;
  15460. options.multiSelectable = false;
  15461. super(player, options);
  15462. this.label = label;
  15463. this.rate = rate;
  15464. this.on(player, 'ratechange', e => this.update(e));
  15465. }
  15466. /**
  15467. * This gets called when an `PlaybackRateMenuItem` is "clicked". See
  15468. * {@link ClickableComponent} for more detailed information on what a click can be.
  15469. *
  15470. * @param {Event} [event]
  15471. * The `keydown`, `tap`, or `click` event that caused this function to be
  15472. * called.
  15473. *
  15474. * @listens tap
  15475. * @listens click
  15476. */
  15477. handleClick(event) {
  15478. super.handleClick();
  15479. this.player().playbackRate(this.rate);
  15480. }
  15481. /**
  15482. * Update the PlaybackRateMenuItem when the playbackrate changes.
  15483. *
  15484. * @param {Event} [event]
  15485. * The `ratechange` event that caused this function to run.
  15486. *
  15487. * @listens Player#ratechange
  15488. */
  15489. update(event) {
  15490. this.selected(this.player().playbackRate() === this.rate);
  15491. }
  15492. }
  15493. /**
  15494. * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.
  15495. *
  15496. * @type {string}
  15497. * @private
  15498. */
  15499. PlaybackRateMenuItem.prototype.contentElType = 'button';
  15500. Component$1.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
  15501. /**
  15502. * @file playback-rate-menu-button.js
  15503. */
  15504. /**
  15505. * The component for controlling the playback rate.
  15506. *
  15507. * @extends MenuButton
  15508. */
  15509. class PlaybackRateMenuButton extends MenuButton {
  15510. /**
  15511. * Creates an instance of this class.
  15512. *
  15513. * @param { import('../../player').default } player
  15514. * The `Player` that this class should be attached to.
  15515. *
  15516. * @param {Object} [options]
  15517. * The key/value store of player options.
  15518. */
  15519. constructor(player, options) {
  15520. super(player, options);
  15521. this.menuButton_.el_.setAttribute('aria-describedby', this.labelElId_);
  15522. this.updateVisibility();
  15523. this.updateLabel();
  15524. this.on(player, 'loadstart', e => this.updateVisibility(e));
  15525. this.on(player, 'ratechange', e => this.updateLabel(e));
  15526. this.on(player, 'playbackrateschange', e => this.handlePlaybackRateschange(e));
  15527. }
  15528. /**
  15529. * Create the `Component`'s DOM element
  15530. *
  15531. * @return {Element}
  15532. * The element that was created.
  15533. */
  15534. createEl() {
  15535. const el = super.createEl();
  15536. this.labelElId_ = 'vjs-playback-rate-value-label-' + this.id_;
  15537. this.labelEl_ = createEl('div', {
  15538. className: 'vjs-playback-rate-value',
  15539. id: this.labelElId_,
  15540. textContent: '1x'
  15541. });
  15542. el.appendChild(this.labelEl_);
  15543. return el;
  15544. }
  15545. dispose() {
  15546. this.labelEl_ = null;
  15547. super.dispose();
  15548. }
  15549. /**
  15550. * Builds the default DOM `className`.
  15551. *
  15552. * @return {string}
  15553. * The DOM `className` for this object.
  15554. */
  15555. buildCSSClass() {
  15556. return `vjs-playback-rate ${super.buildCSSClass()}`;
  15557. }
  15558. buildWrapperCSSClass() {
  15559. return `vjs-playback-rate ${super.buildWrapperCSSClass()}`;
  15560. }
  15561. /**
  15562. * Create the list of menu items. Specific to each subclass.
  15563. *
  15564. */
  15565. createItems() {
  15566. const rates = this.playbackRates();
  15567. const items = [];
  15568. for (let i = rates.length - 1; i >= 0; i--) {
  15569. items.push(new PlaybackRateMenuItem(this.player(), {
  15570. rate: rates[i] + 'x'
  15571. }));
  15572. }
  15573. return items;
  15574. }
  15575. /**
  15576. * On playbackrateschange, update the menu to account for the new items.
  15577. *
  15578. * @listens Player#playbackrateschange
  15579. */
  15580. handlePlaybackRateschange(event) {
  15581. this.update();
  15582. }
  15583. /**
  15584. * Get possible playback rates
  15585. *
  15586. * @return {Array}
  15587. * All possible playback rates
  15588. */
  15589. playbackRates() {
  15590. const player = this.player();
  15591. return player.playbackRates && player.playbackRates() || [];
  15592. }
  15593. /**
  15594. * Get whether playback rates is supported by the tech
  15595. * and an array of playback rates exists
  15596. *
  15597. * @return {boolean}
  15598. * Whether changing playback rate is supported
  15599. */
  15600. playbackRateSupported() {
  15601. return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
  15602. }
  15603. /**
  15604. * Hide playback rate controls when they're no playback rate options to select
  15605. *
  15606. * @param {Event} [event]
  15607. * The event that caused this function to run.
  15608. *
  15609. * @listens Player#loadstart
  15610. */
  15611. updateVisibility(event) {
  15612. if (this.playbackRateSupported()) {
  15613. this.removeClass('vjs-hidden');
  15614. } else {
  15615. this.addClass('vjs-hidden');
  15616. }
  15617. }
  15618. /**
  15619. * Update button label when rate changed
  15620. *
  15621. * @param {Event} [event]
  15622. * The event that caused this function to run.
  15623. *
  15624. * @listens Player#ratechange
  15625. */
  15626. updateLabel(event) {
  15627. if (this.playbackRateSupported()) {
  15628. this.labelEl_.textContent = this.player().playbackRate() + 'x';
  15629. }
  15630. }
  15631. }
  15632. /**
  15633. * The text that should display over the `PlaybackRateMenuButton`s controls.
  15634. *
  15635. * Added for localization.
  15636. *
  15637. * @type {string}
  15638. * @protected
  15639. */
  15640. PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
  15641. Component$1.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
  15642. /**
  15643. * @file spacer.js
  15644. */
  15645. /**
  15646. * Just an empty spacer element that can be used as an append point for plugins, etc.
  15647. * Also can be used to create space between elements when necessary.
  15648. *
  15649. * @extends Component
  15650. */
  15651. class Spacer extends Component$1 {
  15652. /**
  15653. * Builds the default DOM `className`.
  15654. *
  15655. * @return {string}
  15656. * The DOM `className` for this object.
  15657. */
  15658. buildCSSClass() {
  15659. return `vjs-spacer ${super.buildCSSClass()}`;
  15660. }
  15661. /**
  15662. * Create the `Component`'s DOM element
  15663. *
  15664. * @return {Element}
  15665. * The element that was created.
  15666. */
  15667. createEl(tag = 'div', props = {}, attributes = {}) {
  15668. if (!props.className) {
  15669. props.className = this.buildCSSClass();
  15670. }
  15671. return super.createEl(tag, props, attributes);
  15672. }
  15673. }
  15674. Component$1.registerComponent('Spacer', Spacer);
  15675. /**
  15676. * @file custom-control-spacer.js
  15677. */
  15678. /**
  15679. * Spacer specifically meant to be used as an insertion point for new plugins, etc.
  15680. *
  15681. * @extends Spacer
  15682. */
  15683. class CustomControlSpacer extends Spacer {
  15684. /**
  15685. * Builds the default DOM `className`.
  15686. *
  15687. * @return {string}
  15688. * The DOM `className` for this object.
  15689. */
  15690. buildCSSClass() {
  15691. return `vjs-custom-control-spacer ${super.buildCSSClass()}`;
  15692. }
  15693. /**
  15694. * Create the `Component`'s DOM element
  15695. *
  15696. * @return {Element}
  15697. * The element that was created.
  15698. */
  15699. createEl() {
  15700. return super.createEl('div', {
  15701. className: this.buildCSSClass(),
  15702. // No-flex/table-cell mode requires there be some content
  15703. // in the cell to fill the remaining space of the table.
  15704. textContent: '\u00a0'
  15705. });
  15706. }
  15707. }
  15708. Component$1.registerComponent('CustomControlSpacer', CustomControlSpacer);
  15709. /**
  15710. * @file control-bar.js
  15711. */
  15712. /**
  15713. * Container of main controls.
  15714. *
  15715. * @extends Component
  15716. */
  15717. class ControlBar extends Component$1 {
  15718. /**
  15719. * Create the `Component`'s DOM element
  15720. *
  15721. * @return {Element}
  15722. * The element that was created.
  15723. */
  15724. createEl() {
  15725. return super.createEl('div', {
  15726. className: 'vjs-control-bar',
  15727. dir: 'ltr'
  15728. });
  15729. }
  15730. }
  15731. /**
  15732. * Default options for `ControlBar`
  15733. *
  15734. * @type {Object}
  15735. * @private
  15736. */
  15737. ControlBar.prototype.options_ = {
  15738. children: ['playToggle', 'skipBackward', 'skipForward', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'fullscreenToggle']
  15739. };
  15740. if ('exitPictureInPicture' in document) {
  15741. ControlBar.prototype.options_.children.splice(ControlBar.prototype.options_.children.length - 1, 0, 'pictureInPictureToggle');
  15742. }
  15743. Component$1.registerComponent('ControlBar', ControlBar);
  15744. /**
  15745. * @file error-display.js
  15746. */
  15747. /**
  15748. * A display that indicates an error has occurred. This means that the video
  15749. * is unplayable.
  15750. *
  15751. * @extends ModalDialog
  15752. */
  15753. class ErrorDisplay extends ModalDialog {
  15754. /**
  15755. * Creates an instance of this class.
  15756. *
  15757. * @param { import('./player').default } player
  15758. * The `Player` that this class should be attached to.
  15759. *
  15760. * @param {Object} [options]
  15761. * The key/value store of player options.
  15762. */
  15763. constructor(player, options) {
  15764. super(player, options);
  15765. this.on(player, 'error', e => this.open(e));
  15766. }
  15767. /**
  15768. * Builds the default DOM `className`.
  15769. *
  15770. * @return {string}
  15771. * The DOM `className` for this object.
  15772. *
  15773. * @deprecated Since version 5.
  15774. */
  15775. buildCSSClass() {
  15776. return `vjs-error-display ${super.buildCSSClass()}`;
  15777. }
  15778. /**
  15779. * Gets the localized error message based on the `Player`s error.
  15780. *
  15781. * @return {string}
  15782. * The `Player`s error message localized or an empty string.
  15783. */
  15784. content() {
  15785. const error = this.player().error();
  15786. return error ? this.localize(error.message) : '';
  15787. }
  15788. }
  15789. /**
  15790. * The default options for an `ErrorDisplay`.
  15791. *
  15792. * @private
  15793. */
  15794. ErrorDisplay.prototype.options_ = Object.assign({}, ModalDialog.prototype.options_, {
  15795. pauseOnOpen: false,
  15796. fillAlways: true,
  15797. temporary: false,
  15798. uncloseable: true
  15799. });
  15800. Component$1.registerComponent('ErrorDisplay', ErrorDisplay);
  15801. /**
  15802. * @file text-track-settings.js
  15803. */
  15804. const LOCAL_STORAGE_KEY$1 = 'vjs-text-track-settings';
  15805. const COLOR_BLACK = ['#000', 'Black'];
  15806. const COLOR_BLUE = ['#00F', 'Blue'];
  15807. const COLOR_CYAN = ['#0FF', 'Cyan'];
  15808. const COLOR_GREEN = ['#0F0', 'Green'];
  15809. const COLOR_MAGENTA = ['#F0F', 'Magenta'];
  15810. const COLOR_RED = ['#F00', 'Red'];
  15811. const COLOR_WHITE = ['#FFF', 'White'];
  15812. const COLOR_YELLOW = ['#FF0', 'Yellow'];
  15813. const OPACITY_OPAQUE = ['1', 'Opaque'];
  15814. const OPACITY_SEMI = ['0.5', 'Semi-Transparent'];
  15815. const OPACITY_TRANS = ['0', 'Transparent'];
  15816. // Configuration for the various <select> elements in the DOM of this component.
  15817. //
  15818. // Possible keys include:
  15819. //
  15820. // `default`:
  15821. // The default option index. Only needs to be provided if not zero.
  15822. // `parser`:
  15823. // A function which is used to parse the value from the selected option in
  15824. // a customized way.
  15825. // `selector`:
  15826. // The selector used to find the associated <select> element.
  15827. const selectConfigs = {
  15828. backgroundColor: {
  15829. selector: '.vjs-bg-color > select',
  15830. id: 'captions-background-color-%s',
  15831. label: 'Color',
  15832. options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  15833. },
  15834. backgroundOpacity: {
  15835. selector: '.vjs-bg-opacity > select',
  15836. id: 'captions-background-opacity-%s',
  15837. label: 'Opacity',
  15838. options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS]
  15839. },
  15840. color: {
  15841. selector: '.vjs-text-color > select',
  15842. id: 'captions-foreground-color-%s',
  15843. label: 'Color',
  15844. options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  15845. },
  15846. edgeStyle: {
  15847. selector: '.vjs-edge-style > select',
  15848. id: '%s',
  15849. label: 'Text Edge Style',
  15850. options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']]
  15851. },
  15852. fontFamily: {
  15853. selector: '.vjs-font-family > select',
  15854. id: 'captions-font-family-%s',
  15855. label: 'Font Family',
  15856. options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]
  15857. },
  15858. fontPercent: {
  15859. selector: '.vjs-font-percent > select',
  15860. id: 'captions-font-size-%s',
  15861. label: 'Font Size',
  15862. 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%']],
  15863. default: 2,
  15864. parser: v => v === '1.00' ? null : Number(v)
  15865. },
  15866. textOpacity: {
  15867. selector: '.vjs-text-opacity > select',
  15868. id: 'captions-foreground-opacity-%s',
  15869. label: 'Opacity',
  15870. options: [OPACITY_OPAQUE, OPACITY_SEMI]
  15871. },
  15872. // Options for this object are defined below.
  15873. windowColor: {
  15874. selector: '.vjs-window-color > select',
  15875. id: 'captions-window-color-%s',
  15876. label: 'Color'
  15877. },
  15878. // Options for this object are defined below.
  15879. windowOpacity: {
  15880. selector: '.vjs-window-opacity > select',
  15881. id: 'captions-window-opacity-%s',
  15882. label: 'Opacity',
  15883. options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE]
  15884. }
  15885. };
  15886. selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
  15887. /**
  15888. * Get the actual value of an option.
  15889. *
  15890. * @param {string} value
  15891. * The value to get
  15892. *
  15893. * @param {Function} [parser]
  15894. * Optional function to adjust the value.
  15895. *
  15896. * @return {*}
  15897. * - Will be `undefined` if no value exists
  15898. * - Will be `undefined` if the given value is "none".
  15899. * - Will be the actual value otherwise.
  15900. *
  15901. * @private
  15902. */
  15903. function parseOptionValue(value, parser) {
  15904. if (parser) {
  15905. value = parser(value);
  15906. }
  15907. if (value && value !== 'none') {
  15908. return value;
  15909. }
  15910. }
  15911. /**
  15912. * Gets the value of the selected <option> element within a <select> element.
  15913. *
  15914. * @param {Element} el
  15915. * the element to look in
  15916. *
  15917. * @param {Function} [parser]
  15918. * Optional function to adjust the value.
  15919. *
  15920. * @return {*}
  15921. * - Will be `undefined` if no value exists
  15922. * - Will be `undefined` if the given value is "none".
  15923. * - Will be the actual value otherwise.
  15924. *
  15925. * @private
  15926. */
  15927. function getSelectedOptionValue(el, parser) {
  15928. const value = el.options[el.options.selectedIndex].value;
  15929. return parseOptionValue(value, parser);
  15930. }
  15931. /**
  15932. * Sets the selected <option> element within a <select> element based on a
  15933. * given value.
  15934. *
  15935. * @param {Element} el
  15936. * The element to look in.
  15937. *
  15938. * @param {string} value
  15939. * the property to look on.
  15940. *
  15941. * @param {Function} [parser]
  15942. * Optional function to adjust the value before comparing.
  15943. *
  15944. * @private
  15945. */
  15946. function setSelectedOption(el, value, parser) {
  15947. if (!value) {
  15948. return;
  15949. }
  15950. for (let i = 0; i < el.options.length; i++) {
  15951. if (parseOptionValue(el.options[i].value, parser) === value) {
  15952. el.selectedIndex = i;
  15953. break;
  15954. }
  15955. }
  15956. }
  15957. /**
  15958. * Manipulate Text Tracks settings.
  15959. *
  15960. * @extends ModalDialog
  15961. */
  15962. class TextTrackSettings extends ModalDialog {
  15963. /**
  15964. * Creates an instance of this class.
  15965. *
  15966. * @param { import('../player').default } player
  15967. * The `Player` that this class should be attached to.
  15968. *
  15969. * @param {Object} [options]
  15970. * The key/value store of player options.
  15971. */
  15972. constructor(player, options) {
  15973. options.temporary = false;
  15974. super(player, options);
  15975. this.updateDisplay = this.updateDisplay.bind(this);
  15976. // fill the modal and pretend we have opened it
  15977. this.fill();
  15978. this.hasBeenOpened_ = this.hasBeenFilled_ = true;
  15979. this.endDialog = createEl('p', {
  15980. className: 'vjs-control-text',
  15981. textContent: this.localize('End of dialog window.')
  15982. });
  15983. this.el().appendChild(this.endDialog);
  15984. this.setDefaults();
  15985. // Grab `persistTextTrackSettings` from the player options if not passed in child options
  15986. if (options.persistTextTrackSettings === undefined) {
  15987. this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings;
  15988. }
  15989. this.on(this.$('.vjs-done-button'), 'click', () => {
  15990. this.saveSettings();
  15991. this.close();
  15992. });
  15993. this.on(this.$('.vjs-default-button'), 'click', () => {
  15994. this.setDefaults();
  15995. this.updateDisplay();
  15996. });
  15997. each(selectConfigs, config => {
  15998. this.on(this.$(config.selector), 'change', this.updateDisplay);
  15999. });
  16000. if (this.options_.persistTextTrackSettings) {
  16001. this.restoreSettings();
  16002. }
  16003. }
  16004. dispose() {
  16005. this.endDialog = null;
  16006. super.dispose();
  16007. }
  16008. /**
  16009. * Create a <select> element with configured options.
  16010. *
  16011. * @param {string} key
  16012. * Configuration key to use during creation.
  16013. *
  16014. * @return {string}
  16015. * An HTML string.
  16016. *
  16017. * @private
  16018. */
  16019. createElSelect_(key, legendId = '', type = 'label') {
  16020. const config = selectConfigs[key];
  16021. const id = config.id.replace('%s', this.id_);
  16022. const selectLabelledbyIds = [legendId, id].join(' ').trim();
  16023. return [`<${type} id="${id}" class="${type === 'label' ? 'vjs-label' : ''}">`, this.localize(config.label), `</${type}>`, `<select aria-labelledby="${selectLabelledbyIds}">`].concat(config.options.map(o => {
  16024. const optionId = id + '-' + o[1].replace(/\W+/g, '');
  16025. return [`<option id="${optionId}" value="${o[0]}" `, `aria-labelledby="${selectLabelledbyIds} ${optionId}">`, this.localize(o[1]), '</option>'].join('');
  16026. })).concat('</select>').join('');
  16027. }
  16028. /**
  16029. * Create foreground color element for the component
  16030. *
  16031. * @return {string}
  16032. * An HTML string.
  16033. *
  16034. * @private
  16035. */
  16036. createElFgColor_() {
  16037. const legendId = `captions-text-legend-${this.id_}`;
  16038. return ['<fieldset class="vjs-fg vjs-track-setting">', `<legend id="${legendId}">`, this.localize('Text'), '</legend>', '<span class="vjs-text-color">', this.createElSelect_('color', legendId), '</span>', '<span class="vjs-text-opacity vjs-opacity">', this.createElSelect_('textOpacity', legendId), '</span>', '</fieldset>'].join('');
  16039. }
  16040. /**
  16041. * Create background color element for the component
  16042. *
  16043. * @return {string}
  16044. * An HTML string.
  16045. *
  16046. * @private
  16047. */
  16048. createElBgColor_() {
  16049. const legendId = `captions-background-${this.id_}`;
  16050. return ['<fieldset class="vjs-bg vjs-track-setting">', `<legend id="${legendId}">`, this.localize('Text Background'), '</legend>', '<span class="vjs-bg-color">', this.createElSelect_('backgroundColor', legendId), '</span>', '<span class="vjs-bg-opacity vjs-opacity">', this.createElSelect_('backgroundOpacity', legendId), '</span>', '</fieldset>'].join('');
  16051. }
  16052. /**
  16053. * Create window color element for the component
  16054. *
  16055. * @return {string}
  16056. * An HTML string.
  16057. *
  16058. * @private
  16059. */
  16060. createElWinColor_() {
  16061. const legendId = `captions-window-${this.id_}`;
  16062. return ['<fieldset class="vjs-window vjs-track-setting">', `<legend id="${legendId}">`, this.localize('Caption Area Background'), '</legend>', '<span class="vjs-window-color">', this.createElSelect_('windowColor', legendId), '</span>', '<span class="vjs-window-opacity vjs-opacity">', this.createElSelect_('windowOpacity', legendId), '</span>', '</fieldset>'].join('');
  16063. }
  16064. /**
  16065. * Create color elements for the component
  16066. *
  16067. * @return {Element}
  16068. * The element that was created
  16069. *
  16070. * @private
  16071. */
  16072. createElColors_() {
  16073. return createEl('div', {
  16074. className: 'vjs-track-settings-colors',
  16075. innerHTML: [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()].join('')
  16076. });
  16077. }
  16078. /**
  16079. * Create font elements for the component
  16080. *
  16081. * @return {Element}
  16082. * The element that was created.
  16083. *
  16084. * @private
  16085. */
  16086. createElFont_() {
  16087. return createEl('div', {
  16088. className: 'vjs-track-settings-font',
  16089. 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('')
  16090. });
  16091. }
  16092. /**
  16093. * Create controls for the component
  16094. *
  16095. * @return {Element}
  16096. * The element that was created.
  16097. *
  16098. * @private
  16099. */
  16100. createElControls_() {
  16101. const defaultsDescription = this.localize('restore all settings to the default values');
  16102. return createEl('div', {
  16103. className: 'vjs-track-settings-controls',
  16104. 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('')
  16105. });
  16106. }
  16107. content() {
  16108. return [this.createElColors_(), this.createElFont_(), this.createElControls_()];
  16109. }
  16110. label() {
  16111. return this.localize('Caption Settings Dialog');
  16112. }
  16113. description() {
  16114. return this.localize('Beginning of dialog window. Escape will cancel and close the window.');
  16115. }
  16116. buildCSSClass() {
  16117. return super.buildCSSClass() + ' vjs-text-track-settings';
  16118. }
  16119. /**
  16120. * Gets an object of text track settings (or null).
  16121. *
  16122. * @return {Object}
  16123. * An object with config values parsed from the DOM or localStorage.
  16124. */
  16125. getValues() {
  16126. return reduce(selectConfigs, (accum, config, key) => {
  16127. const value = getSelectedOptionValue(this.$(config.selector), config.parser);
  16128. if (value !== undefined) {
  16129. accum[key] = value;
  16130. }
  16131. return accum;
  16132. }, {});
  16133. }
  16134. /**
  16135. * Sets text track settings from an object of values.
  16136. *
  16137. * @param {Object} values
  16138. * An object with config values parsed from the DOM or localStorage.
  16139. */
  16140. setValues(values) {
  16141. each(selectConfigs, (config, key) => {
  16142. setSelectedOption(this.$(config.selector), values[key], config.parser);
  16143. });
  16144. }
  16145. /**
  16146. * Sets all `<select>` elements to their default values.
  16147. */
  16148. setDefaults() {
  16149. each(selectConfigs, config => {
  16150. const index = config.hasOwnProperty('default') ? config.default : 0;
  16151. this.$(config.selector).selectedIndex = index;
  16152. });
  16153. }
  16154. /**
  16155. * Restore texttrack settings from localStorage
  16156. */
  16157. restoreSettings() {
  16158. let values;
  16159. try {
  16160. values = JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_KEY$1));
  16161. } catch (err) {
  16162. log$1.warn(err);
  16163. }
  16164. if (values) {
  16165. this.setValues(values);
  16166. }
  16167. }
  16168. /**
  16169. * Save text track settings to localStorage
  16170. */
  16171. saveSettings() {
  16172. if (!this.options_.persistTextTrackSettings) {
  16173. return;
  16174. }
  16175. const values = this.getValues();
  16176. try {
  16177. if (Object.keys(values).length) {
  16178. window.localStorage.setItem(LOCAL_STORAGE_KEY$1, JSON.stringify(values));
  16179. } else {
  16180. window.localStorage.removeItem(LOCAL_STORAGE_KEY$1);
  16181. }
  16182. } catch (err) {
  16183. log$1.warn(err);
  16184. }
  16185. }
  16186. /**
  16187. * Update display of text track settings
  16188. */
  16189. updateDisplay() {
  16190. const ttDisplay = this.player_.getChild('textTrackDisplay');
  16191. if (ttDisplay) {
  16192. ttDisplay.updateDisplay();
  16193. }
  16194. }
  16195. /**
  16196. * conditionally blur the element and refocus the captions button
  16197. *
  16198. * @private
  16199. */
  16200. conditionalBlur_() {
  16201. this.previouslyActiveEl_ = null;
  16202. const cb = this.player_.controlBar;
  16203. const subsCapsBtn = cb && cb.subsCapsButton;
  16204. const ccBtn = cb && cb.captionsButton;
  16205. if (subsCapsBtn) {
  16206. subsCapsBtn.focus();
  16207. } else if (ccBtn) {
  16208. ccBtn.focus();
  16209. }
  16210. }
  16211. /**
  16212. * Repopulate dialog with new localizations on languagechange
  16213. */
  16214. handleLanguagechange() {
  16215. this.fill();
  16216. }
  16217. }
  16218. Component$1.registerComponent('TextTrackSettings', TextTrackSettings);
  16219. /**
  16220. * @file resize-manager.js
  16221. */
  16222. /**
  16223. * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
  16224. *
  16225. * 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}.
  16226. *
  16227. * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
  16228. * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
  16229. *
  16230. * @example <caption>How to disable the resize manager</caption>
  16231. * const player = videojs('#vid', {
  16232. * resizeManager: false
  16233. * });
  16234. *
  16235. * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
  16236. *
  16237. * @extends Component
  16238. */
  16239. class ResizeManager extends Component$1 {
  16240. /**
  16241. * Create the ResizeManager.
  16242. *
  16243. * @param {Object} player
  16244. * The `Player` that this class should be attached to.
  16245. *
  16246. * @param {Object} [options]
  16247. * The key/value store of ResizeManager options.
  16248. *
  16249. * @param {Object} [options.ResizeObserver]
  16250. * A polyfill for ResizeObserver can be passed in here.
  16251. * If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
  16252. */
  16253. constructor(player, options) {
  16254. let RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window.ResizeObserver;
  16255. // if `null` was passed, we want to disable the ResizeObserver
  16256. if (options.ResizeObserver === null) {
  16257. RESIZE_OBSERVER_AVAILABLE = false;
  16258. }
  16259. // Only create an element when ResizeObserver isn't available
  16260. const options_ = merge$2({
  16261. createEl: !RESIZE_OBSERVER_AVAILABLE,
  16262. reportTouchActivity: false
  16263. }, options);
  16264. super(player, options_);
  16265. this.ResizeObserver = options.ResizeObserver || window.ResizeObserver;
  16266. this.loadListener_ = null;
  16267. this.resizeObserver_ = null;
  16268. this.debouncedHandler_ = debounce(() => {
  16269. this.resizeHandler();
  16270. }, 100, false, this);
  16271. if (RESIZE_OBSERVER_AVAILABLE) {
  16272. this.resizeObserver_ = new this.ResizeObserver(this.debouncedHandler_);
  16273. this.resizeObserver_.observe(player.el());
  16274. } else {
  16275. this.loadListener_ = () => {
  16276. if (!this.el_ || !this.el_.contentWindow) {
  16277. return;
  16278. }
  16279. const debouncedHandler_ = this.debouncedHandler_;
  16280. let unloadListener_ = this.unloadListener_ = function () {
  16281. off(this, 'resize', debouncedHandler_);
  16282. off(this, 'unload', unloadListener_);
  16283. unloadListener_ = null;
  16284. };
  16285. // safari and edge can unload the iframe before resizemanager dispose
  16286. // we have to dispose of event handlers correctly before that happens
  16287. on(this.el_.contentWindow, 'unload', unloadListener_);
  16288. on(this.el_.contentWindow, 'resize', debouncedHandler_);
  16289. };
  16290. this.one('load', this.loadListener_);
  16291. }
  16292. }
  16293. createEl() {
  16294. return super.createEl('iframe', {
  16295. className: 'vjs-resize-manager',
  16296. tabIndex: -1,
  16297. title: this.localize('No content')
  16298. }, {
  16299. 'aria-hidden': 'true'
  16300. });
  16301. }
  16302. /**
  16303. * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
  16304. *
  16305. * @fires Player#playerresize
  16306. */
  16307. resizeHandler() {
  16308. /**
  16309. * Called when the player size has changed
  16310. *
  16311. * @event Player#playerresize
  16312. * @type {Event}
  16313. */
  16314. // make sure player is still around to trigger
  16315. // prevents this from causing an error after dispose
  16316. if (!this.player_ || !this.player_.trigger) {
  16317. return;
  16318. }
  16319. this.player_.trigger('playerresize');
  16320. }
  16321. dispose() {
  16322. if (this.debouncedHandler_) {
  16323. this.debouncedHandler_.cancel();
  16324. }
  16325. if (this.resizeObserver_) {
  16326. if (this.player_.el()) {
  16327. this.resizeObserver_.unobserve(this.player_.el());
  16328. }
  16329. this.resizeObserver_.disconnect();
  16330. }
  16331. if (this.loadListener_) {
  16332. this.off('load', this.loadListener_);
  16333. }
  16334. if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
  16335. this.unloadListener_.call(this.el_.contentWindow);
  16336. }
  16337. this.ResizeObserver = null;
  16338. this.resizeObserver = null;
  16339. this.debouncedHandler_ = null;
  16340. this.loadListener_ = null;
  16341. super.dispose();
  16342. }
  16343. }
  16344. Component$1.registerComponent('ResizeManager', ResizeManager);
  16345. const defaults = {
  16346. trackingThreshold: 20,
  16347. liveTolerance: 15
  16348. };
  16349. /*
  16350. track when we are at the live edge, and other helpers for live playback */
  16351. /**
  16352. * A class for checking live current time and determining when the player
  16353. * is at or behind the live edge.
  16354. */
  16355. class LiveTracker extends Component$1 {
  16356. /**
  16357. * Creates an instance of this class.
  16358. *
  16359. * @param { import('./player').default } player
  16360. * The `Player` that this class should be attached to.
  16361. *
  16362. * @param {Object} [options]
  16363. * The key/value store of player options.
  16364. *
  16365. * @param {number} [options.trackingThreshold=20]
  16366. * Number of seconds of live window (seekableEnd - seekableStart) that
  16367. * media needs to have before the liveui will be shown.
  16368. *
  16369. * @param {number} [options.liveTolerance=15]
  16370. * Number of seconds behind live that we have to be
  16371. * before we will be considered non-live. Note that this will only
  16372. * be used when playing at the live edge. This allows large seekable end
  16373. * changes to not effect whether we are live or not.
  16374. */
  16375. constructor(player, options) {
  16376. // LiveTracker does not need an element
  16377. const options_ = merge$2(defaults, options, {
  16378. createEl: false
  16379. });
  16380. super(player, options_);
  16381. this.trackLiveHandler_ = () => this.trackLive_();
  16382. this.handlePlay_ = e => this.handlePlay(e);
  16383. this.handleFirstTimeupdate_ = e => this.handleFirstTimeupdate(e);
  16384. this.handleSeeked_ = e => this.handleSeeked(e);
  16385. this.seekToLiveEdge_ = e => this.seekToLiveEdge(e);
  16386. this.reset_();
  16387. this.on(this.player_, 'durationchange', e => this.handleDurationchange(e));
  16388. // we should try to toggle tracking on canplay as native playback engines, like Safari
  16389. // may not have the proper values for things like seekableEnd until then
  16390. this.on(this.player_, 'canplay', () => this.toggleTracking());
  16391. }
  16392. /**
  16393. * all the functionality for tracking when seek end changes
  16394. * and for tracking how far past seek end we should be
  16395. */
  16396. trackLive_() {
  16397. const seekable = this.player_.seekable();
  16398. // skip undefined seekable
  16399. if (!seekable || !seekable.length) {
  16400. return;
  16401. }
  16402. const newTime = Number(window.performance.now().toFixed(4));
  16403. const deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1000;
  16404. this.lastTime_ = newTime;
  16405. this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;
  16406. const liveCurrentTime = this.liveCurrentTime();
  16407. const currentTime = this.player_.currentTime();
  16408. // we are behind live if any are true
  16409. // 1. the player is paused
  16410. // 2. the user seeked to a location 2 seconds away from live
  16411. // 3. the difference between live and current time is greater
  16412. // liveTolerance which defaults to 15s
  16413. let isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance;
  16414. // we cannot be behind if
  16415. // 1. until we have not seen a timeupdate yet
  16416. // 2. liveCurrentTime is Infinity, which happens on Android and Native Safari
  16417. if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {
  16418. isBehind = false;
  16419. }
  16420. if (isBehind !== this.behindLiveEdge_) {
  16421. this.behindLiveEdge_ = isBehind;
  16422. this.trigger('liveedgechange');
  16423. }
  16424. }
  16425. /**
  16426. * handle a durationchange event on the player
  16427. * and start/stop tracking accordingly.
  16428. */
  16429. handleDurationchange() {
  16430. this.toggleTracking();
  16431. }
  16432. /**
  16433. * start/stop tracking
  16434. */
  16435. toggleTracking() {
  16436. if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {
  16437. if (this.player_.options_.liveui) {
  16438. this.player_.addClass('vjs-liveui');
  16439. }
  16440. this.startTracking();
  16441. } else {
  16442. this.player_.removeClass('vjs-liveui');
  16443. this.stopTracking();
  16444. }
  16445. }
  16446. /**
  16447. * start tracking live playback
  16448. */
  16449. startTracking() {
  16450. if (this.isTracking()) {
  16451. return;
  16452. }
  16453. // If we haven't seen a timeupdate, we need to check whether playback
  16454. // began before this component started tracking. This can happen commonly
  16455. // when using autoplay.
  16456. if (!this.timeupdateSeen_) {
  16457. this.timeupdateSeen_ = this.player_.hasStarted();
  16458. }
  16459. this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);
  16460. this.trackLive_();
  16461. this.on(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  16462. if (!this.timeupdateSeen_) {
  16463. this.one(this.player_, 'play', this.handlePlay_);
  16464. this.one(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  16465. } else {
  16466. this.on(this.player_, 'seeked', this.handleSeeked_);
  16467. }
  16468. }
  16469. /**
  16470. * handle the first timeupdate on the player if it wasn't already playing
  16471. * when live tracker started tracking.
  16472. */
  16473. handleFirstTimeupdate() {
  16474. this.timeupdateSeen_ = true;
  16475. this.on(this.player_, 'seeked', this.handleSeeked_);
  16476. }
  16477. /**
  16478. * Keep track of what time a seek starts, and listen for seeked
  16479. * to find where a seek ends.
  16480. */
  16481. handleSeeked() {
  16482. const timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());
  16483. this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;
  16484. this.nextSeekedFromUser_ = false;
  16485. this.trackLive_();
  16486. }
  16487. /**
  16488. * handle the first play on the player, and make sure that we seek
  16489. * right to the live edge.
  16490. */
  16491. handlePlay() {
  16492. this.one(this.player_, 'timeupdate', this.seekToLiveEdge_);
  16493. }
  16494. /**
  16495. * Stop tracking, and set all internal variables to
  16496. * their initial value.
  16497. */
  16498. reset_() {
  16499. this.lastTime_ = -1;
  16500. this.pastSeekEnd_ = 0;
  16501. this.lastSeekEnd_ = -1;
  16502. this.behindLiveEdge_ = true;
  16503. this.timeupdateSeen_ = false;
  16504. this.seekedBehindLive_ = false;
  16505. this.nextSeekedFromUser_ = false;
  16506. this.clearInterval(this.trackingInterval_);
  16507. this.trackingInterval_ = null;
  16508. this.off(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  16509. this.off(this.player_, 'seeked', this.handleSeeked_);
  16510. this.off(this.player_, 'play', this.handlePlay_);
  16511. this.off(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  16512. this.off(this.player_, 'timeupdate', this.seekToLiveEdge_);
  16513. }
  16514. /**
  16515. * The next seeked event is from the user. Meaning that any seek
  16516. * > 2s behind live will be considered behind live for real and
  16517. * liveTolerance will be ignored.
  16518. */
  16519. nextSeekedFromUser() {
  16520. this.nextSeekedFromUser_ = true;
  16521. }
  16522. /**
  16523. * stop tracking live playback
  16524. */
  16525. stopTracking() {
  16526. if (!this.isTracking()) {
  16527. return;
  16528. }
  16529. this.reset_();
  16530. this.trigger('liveedgechange');
  16531. }
  16532. /**
  16533. * A helper to get the player seekable end
  16534. * so that we don't have to null check everywhere
  16535. *
  16536. * @return {number}
  16537. * The furthest seekable end or Infinity.
  16538. */
  16539. seekableEnd() {
  16540. const seekable = this.player_.seekable();
  16541. const seekableEnds = [];
  16542. let i = seekable ? seekable.length : 0;
  16543. while (i--) {
  16544. seekableEnds.push(seekable.end(i));
  16545. }
  16546. // grab the furthest seekable end after sorting, or if there are none
  16547. // default to Infinity
  16548. return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;
  16549. }
  16550. /**
  16551. * A helper to get the player seekable start
  16552. * so that we don't have to null check everywhere
  16553. *
  16554. * @return {number}
  16555. * The earliest seekable start or 0.
  16556. */
  16557. seekableStart() {
  16558. const seekable = this.player_.seekable();
  16559. const seekableStarts = [];
  16560. let i = seekable ? seekable.length : 0;
  16561. while (i--) {
  16562. seekableStarts.push(seekable.start(i));
  16563. }
  16564. // grab the first seekable start after sorting, or if there are none
  16565. // default to 0
  16566. return seekableStarts.length ? seekableStarts.sort()[0] : 0;
  16567. }
  16568. /**
  16569. * Get the live time window aka
  16570. * the amount of time between seekable start and
  16571. * live current time.
  16572. *
  16573. * @return {number}
  16574. * The amount of seconds that are seekable in
  16575. * the live video.
  16576. */
  16577. liveWindow() {
  16578. const liveCurrentTime = this.liveCurrentTime();
  16579. // if liveCurrenTime is Infinity then we don't have a liveWindow at all
  16580. if (liveCurrentTime === Infinity) {
  16581. return 0;
  16582. }
  16583. return liveCurrentTime - this.seekableStart();
  16584. }
  16585. /**
  16586. * Determines if the player is live, only checks if this component
  16587. * is tracking live playback or not
  16588. *
  16589. * @return {boolean}
  16590. * Whether liveTracker is tracking
  16591. */
  16592. isLive() {
  16593. return this.isTracking();
  16594. }
  16595. /**
  16596. * Determines if currentTime is at the live edge and won't fall behind
  16597. * on each seekableendchange
  16598. *
  16599. * @return {boolean}
  16600. * Whether playback is at the live edge
  16601. */
  16602. atLiveEdge() {
  16603. return !this.behindLiveEdge();
  16604. }
  16605. /**
  16606. * get what we expect the live current time to be
  16607. *
  16608. * @return {number}
  16609. * The expected live current time
  16610. */
  16611. liveCurrentTime() {
  16612. return this.pastSeekEnd() + this.seekableEnd();
  16613. }
  16614. /**
  16615. * The number of seconds that have occurred after seekable end
  16616. * changed. This will be reset to 0 once seekable end changes.
  16617. *
  16618. * @return {number}
  16619. * Seconds past the current seekable end
  16620. */
  16621. pastSeekEnd() {
  16622. const seekableEnd = this.seekableEnd();
  16623. if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {
  16624. this.pastSeekEnd_ = 0;
  16625. }
  16626. this.lastSeekEnd_ = seekableEnd;
  16627. return this.pastSeekEnd_;
  16628. }
  16629. /**
  16630. * If we are currently behind the live edge, aka currentTime will be
  16631. * behind on a seekableendchange
  16632. *
  16633. * @return {boolean}
  16634. * If we are behind the live edge
  16635. */
  16636. behindLiveEdge() {
  16637. return this.behindLiveEdge_;
  16638. }
  16639. /**
  16640. * Whether live tracker is currently tracking or not.
  16641. */
  16642. isTracking() {
  16643. return typeof this.trackingInterval_ === 'number';
  16644. }
  16645. /**
  16646. * Seek to the live edge if we are behind the live edge
  16647. */
  16648. seekToLiveEdge() {
  16649. this.seekedBehindLive_ = false;
  16650. if (this.atLiveEdge()) {
  16651. return;
  16652. }
  16653. this.nextSeekedFromUser_ = false;
  16654. this.player_.currentTime(this.liveCurrentTime());
  16655. }
  16656. /**
  16657. * Dispose of liveTracker
  16658. */
  16659. dispose() {
  16660. this.stopTracking();
  16661. super.dispose();
  16662. }
  16663. }
  16664. Component$1.registerComponent('LiveTracker', LiveTracker);
  16665. /**
  16666. * Displays an element over the player which contains an optional title and
  16667. * description for the current content.
  16668. *
  16669. * Much of the code for this component originated in the now obsolete
  16670. * videojs-dock plugin: https://github.com/brightcove/videojs-dock/
  16671. *
  16672. * @extends Component
  16673. */
  16674. class TitleBar extends Component$1 {
  16675. constructor(player, options) {
  16676. super(player, options);
  16677. this.on('statechanged', e => this.updateDom_());
  16678. this.updateDom_();
  16679. }
  16680. /**
  16681. * Create the `TitleBar`'s DOM element
  16682. *
  16683. * @return {Element}
  16684. * The element that was created.
  16685. */
  16686. createEl() {
  16687. this.els = {
  16688. title: createEl('div', {
  16689. className: 'vjs-title-bar-title',
  16690. id: `vjs-title-bar-title-${newGUID()}`
  16691. }),
  16692. description: createEl('div', {
  16693. className: 'vjs-title-bar-description',
  16694. id: `vjs-title-bar-description-${newGUID()}`
  16695. })
  16696. };
  16697. return createEl('div', {
  16698. className: 'vjs-title-bar'
  16699. }, {}, Object.values(this.els));
  16700. }
  16701. /**
  16702. * Updates the DOM based on the component's state object.
  16703. */
  16704. updateDom_() {
  16705. const tech = this.player_.tech_;
  16706. const techEl = tech && tech.el_;
  16707. const techAriaAttrs = {
  16708. title: 'aria-labelledby',
  16709. description: 'aria-describedby'
  16710. };
  16711. ['title', 'description'].forEach(k => {
  16712. const value = this.state[k];
  16713. const el = this.els[k];
  16714. const techAriaAttr = techAriaAttrs[k];
  16715. emptyEl(el);
  16716. if (value) {
  16717. textContent(el, value);
  16718. }
  16719. // If there is a tech element available, update its ARIA attributes
  16720. // according to whether a title and/or description have been provided.
  16721. if (techEl) {
  16722. techEl.removeAttribute(techAriaAttr);
  16723. if (value) {
  16724. techEl.setAttribute(techAriaAttr, el.id);
  16725. }
  16726. }
  16727. });
  16728. if (this.state.title || this.state.description) {
  16729. this.show();
  16730. } else {
  16731. this.hide();
  16732. }
  16733. }
  16734. /**
  16735. * Update the contents of the title bar component with new title and
  16736. * description text.
  16737. *
  16738. * If both title and description are missing, the title bar will be hidden.
  16739. *
  16740. * If either title or description are present, the title bar will be visible.
  16741. *
  16742. * NOTE: Any previously set value will be preserved. To unset a previously
  16743. * set value, you must pass an empty string or null.
  16744. *
  16745. * For example:
  16746. *
  16747. * ```
  16748. * update({title: 'foo', description: 'bar'}) // title: 'foo', description: 'bar'
  16749. * update({description: 'bar2'}) // title: 'foo', description: 'bar2'
  16750. * update({title: ''}) // title: '', description: 'bar2'
  16751. * update({title: 'foo', description: null}) // title: 'foo', description: null
  16752. * ```
  16753. *
  16754. * @param {Object} [options={}]
  16755. * An options object. When empty, the title bar will be hidden.
  16756. *
  16757. * @param {string} [options.title]
  16758. * A title to display in the title bar.
  16759. *
  16760. * @param {string} [options.description]
  16761. * A description to display in the title bar.
  16762. */
  16763. update(options) {
  16764. this.setState(options);
  16765. }
  16766. /**
  16767. * Dispose the component.
  16768. */
  16769. dispose() {
  16770. const tech = this.player_.tech_;
  16771. const techEl = tech && tech.el_;
  16772. if (techEl) {
  16773. techEl.removeAttribute('aria-labelledby');
  16774. techEl.removeAttribute('aria-describedby');
  16775. }
  16776. super.dispose();
  16777. this.els = null;
  16778. }
  16779. }
  16780. Component$1.registerComponent('TitleBar', TitleBar);
  16781. /**
  16782. * This function is used to fire a sourceset when there is something
  16783. * similar to `mediaEl.load()` being called. It will try to find the source via
  16784. * the `src` attribute and then the `<source>` elements. It will then fire `sourceset`
  16785. * with the source that was found or empty string if we cannot know. If it cannot
  16786. * find a source then `sourceset` will not be fired.
  16787. *
  16788. * @param { import('./html5').default } tech
  16789. * The tech object that sourceset was setup on
  16790. *
  16791. * @return {boolean}
  16792. * returns false if the sourceset was not fired and true otherwise.
  16793. */
  16794. const sourcesetLoad = tech => {
  16795. const el = tech.el();
  16796. // if `el.src` is set, that source will be loaded.
  16797. if (el.hasAttribute('src')) {
  16798. tech.triggerSourceset(el.src);
  16799. return true;
  16800. }
  16801. /**
  16802. * Since there isn't a src property on the media element, source elements will be used for
  16803. * implementing the source selection algorithm. This happens asynchronously and
  16804. * for most cases were there is more than one source we cannot tell what source will
  16805. * be loaded, without re-implementing the source selection algorithm. At this time we are not
  16806. * going to do that. There are three special cases that we do handle here though:
  16807. *
  16808. * 1. If there are no sources, do not fire `sourceset`.
  16809. * 2. If there is only one `<source>` with a `src` property/attribute that is our `src`
  16810. * 3. If there is more than one `<source>` but all of them have the same `src` url.
  16811. * That will be our src.
  16812. */
  16813. const sources = tech.$$('source');
  16814. const srcUrls = [];
  16815. let src = '';
  16816. // if there are no sources, do not fire sourceset
  16817. if (!sources.length) {
  16818. return false;
  16819. }
  16820. // only count valid/non-duplicate source elements
  16821. for (let i = 0; i < sources.length; i++) {
  16822. const url = sources[i].src;
  16823. if (url && srcUrls.indexOf(url) === -1) {
  16824. srcUrls.push(url);
  16825. }
  16826. }
  16827. // there were no valid sources
  16828. if (!srcUrls.length) {
  16829. return false;
  16830. }
  16831. // there is only one valid source element url
  16832. // use that
  16833. if (srcUrls.length === 1) {
  16834. src = srcUrls[0];
  16835. }
  16836. tech.triggerSourceset(src);
  16837. return true;
  16838. };
  16839. /**
  16840. * our implementation of an `innerHTML` descriptor for browsers
  16841. * that do not have one.
  16842. */
  16843. const innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {
  16844. get() {
  16845. return this.cloneNode(true).innerHTML;
  16846. },
  16847. set(v) {
  16848. // make a dummy node to use innerHTML on
  16849. const dummy = document.createElement(this.nodeName.toLowerCase());
  16850. // set innerHTML to the value provided
  16851. dummy.innerHTML = v;
  16852. // make a document fragment to hold the nodes from dummy
  16853. const docFrag = document.createDocumentFragment();
  16854. // copy all of the nodes created by the innerHTML on dummy
  16855. // to the document fragment
  16856. while (dummy.childNodes.length) {
  16857. docFrag.appendChild(dummy.childNodes[0]);
  16858. }
  16859. // remove content
  16860. this.innerText = '';
  16861. // now we add all of that html in one by appending the
  16862. // document fragment. This is how innerHTML does it.
  16863. window.Element.prototype.appendChild.call(this, docFrag);
  16864. // then return the result that innerHTML's setter would
  16865. return this.innerHTML;
  16866. }
  16867. });
  16868. /**
  16869. * Get a property descriptor given a list of priorities and the
  16870. * property to get.
  16871. */
  16872. const getDescriptor = (priority, prop) => {
  16873. let descriptor = {};
  16874. for (let i = 0; i < priority.length; i++) {
  16875. descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
  16876. if (descriptor && descriptor.set && descriptor.get) {
  16877. break;
  16878. }
  16879. }
  16880. descriptor.enumerable = true;
  16881. descriptor.configurable = true;
  16882. return descriptor;
  16883. };
  16884. const getInnerHTMLDescriptor = tech => getDescriptor([tech.el(), window.HTMLMediaElement.prototype, window.Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');
  16885. /**
  16886. * Patches browser internal functions so that we can tell synchronously
  16887. * if a `<source>` was appended to the media element. For some reason this
  16888. * causes a `sourceset` if the the media element is ready and has no source.
  16889. * This happens when:
  16890. * - The page has just loaded and the media element does not have a source.
  16891. * - The media element was emptied of all sources, then `load()` was called.
  16892. *
  16893. * It does this by patching the following functions/properties when they are supported:
  16894. *
  16895. * - `append()` - can be used to add a `<source>` element to the media element
  16896. * - `appendChild()` - can be used to add a `<source>` element to the media element
  16897. * - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element
  16898. * - `innerHTML` - can be used to add a `<source>` element to the media element
  16899. *
  16900. * @param {Html5} tech
  16901. * The tech object that sourceset is being setup on.
  16902. */
  16903. const firstSourceWatch = function (tech) {
  16904. const el = tech.el();
  16905. // make sure firstSourceWatch isn't setup twice.
  16906. if (el.resetSourceWatch_) {
  16907. return;
  16908. }
  16909. const old = {};
  16910. const innerDescriptor = getInnerHTMLDescriptor(tech);
  16911. const appendWrapper = appendFn => (...args) => {
  16912. const retval = appendFn.apply(el, args);
  16913. sourcesetLoad(tech);
  16914. return retval;
  16915. };
  16916. ['append', 'appendChild', 'insertAdjacentHTML'].forEach(k => {
  16917. if (!el[k]) {
  16918. return;
  16919. }
  16920. // store the old function
  16921. old[k] = el[k];
  16922. // call the old function with a sourceset if a source
  16923. // was loaded
  16924. el[k] = appendWrapper(old[k]);
  16925. });
  16926. Object.defineProperty(el, 'innerHTML', merge$2(innerDescriptor, {
  16927. set: appendWrapper(innerDescriptor.set)
  16928. }));
  16929. el.resetSourceWatch_ = () => {
  16930. el.resetSourceWatch_ = null;
  16931. Object.keys(old).forEach(k => {
  16932. el[k] = old[k];
  16933. });
  16934. Object.defineProperty(el, 'innerHTML', innerDescriptor);
  16935. };
  16936. // on the first sourceset, we need to revert our changes
  16937. tech.one('sourceset', el.resetSourceWatch_);
  16938. };
  16939. /**
  16940. * our implementation of a `src` descriptor for browsers
  16941. * that do not have one
  16942. */
  16943. const srcDescriptorPolyfill = Object.defineProperty({}, 'src', {
  16944. get() {
  16945. if (this.hasAttribute('src')) {
  16946. return getAbsoluteURL(window.Element.prototype.getAttribute.call(this, 'src'));
  16947. }
  16948. return '';
  16949. },
  16950. set(v) {
  16951. window.Element.prototype.setAttribute.call(this, 'src', v);
  16952. return v;
  16953. }
  16954. });
  16955. const getSrcDescriptor = tech => getDescriptor([tech.el(), window.HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');
  16956. /**
  16957. * setup `sourceset` handling on the `Html5` tech. This function
  16958. * patches the following element properties/functions:
  16959. *
  16960. * - `src` - to determine when `src` is set
  16961. * - `setAttribute()` - to determine when `src` is set
  16962. * - `load()` - this re-triggers the source selection algorithm, and can
  16963. * cause a sourceset.
  16964. *
  16965. * If there is no source when we are adding `sourceset` support or during a `load()`
  16966. * we also patch the functions listed in `firstSourceWatch`.
  16967. *
  16968. * @param {Html5} tech
  16969. * The tech to patch
  16970. */
  16971. const setupSourceset = function (tech) {
  16972. if (!tech.featuresSourceset) {
  16973. return;
  16974. }
  16975. const el = tech.el();
  16976. // make sure sourceset isn't setup twice.
  16977. if (el.resetSourceset_) {
  16978. return;
  16979. }
  16980. const srcDescriptor = getSrcDescriptor(tech);
  16981. const oldSetAttribute = el.setAttribute;
  16982. const oldLoad = el.load;
  16983. Object.defineProperty(el, 'src', merge$2(srcDescriptor, {
  16984. set: v => {
  16985. const retval = srcDescriptor.set.call(el, v);
  16986. // we use the getter here to get the actual value set on src
  16987. tech.triggerSourceset(el.src);
  16988. return retval;
  16989. }
  16990. }));
  16991. el.setAttribute = (n, v) => {
  16992. const retval = oldSetAttribute.call(el, n, v);
  16993. if (/src/i.test(n)) {
  16994. tech.triggerSourceset(el.src);
  16995. }
  16996. return retval;
  16997. };
  16998. el.load = () => {
  16999. const retval = oldLoad.call(el);
  17000. // if load was called, but there was no source to fire
  17001. // sourceset on. We have to watch for a source append
  17002. // as that can trigger a `sourceset` when the media element
  17003. // has no source
  17004. if (!sourcesetLoad(tech)) {
  17005. tech.triggerSourceset('');
  17006. firstSourceWatch(tech);
  17007. }
  17008. return retval;
  17009. };
  17010. if (el.currentSrc) {
  17011. tech.triggerSourceset(el.currentSrc);
  17012. } else if (!sourcesetLoad(tech)) {
  17013. firstSourceWatch(tech);
  17014. }
  17015. el.resetSourceset_ = () => {
  17016. el.resetSourceset_ = null;
  17017. el.load = oldLoad;
  17018. el.setAttribute = oldSetAttribute;
  17019. Object.defineProperty(el, 'src', srcDescriptor);
  17020. if (el.resetSourceWatch_) {
  17021. el.resetSourceWatch_();
  17022. }
  17023. };
  17024. };
  17025. /**
  17026. * @file html5.js
  17027. */
  17028. /**
  17029. * HTML5 Media Controller - Wrapper for HTML5 Media API
  17030. *
  17031. * @mixes Tech~SourceHandlerAdditions
  17032. * @extends Tech
  17033. */
  17034. class Html5 extends Tech {
  17035. /**
  17036. * Create an instance of this Tech.
  17037. *
  17038. * @param {Object} [options]
  17039. * The key/value store of player options.
  17040. *
  17041. * @param {Function} [ready]
  17042. * Callback function to call when the `HTML5` Tech is ready.
  17043. */
  17044. constructor(options, ready) {
  17045. super(options, ready);
  17046. const source = options.source;
  17047. let crossoriginTracks = false;
  17048. this.featuresVideoFrameCallback = this.featuresVideoFrameCallback && this.el_.tagName === 'VIDEO';
  17049. // Set the source if one is provided
  17050. // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
  17051. // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
  17052. // anyway so the error gets fired.
  17053. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
  17054. this.setSource(source);
  17055. } else {
  17056. this.handleLateInit_(this.el_);
  17057. }
  17058. // setup sourceset after late sourceset/init
  17059. if (options.enableSourceset) {
  17060. this.setupSourcesetHandling_();
  17061. }
  17062. this.isScrubbing_ = false;
  17063. if (this.el_.hasChildNodes()) {
  17064. const nodes = this.el_.childNodes;
  17065. let nodesLength = nodes.length;
  17066. const removeNodes = [];
  17067. while (nodesLength--) {
  17068. const node = nodes[nodesLength];
  17069. const nodeName = node.nodeName.toLowerCase();
  17070. if (nodeName === 'track') {
  17071. if (!this.featuresNativeTextTracks) {
  17072. // Empty video tag tracks so the built-in player doesn't use them also.
  17073. // This may not be fast enough to stop HTML5 browsers from reading the tags
  17074. // so we'll need to turn off any default tracks if we're manually doing
  17075. // captions and subtitles. videoElement.textTracks
  17076. removeNodes.push(node);
  17077. } else {
  17078. // store HTMLTrackElement and TextTrack to remote list
  17079. this.remoteTextTrackEls().addTrackElement_(node);
  17080. this.remoteTextTracks().addTrack(node.track);
  17081. this.textTracks().addTrack(node.track);
  17082. if (!crossoriginTracks && !this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {
  17083. crossoriginTracks = true;
  17084. }
  17085. }
  17086. }
  17087. }
  17088. for (let i = 0; i < removeNodes.length; i++) {
  17089. this.el_.removeChild(removeNodes[i]);
  17090. }
  17091. }
  17092. this.proxyNativeTracks_();
  17093. if (this.featuresNativeTextTracks && crossoriginTracks) {
  17094. 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.');
  17095. }
  17096. // prevent iOS Safari from disabling metadata text tracks during native playback
  17097. this.restoreMetadataTracksInIOSNativePlayer_();
  17098. // Determine if native controls should be used
  17099. // Our goal should be to get the custom controls on mobile solid everywhere
  17100. // so we can remove this all together. Right now this will block custom
  17101. // controls on touch enabled laptops like the Chrome Pixel
  17102. if ((TOUCH_ENABLED || IS_IPHONE) && options.nativeControlsForTouch === true) {
  17103. this.setControls(true);
  17104. }
  17105. // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
  17106. // into a `fullscreenchange` event
  17107. this.proxyWebkitFullscreen_();
  17108. this.triggerReady();
  17109. }
  17110. /**
  17111. * Dispose of `HTML5` media element and remove all tracks.
  17112. */
  17113. dispose() {
  17114. if (this.el_ && this.el_.resetSourceset_) {
  17115. this.el_.resetSourceset_();
  17116. }
  17117. Html5.disposeMediaElement(this.el_);
  17118. this.options_ = null;
  17119. // tech will handle clearing of the emulated track list
  17120. super.dispose();
  17121. }
  17122. /**
  17123. * Modify the media element so that we can detect when
  17124. * the source is changed. Fires `sourceset` just after the source has changed
  17125. */
  17126. setupSourcesetHandling_() {
  17127. setupSourceset(this);
  17128. }
  17129. /**
  17130. * When a captions track is enabled in the iOS Safari native player, all other
  17131. * tracks are disabled (including metadata tracks), which nulls all of their
  17132. * associated cue points. This will restore metadata tracks to their pre-fullscreen
  17133. * state in those cases so that cue points are not needlessly lost.
  17134. *
  17135. * @private
  17136. */
  17137. restoreMetadataTracksInIOSNativePlayer_() {
  17138. const textTracks = this.textTracks();
  17139. let metadataTracksPreFullscreenState;
  17140. // captures a snapshot of every metadata track's current state
  17141. const takeMetadataTrackSnapshot = () => {
  17142. metadataTracksPreFullscreenState = [];
  17143. for (let i = 0; i < textTracks.length; i++) {
  17144. const track = textTracks[i];
  17145. if (track.kind === 'metadata') {
  17146. metadataTracksPreFullscreenState.push({
  17147. track,
  17148. storedMode: track.mode
  17149. });
  17150. }
  17151. }
  17152. };
  17153. // snapshot each metadata track's initial state, and update the snapshot
  17154. // each time there is a track 'change' event
  17155. takeMetadataTrackSnapshot();
  17156. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  17157. this.on('dispose', () => textTracks.removeEventListener('change', takeMetadataTrackSnapshot));
  17158. const restoreTrackMode = () => {
  17159. for (let i = 0; i < metadataTracksPreFullscreenState.length; i++) {
  17160. const storedTrack = metadataTracksPreFullscreenState[i];
  17161. if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {
  17162. storedTrack.track.mode = storedTrack.storedMode;
  17163. }
  17164. }
  17165. // we only want this handler to be executed on the first 'change' event
  17166. textTracks.removeEventListener('change', restoreTrackMode);
  17167. };
  17168. // when we enter fullscreen playback, stop updating the snapshot and
  17169. // restore all track modes to their pre-fullscreen state
  17170. this.on('webkitbeginfullscreen', () => {
  17171. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  17172. // remove the listener before adding it just in case it wasn't previously removed
  17173. textTracks.removeEventListener('change', restoreTrackMode);
  17174. textTracks.addEventListener('change', restoreTrackMode);
  17175. });
  17176. // start updating the snapshot again after leaving fullscreen
  17177. this.on('webkitendfullscreen', () => {
  17178. // remove the listener before adding it just in case it wasn't previously removed
  17179. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  17180. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  17181. // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback
  17182. textTracks.removeEventListener('change', restoreTrackMode);
  17183. });
  17184. }
  17185. /**
  17186. * Attempt to force override of tracks for the given type
  17187. *
  17188. * @param {string} type - Track type to override, possible values include 'Audio',
  17189. * 'Video', and 'Text'.
  17190. * @param {boolean} override - If set to true native audio/video will be overridden,
  17191. * otherwise native audio/video will potentially be used.
  17192. * @private
  17193. */
  17194. overrideNative_(type, override) {
  17195. // If there is no behavioral change don't add/remove listeners
  17196. if (override !== this[`featuresNative${type}Tracks`]) {
  17197. return;
  17198. }
  17199. const lowerCaseType = type.toLowerCase();
  17200. if (this[`${lowerCaseType}TracksListeners_`]) {
  17201. Object.keys(this[`${lowerCaseType}TracksListeners_`]).forEach(eventName => {
  17202. const elTracks = this.el()[`${lowerCaseType}Tracks`];
  17203. elTracks.removeEventListener(eventName, this[`${lowerCaseType}TracksListeners_`][eventName]);
  17204. });
  17205. }
  17206. this[`featuresNative${type}Tracks`] = !override;
  17207. this[`${lowerCaseType}TracksListeners_`] = null;
  17208. this.proxyNativeTracksForType_(lowerCaseType);
  17209. }
  17210. /**
  17211. * Attempt to force override of native audio tracks.
  17212. *
  17213. * @param {boolean} override - If set to true native audio will be overridden,
  17214. * otherwise native audio will potentially be used.
  17215. */
  17216. overrideNativeAudioTracks(override) {
  17217. this.overrideNative_('Audio', override);
  17218. }
  17219. /**
  17220. * Attempt to force override of native video tracks.
  17221. *
  17222. * @param {boolean} override - If set to true native video will be overridden,
  17223. * otherwise native video will potentially be used.
  17224. */
  17225. overrideNativeVideoTracks(override) {
  17226. this.overrideNative_('Video', override);
  17227. }
  17228. /**
  17229. * Proxy native track list events for the given type to our track
  17230. * lists if the browser we are playing in supports that type of track list.
  17231. *
  17232. * @param {string} name - Track type; values include 'audio', 'video', and 'text'
  17233. * @private
  17234. */
  17235. proxyNativeTracksForType_(name) {
  17236. const props = NORMAL[name];
  17237. const elTracks = this.el()[props.getterName];
  17238. const techTracks = this[props.getterName]();
  17239. if (!this[`featuresNative${props.capitalName}Tracks`] || !elTracks || !elTracks.addEventListener) {
  17240. return;
  17241. }
  17242. const listeners = {
  17243. change: e => {
  17244. const event = {
  17245. type: 'change',
  17246. target: techTracks,
  17247. currentTarget: techTracks,
  17248. srcElement: techTracks
  17249. };
  17250. techTracks.trigger(event);
  17251. // if we are a text track change event, we should also notify the
  17252. // remote text track list. This can potentially cause a false positive
  17253. // if we were to get a change event on a non-remote track and
  17254. // we triggered the event on the remote text track list which doesn't
  17255. // contain that track. However, best practices mean looping through the
  17256. // list of tracks and searching for the appropriate mode value, so,
  17257. // this shouldn't pose an issue
  17258. if (name === 'text') {
  17259. this[REMOTE.remoteText.getterName]().trigger(event);
  17260. }
  17261. },
  17262. addtrack(e) {
  17263. techTracks.addTrack(e.track);
  17264. },
  17265. removetrack(e) {
  17266. techTracks.removeTrack(e.track);
  17267. }
  17268. };
  17269. const removeOldTracks = function () {
  17270. const removeTracks = [];
  17271. for (let i = 0; i < techTracks.length; i++) {
  17272. let found = false;
  17273. for (let j = 0; j < elTracks.length; j++) {
  17274. if (elTracks[j] === techTracks[i]) {
  17275. found = true;
  17276. break;
  17277. }
  17278. }
  17279. if (!found) {
  17280. removeTracks.push(techTracks[i]);
  17281. }
  17282. }
  17283. while (removeTracks.length) {
  17284. techTracks.removeTrack(removeTracks.shift());
  17285. }
  17286. };
  17287. this[props.getterName + 'Listeners_'] = listeners;
  17288. Object.keys(listeners).forEach(eventName => {
  17289. const listener = listeners[eventName];
  17290. elTracks.addEventListener(eventName, listener);
  17291. this.on('dispose', e => elTracks.removeEventListener(eventName, listener));
  17292. });
  17293. // Remove (native) tracks that are not used anymore
  17294. this.on('loadstart', removeOldTracks);
  17295. this.on('dispose', e => this.off('loadstart', removeOldTracks));
  17296. }
  17297. /**
  17298. * Proxy all native track list events to our track lists if the browser we are playing
  17299. * in supports that type of track list.
  17300. *
  17301. * @private
  17302. */
  17303. proxyNativeTracks_() {
  17304. NORMAL.names.forEach(name => {
  17305. this.proxyNativeTracksForType_(name);
  17306. });
  17307. }
  17308. /**
  17309. * Create the `Html5` Tech's DOM element.
  17310. *
  17311. * @return {Element}
  17312. * The element that gets created.
  17313. */
  17314. createEl() {
  17315. let el = this.options_.tag;
  17316. // Check if this browser supports moving the element into the box.
  17317. // On the iPhone video will break if you move the element,
  17318. // So we have to create a brand new element.
  17319. // If we ingested the player div, we do not need to move the media element.
  17320. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
  17321. // If the original tag is still there, clone and remove it.
  17322. if (el) {
  17323. const clone = el.cloneNode(true);
  17324. if (el.parentNode) {
  17325. el.parentNode.insertBefore(clone, el);
  17326. }
  17327. Html5.disposeMediaElement(el);
  17328. el = clone;
  17329. } else {
  17330. el = document.createElement('video');
  17331. // determine if native controls should be used
  17332. const tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
  17333. const attributes = merge$2({}, tagAttributes);
  17334. if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
  17335. delete attributes.controls;
  17336. }
  17337. setAttributes(el, Object.assign(attributes, {
  17338. id: this.options_.techId,
  17339. class: 'vjs-tech'
  17340. }));
  17341. }
  17342. el.playerId = this.options_.playerId;
  17343. }
  17344. if (typeof this.options_.preload !== 'undefined') {
  17345. setAttribute(el, 'preload', this.options_.preload);
  17346. }
  17347. if (this.options_.disablePictureInPicture !== undefined) {
  17348. el.disablePictureInPicture = this.options_.disablePictureInPicture;
  17349. }
  17350. // Update specific tag settings, in case they were overridden
  17351. // `autoplay` has to be *last* so that `muted` and `playsinline` are present
  17352. // when iOS/Safari or other browsers attempt to autoplay.
  17353. const settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];
  17354. for (let i = 0; i < settingsAttrs.length; i++) {
  17355. const attr = settingsAttrs[i];
  17356. const value = this.options_[attr];
  17357. if (typeof value !== 'undefined') {
  17358. if (value) {
  17359. setAttribute(el, attr, attr);
  17360. } else {
  17361. removeAttribute(el, attr);
  17362. }
  17363. el[attr] = value;
  17364. }
  17365. }
  17366. return el;
  17367. }
  17368. /**
  17369. * This will be triggered if the loadstart event has already fired, before videojs was
  17370. * ready. Two known examples of when this can happen are:
  17371. * 1. If we're loading the playback object after it has started loading
  17372. * 2. The media is already playing the (often with autoplay on) then
  17373. *
  17374. * This function will fire another loadstart so that videojs can catchup.
  17375. *
  17376. * @fires Tech#loadstart
  17377. *
  17378. * @return {undefined}
  17379. * returns nothing.
  17380. */
  17381. handleLateInit_(el) {
  17382. if (el.networkState === 0 || el.networkState === 3) {
  17383. // The video element hasn't started loading the source yet
  17384. // or didn't find a source
  17385. return;
  17386. }
  17387. if (el.readyState === 0) {
  17388. // NetworkState is set synchronously BUT loadstart is fired at the
  17389. // end of the current stack, usually before setInterval(fn, 0).
  17390. // So at this point we know loadstart may have already fired or is
  17391. // about to fire, and either way the player hasn't seen it yet.
  17392. // We don't want to fire loadstart prematurely here and cause a
  17393. // double loadstart so we'll wait and see if it happens between now
  17394. // and the next loop, and fire it if not.
  17395. // HOWEVER, we also want to make sure it fires before loadedmetadata
  17396. // which could also happen between now and the next loop, so we'll
  17397. // watch for that also.
  17398. let loadstartFired = false;
  17399. const setLoadstartFired = function () {
  17400. loadstartFired = true;
  17401. };
  17402. this.on('loadstart', setLoadstartFired);
  17403. const triggerLoadstart = function () {
  17404. // We did miss the original loadstart. Make sure the player
  17405. // sees loadstart before loadedmetadata
  17406. if (!loadstartFired) {
  17407. this.trigger('loadstart');
  17408. }
  17409. };
  17410. this.on('loadedmetadata', triggerLoadstart);
  17411. this.ready(function () {
  17412. this.off('loadstart', setLoadstartFired);
  17413. this.off('loadedmetadata', triggerLoadstart);
  17414. if (!loadstartFired) {
  17415. // We did miss the original native loadstart. Fire it now.
  17416. this.trigger('loadstart');
  17417. }
  17418. });
  17419. return;
  17420. }
  17421. // From here on we know that loadstart already fired and we missed it.
  17422. // The other readyState events aren't as much of a problem if we double
  17423. // them, so not going to go to as much trouble as loadstart to prevent
  17424. // that unless we find reason to.
  17425. const eventsToTrigger = ['loadstart'];
  17426. // loadedmetadata: newly equal to HAVE_METADATA (1) or greater
  17427. eventsToTrigger.push('loadedmetadata');
  17428. // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
  17429. if (el.readyState >= 2) {
  17430. eventsToTrigger.push('loadeddata');
  17431. }
  17432. // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
  17433. if (el.readyState >= 3) {
  17434. eventsToTrigger.push('canplay');
  17435. }
  17436. // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
  17437. if (el.readyState >= 4) {
  17438. eventsToTrigger.push('canplaythrough');
  17439. }
  17440. // We still need to give the player time to add event listeners
  17441. this.ready(function () {
  17442. eventsToTrigger.forEach(function (type) {
  17443. this.trigger(type);
  17444. }, this);
  17445. });
  17446. }
  17447. /**
  17448. * Set whether we are scrubbing or not.
  17449. * This is used to decide whether we should use `fastSeek` or not.
  17450. * `fastSeek` is used to provide trick play on Safari browsers.
  17451. *
  17452. * @param {boolean} isScrubbing
  17453. * - true for we are currently scrubbing
  17454. * - false for we are no longer scrubbing
  17455. */
  17456. setScrubbing(isScrubbing) {
  17457. this.isScrubbing_ = isScrubbing;
  17458. }
  17459. /**
  17460. * Get whether we are scrubbing or not.
  17461. *
  17462. * @return {boolean} isScrubbing
  17463. * - true for we are currently scrubbing
  17464. * - false for we are no longer scrubbing
  17465. */
  17466. scrubbing() {
  17467. return this.isScrubbing_;
  17468. }
  17469. /**
  17470. * Set current time for the `HTML5` tech.
  17471. *
  17472. * @param {number} seconds
  17473. * Set the current time of the media to this.
  17474. */
  17475. setCurrentTime(seconds) {
  17476. try {
  17477. if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {
  17478. this.el_.fastSeek(seconds);
  17479. } else {
  17480. this.el_.currentTime = seconds;
  17481. }
  17482. } catch (e) {
  17483. log$1(e, 'Video is not ready. (Video.js)');
  17484. // this.warning(VideoJS.warnings.videoNotReady);
  17485. }
  17486. }
  17487. /**
  17488. * Get the current duration of the HTML5 media element.
  17489. *
  17490. * @return {number}
  17491. * The duration of the media or 0 if there is no duration.
  17492. */
  17493. duration() {
  17494. // Android Chrome will report duration as Infinity for VOD HLS until after
  17495. // playback has started, which triggers the live display erroneously.
  17496. // Return NaN if playback has not started and trigger a durationupdate once
  17497. // the duration can be reliably known.
  17498. if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
  17499. // Wait for the first `timeupdate` with currentTime > 0 - there may be
  17500. // several with 0
  17501. const checkProgress = () => {
  17502. if (this.el_.currentTime > 0) {
  17503. // Trigger durationchange for genuinely live video
  17504. if (this.el_.duration === Infinity) {
  17505. this.trigger('durationchange');
  17506. }
  17507. this.off('timeupdate', checkProgress);
  17508. }
  17509. };
  17510. this.on('timeupdate', checkProgress);
  17511. return NaN;
  17512. }
  17513. return this.el_.duration || NaN;
  17514. }
  17515. /**
  17516. * Get the current width of the HTML5 media element.
  17517. *
  17518. * @return {number}
  17519. * The width of the HTML5 media element.
  17520. */
  17521. width() {
  17522. return this.el_.offsetWidth;
  17523. }
  17524. /**
  17525. * Get the current height of the HTML5 media element.
  17526. *
  17527. * @return {number}
  17528. * The height of the HTML5 media element.
  17529. */
  17530. height() {
  17531. return this.el_.offsetHeight;
  17532. }
  17533. /**
  17534. * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into
  17535. * `fullscreenchange` event.
  17536. *
  17537. * @private
  17538. * @fires fullscreenchange
  17539. * @listens webkitendfullscreen
  17540. * @listens webkitbeginfullscreen
  17541. * @listens webkitbeginfullscreen
  17542. */
  17543. proxyWebkitFullscreen_() {
  17544. if (!('webkitDisplayingFullscreen' in this.el_)) {
  17545. return;
  17546. }
  17547. const endFn = function () {
  17548. this.trigger('fullscreenchange', {
  17549. isFullscreen: false
  17550. });
  17551. // Safari will sometimes set controls on the videoelement when existing fullscreen.
  17552. if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {
  17553. this.el_.controls = false;
  17554. }
  17555. };
  17556. const beginFn = function () {
  17557. if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {
  17558. this.one('webkitendfullscreen', endFn);
  17559. this.trigger('fullscreenchange', {
  17560. isFullscreen: true,
  17561. // set a flag in case another tech triggers fullscreenchange
  17562. nativeIOSFullscreen: true
  17563. });
  17564. }
  17565. };
  17566. this.on('webkitbeginfullscreen', beginFn);
  17567. this.on('dispose', () => {
  17568. this.off('webkitbeginfullscreen', beginFn);
  17569. this.off('webkitendfullscreen', endFn);
  17570. });
  17571. }
  17572. /**
  17573. * Check if fullscreen is supported on the video el.
  17574. *
  17575. * @return {boolean}
  17576. * - True if fullscreen is supported.
  17577. * - False if fullscreen is not supported.
  17578. */
  17579. supportsFullScreen() {
  17580. return typeof this.el_.webkitEnterFullScreen === 'function';
  17581. }
  17582. /**
  17583. * Request that the `HTML5` Tech enter fullscreen.
  17584. */
  17585. enterFullScreen() {
  17586. const video = this.el_;
  17587. if (video.paused && video.networkState <= video.HAVE_METADATA) {
  17588. // attempt to prime the video element for programmatic access
  17589. // this isn't necessary on the desktop but shouldn't hurt
  17590. silencePromise(this.el_.play());
  17591. // playing and pausing synchronously during the transition to fullscreen
  17592. // can get iOS ~6.1 devices into a play/pause loop
  17593. this.setTimeout(function () {
  17594. video.pause();
  17595. try {
  17596. video.webkitEnterFullScreen();
  17597. } catch (e) {
  17598. this.trigger('fullscreenerror', e);
  17599. }
  17600. }, 0);
  17601. } else {
  17602. try {
  17603. video.webkitEnterFullScreen();
  17604. } catch (e) {
  17605. this.trigger('fullscreenerror', e);
  17606. }
  17607. }
  17608. }
  17609. /**
  17610. * Request that the `HTML5` Tech exit fullscreen.
  17611. */
  17612. exitFullScreen() {
  17613. if (!this.el_.webkitDisplayingFullscreen) {
  17614. this.trigger('fullscreenerror', new Error('The video is not fullscreen'));
  17615. return;
  17616. }
  17617. this.el_.webkitExitFullScreen();
  17618. }
  17619. /**
  17620. * Create a floating video window always on top of other windows so that users may
  17621. * continue consuming media while they interact with other content sites, or
  17622. * applications on their device.
  17623. *
  17624. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  17625. *
  17626. * @return {Promise}
  17627. * A promise with a Picture-in-Picture window.
  17628. */
  17629. requestPictureInPicture() {
  17630. return this.el_.requestPictureInPicture();
  17631. }
  17632. /**
  17633. * Native requestVideoFrameCallback if supported by browser/tech, or fallback
  17634. * Don't use rVCF on Safari when DRM is playing, as it doesn't fire
  17635. * Needs to be checked later than the constructor
  17636. * This will be a false positive for clear sources loaded after a Fairplay source
  17637. *
  17638. * @param {function} cb function to call
  17639. * @return {number} id of request
  17640. */
  17641. requestVideoFrameCallback(cb) {
  17642. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  17643. return this.el_.requestVideoFrameCallback(cb);
  17644. }
  17645. return super.requestVideoFrameCallback(cb);
  17646. }
  17647. /**
  17648. * Native or fallback requestVideoFrameCallback
  17649. *
  17650. * @param {number} id request id to cancel
  17651. */
  17652. cancelVideoFrameCallback(id) {
  17653. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  17654. this.el_.cancelVideoFrameCallback(id);
  17655. } else {
  17656. super.cancelVideoFrameCallback(id);
  17657. }
  17658. }
  17659. /**
  17660. * A getter/setter for the `Html5` Tech's source object.
  17661. * > Note: Please use {@link Html5#setSource}
  17662. *
  17663. * @param {Tech~SourceObject} [src]
  17664. * The source object you want to set on the `HTML5` techs element.
  17665. *
  17666. * @return {Tech~SourceObject|undefined}
  17667. * - The current source object when a source is not passed in.
  17668. * - undefined when setting
  17669. *
  17670. * @deprecated Since version 5.
  17671. */
  17672. src(src) {
  17673. if (src === undefined) {
  17674. return this.el_.src;
  17675. }
  17676. // Setting src through `src` instead of `setSrc` will be deprecated
  17677. this.setSrc(src);
  17678. }
  17679. /**
  17680. * Reset the tech by removing all sources and then calling
  17681. * {@link Html5.resetMediaElement}.
  17682. */
  17683. reset() {
  17684. Html5.resetMediaElement(this.el_);
  17685. }
  17686. /**
  17687. * Get the current source on the `HTML5` Tech. Falls back to returning the source from
  17688. * the HTML5 media element.
  17689. *
  17690. * @return {Tech~SourceObject}
  17691. * The current source object from the HTML5 tech. With a fallback to the
  17692. * elements source.
  17693. */
  17694. currentSrc() {
  17695. if (this.currentSource_) {
  17696. return this.currentSource_.src;
  17697. }
  17698. return this.el_.currentSrc;
  17699. }
  17700. /**
  17701. * Set controls attribute for the HTML5 media Element.
  17702. *
  17703. * @param {string} val
  17704. * Value to set the controls attribute to
  17705. */
  17706. setControls(val) {
  17707. this.el_.controls = !!val;
  17708. }
  17709. /**
  17710. * Create and returns a remote {@link TextTrack} object.
  17711. *
  17712. * @param {string} kind
  17713. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  17714. *
  17715. * @param {string} [label]
  17716. * Label to identify the text track
  17717. *
  17718. * @param {string} [language]
  17719. * Two letter language abbreviation
  17720. *
  17721. * @return {TextTrack}
  17722. * The TextTrack that gets created.
  17723. */
  17724. addTextTrack(kind, label, language) {
  17725. if (!this.featuresNativeTextTracks) {
  17726. return super.addTextTrack(kind, label, language);
  17727. }
  17728. return this.el_.addTextTrack(kind, label, language);
  17729. }
  17730. /**
  17731. * Creates either native TextTrack or an emulated TextTrack depending
  17732. * on the value of `featuresNativeTextTracks`
  17733. *
  17734. * @param {Object} options
  17735. * The object should contain the options to initialize the TextTrack with.
  17736. *
  17737. * @param {string} [options.kind]
  17738. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  17739. *
  17740. * @param {string} [options.label]
  17741. * Label to identify the text track
  17742. *
  17743. * @param {string} [options.language]
  17744. * Two letter language abbreviation.
  17745. *
  17746. * @param {boolean} [options.default]
  17747. * Default this track to on.
  17748. *
  17749. * @param {string} [options.id]
  17750. * The internal id to assign this track.
  17751. *
  17752. * @param {string} [options.src]
  17753. * A source url for the track.
  17754. *
  17755. * @return {HTMLTrackElement}
  17756. * The track element that gets created.
  17757. */
  17758. createRemoteTextTrack(options) {
  17759. if (!this.featuresNativeTextTracks) {
  17760. return super.createRemoteTextTrack(options);
  17761. }
  17762. const htmlTrackElement = document.createElement('track');
  17763. if (options.kind) {
  17764. htmlTrackElement.kind = options.kind;
  17765. }
  17766. if (options.label) {
  17767. htmlTrackElement.label = options.label;
  17768. }
  17769. if (options.language || options.srclang) {
  17770. htmlTrackElement.srclang = options.language || options.srclang;
  17771. }
  17772. if (options.default) {
  17773. htmlTrackElement.default = options.default;
  17774. }
  17775. if (options.id) {
  17776. htmlTrackElement.id = options.id;
  17777. }
  17778. if (options.src) {
  17779. htmlTrackElement.src = options.src;
  17780. }
  17781. return htmlTrackElement;
  17782. }
  17783. /**
  17784. * Creates a remote text track object and returns an html track element.
  17785. *
  17786. * @param {Object} options The object should contain values for
  17787. * kind, language, label, and src (location of the WebVTT file)
  17788. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack
  17789. * will not be removed from the TextTrackList and HtmlTrackElementList
  17790. * after a source change
  17791. * @return {HTMLTrackElement} An Html Track Element.
  17792. * This can be an emulated {@link HTMLTrackElement} or a native one.
  17793. *
  17794. */
  17795. addRemoteTextTrack(options, manualCleanup) {
  17796. const htmlTrackElement = super.addRemoteTextTrack(options, manualCleanup);
  17797. if (this.featuresNativeTextTracks) {
  17798. this.el().appendChild(htmlTrackElement);
  17799. }
  17800. return htmlTrackElement;
  17801. }
  17802. /**
  17803. * Remove remote `TextTrack` from `TextTrackList` object
  17804. *
  17805. * @param {TextTrack} track
  17806. * `TextTrack` object to remove
  17807. */
  17808. removeRemoteTextTrack(track) {
  17809. super.removeRemoteTextTrack(track);
  17810. if (this.featuresNativeTextTracks) {
  17811. const tracks = this.$$('track');
  17812. let i = tracks.length;
  17813. while (i--) {
  17814. if (track === tracks[i] || track === tracks[i].track) {
  17815. this.el().removeChild(tracks[i]);
  17816. }
  17817. }
  17818. }
  17819. }
  17820. /**
  17821. * Gets available media playback quality metrics as specified by the W3C's Media
  17822. * Playback Quality API.
  17823. *
  17824. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  17825. *
  17826. * @return {Object}
  17827. * An object with supported media playback quality metrics
  17828. */
  17829. getVideoPlaybackQuality() {
  17830. if (typeof this.el().getVideoPlaybackQuality === 'function') {
  17831. return this.el().getVideoPlaybackQuality();
  17832. }
  17833. const videoPlaybackQuality = {};
  17834. if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {
  17835. videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
  17836. videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
  17837. }
  17838. if (window.performance) {
  17839. videoPlaybackQuality.creationTime = window.performance.now();
  17840. }
  17841. return videoPlaybackQuality;
  17842. }
  17843. }
  17844. /* HTML5 Support Testing ---------------------------------------------------- */
  17845. /**
  17846. * Element for testing browser HTML5 media capabilities
  17847. *
  17848. * @type {Element}
  17849. * @constant
  17850. * @private
  17851. */
  17852. defineLazyProperty(Html5, 'TEST_VID', function () {
  17853. if (!isReal()) {
  17854. return;
  17855. }
  17856. const video = document.createElement('video');
  17857. const track = document.createElement('track');
  17858. track.kind = 'captions';
  17859. track.srclang = 'en';
  17860. track.label = 'English';
  17861. video.appendChild(track);
  17862. return video;
  17863. });
  17864. /**
  17865. * Check if HTML5 media is supported by this browser/device.
  17866. *
  17867. * @return {boolean}
  17868. * - True if HTML5 media is supported.
  17869. * - False if HTML5 media is not supported.
  17870. */
  17871. Html5.isSupported = function () {
  17872. // IE with no Media Player is a LIAR! (#984)
  17873. try {
  17874. Html5.TEST_VID.volume = 0.5;
  17875. } catch (e) {
  17876. return false;
  17877. }
  17878. return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
  17879. };
  17880. /**
  17881. * Check if the tech can support the given type
  17882. *
  17883. * @param {string} type
  17884. * The mimetype to check
  17885. * @return {string} 'probably', 'maybe', or '' (empty string)
  17886. */
  17887. Html5.canPlayType = function (type) {
  17888. return Html5.TEST_VID.canPlayType(type);
  17889. };
  17890. /**
  17891. * Check if the tech can support the given source
  17892. *
  17893. * @param {Object} srcObj
  17894. * The source object
  17895. * @param {Object} options
  17896. * The options passed to the tech
  17897. * @return {string} 'probably', 'maybe', or '' (empty string)
  17898. */
  17899. Html5.canPlaySource = function (srcObj, options) {
  17900. return Html5.canPlayType(srcObj.type);
  17901. };
  17902. /**
  17903. * Check if the volume can be changed in this browser/device.
  17904. * Volume cannot be changed in a lot of mobile devices.
  17905. * Specifically, it can't be changed from 1 on iOS.
  17906. *
  17907. * @return {boolean}
  17908. * - True if volume can be controlled
  17909. * - False otherwise
  17910. */
  17911. Html5.canControlVolume = function () {
  17912. // IE will error if Windows Media Player not installed #3315
  17913. try {
  17914. const volume = Html5.TEST_VID.volume;
  17915. Html5.TEST_VID.volume = volume / 2 + 0.1;
  17916. const canControl = volume !== Html5.TEST_VID.volume;
  17917. // With the introduction of iOS 15, there are cases where the volume is read as
  17918. // changed but reverts back to its original state at the start of the next tick.
  17919. // To determine whether volume can be controlled on iOS,
  17920. // a timeout is set and the volume is checked asynchronously.
  17921. // Since `features` doesn't currently work asynchronously, the value is manually set.
  17922. if (canControl && IS_IOS) {
  17923. window.setTimeout(() => {
  17924. if (Html5 && Html5.prototype) {
  17925. Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;
  17926. }
  17927. });
  17928. // default iOS to false, which will be updated in the timeout above.
  17929. return false;
  17930. }
  17931. return canControl;
  17932. } catch (e) {
  17933. return false;
  17934. }
  17935. };
  17936. /**
  17937. * Check if the volume can be muted in this browser/device.
  17938. * Some devices, e.g. iOS, don't allow changing volume
  17939. * but permits muting/unmuting.
  17940. *
  17941. * @return {boolean}
  17942. * - True if volume can be muted
  17943. * - False otherwise
  17944. */
  17945. Html5.canMuteVolume = function () {
  17946. try {
  17947. const muted = Html5.TEST_VID.muted;
  17948. // in some versions of iOS muted property doesn't always
  17949. // work, so we want to set both property and attribute
  17950. Html5.TEST_VID.muted = !muted;
  17951. if (Html5.TEST_VID.muted) {
  17952. setAttribute(Html5.TEST_VID, 'muted', 'muted');
  17953. } else {
  17954. removeAttribute(Html5.TEST_VID, 'muted', 'muted');
  17955. }
  17956. return muted !== Html5.TEST_VID.muted;
  17957. } catch (e) {
  17958. return false;
  17959. }
  17960. };
  17961. /**
  17962. * Check if the playback rate can be changed in this browser/device.
  17963. *
  17964. * @return {boolean}
  17965. * - True if playback rate can be controlled
  17966. * - False otherwise
  17967. */
  17968. Html5.canControlPlaybackRate = function () {
  17969. // Playback rate API is implemented in Android Chrome, but doesn't do anything
  17970. // https://github.com/videojs/video.js/issues/3180
  17971. if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
  17972. return false;
  17973. }
  17974. // IE will error if Windows Media Player not installed #3315
  17975. try {
  17976. const playbackRate = Html5.TEST_VID.playbackRate;
  17977. Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
  17978. return playbackRate !== Html5.TEST_VID.playbackRate;
  17979. } catch (e) {
  17980. return false;
  17981. }
  17982. };
  17983. /**
  17984. * Check if we can override a video/audio elements attributes, with
  17985. * Object.defineProperty.
  17986. *
  17987. * @return {boolean}
  17988. * - True if builtin attributes can be overridden
  17989. * - False otherwise
  17990. */
  17991. Html5.canOverrideAttributes = function () {
  17992. // if we cannot overwrite the src/innerHTML property, there is no support
  17993. // iOS 7 safari for instance cannot do this.
  17994. try {
  17995. const noop = () => {};
  17996. Object.defineProperty(document.createElement('video'), 'src', {
  17997. get: noop,
  17998. set: noop
  17999. });
  18000. Object.defineProperty(document.createElement('audio'), 'src', {
  18001. get: noop,
  18002. set: noop
  18003. });
  18004. Object.defineProperty(document.createElement('video'), 'innerHTML', {
  18005. get: noop,
  18006. set: noop
  18007. });
  18008. Object.defineProperty(document.createElement('audio'), 'innerHTML', {
  18009. get: noop,
  18010. set: noop
  18011. });
  18012. } catch (e) {
  18013. return false;
  18014. }
  18015. return true;
  18016. };
  18017. /**
  18018. * Check to see if native `TextTrack`s are supported by this browser/device.
  18019. *
  18020. * @return {boolean}
  18021. * - True if native `TextTrack`s are supported.
  18022. * - False otherwise
  18023. */
  18024. Html5.supportsNativeTextTracks = function () {
  18025. return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
  18026. };
  18027. /**
  18028. * Check to see if native `VideoTrack`s are supported by this browser/device
  18029. *
  18030. * @return {boolean}
  18031. * - True if native `VideoTrack`s are supported.
  18032. * - False otherwise
  18033. */
  18034. Html5.supportsNativeVideoTracks = function () {
  18035. return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
  18036. };
  18037. /**
  18038. * Check to see if native `AudioTrack`s are supported by this browser/device
  18039. *
  18040. * @return {boolean}
  18041. * - True if native `AudioTrack`s are supported.
  18042. * - False otherwise
  18043. */
  18044. Html5.supportsNativeAudioTracks = function () {
  18045. return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
  18046. };
  18047. /**
  18048. * An array of events available on the Html5 tech.
  18049. *
  18050. * @private
  18051. * @type {Array}
  18052. */
  18053. 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'];
  18054. /**
  18055. * Boolean indicating whether the `Tech` supports volume control.
  18056. *
  18057. * @type {boolean}
  18058. * @default {@link Html5.canControlVolume}
  18059. */
  18060. /**
  18061. * Boolean indicating whether the `Tech` supports muting volume.
  18062. *
  18063. * @type {boolean}
  18064. * @default {@link Html5.canMuteVolume}
  18065. */
  18066. /**
  18067. * Boolean indicating whether the `Tech` supports changing the speed at which the media
  18068. * plays. Examples:
  18069. * - Set player to play 2x (twice) as fast
  18070. * - Set player to play 0.5x (half) as fast
  18071. *
  18072. * @type {boolean}
  18073. * @default {@link Html5.canControlPlaybackRate}
  18074. */
  18075. /**
  18076. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  18077. *
  18078. * @type {boolean}
  18079. * @default
  18080. */
  18081. /**
  18082. * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.
  18083. *
  18084. * @type {boolean}
  18085. * @default {@link Html5.supportsNativeTextTracks}
  18086. */
  18087. /**
  18088. * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.
  18089. *
  18090. * @type {boolean}
  18091. * @default {@link Html5.supportsNativeVideoTracks}
  18092. */
  18093. /**
  18094. * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.
  18095. *
  18096. * @type {boolean}
  18097. * @default {@link Html5.supportsNativeAudioTracks}
  18098. */
  18099. [['featuresMuteControl', 'canMuteVolume'], ['featuresPlaybackRate', 'canControlPlaybackRate'], ['featuresSourceset', 'canOverrideAttributes'], ['featuresNativeTextTracks', 'supportsNativeTextTracks'], ['featuresNativeVideoTracks', 'supportsNativeVideoTracks'], ['featuresNativeAudioTracks', 'supportsNativeAudioTracks']].forEach(function ([key, fn]) {
  18100. defineLazyProperty(Html5.prototype, key, () => Html5[fn](), true);
  18101. });
  18102. Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
  18103. /**
  18104. * Boolean indicating whether the `HTML5` tech currently supports the media element
  18105. * moving in the DOM. iOS breaks if you move the media element, so this is set this to
  18106. * false there. Everywhere else this should be true.
  18107. *
  18108. * @type {boolean}
  18109. * @default
  18110. */
  18111. Html5.prototype.movingMediaElementInDOM = !IS_IOS;
  18112. // TODO: Previous comment: No longer appears to be used. Can probably be removed.
  18113. // Is this true?
  18114. /**
  18115. * Boolean indicating whether the `HTML5` tech currently supports automatic media resize
  18116. * when going into fullscreen.
  18117. *
  18118. * @type {boolean}
  18119. * @default
  18120. */
  18121. Html5.prototype.featuresFullscreenResize = true;
  18122. /**
  18123. * Boolean indicating whether the `HTML5` tech currently supports the progress event.
  18124. * If this is false, manual `progress` events will be triggered instead.
  18125. *
  18126. * @type {boolean}
  18127. * @default
  18128. */
  18129. Html5.prototype.featuresProgressEvents = true;
  18130. /**
  18131. * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.
  18132. * If this is false, manual `timeupdate` events will be triggered instead.
  18133. *
  18134. * @default
  18135. */
  18136. Html5.prototype.featuresTimeupdateEvents = true;
  18137. /**
  18138. * Whether the HTML5 el supports `requestVideoFrameCallback`
  18139. *
  18140. * @type {boolean}
  18141. */
  18142. Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback);
  18143. Html5.disposeMediaElement = function (el) {
  18144. if (!el) {
  18145. return;
  18146. }
  18147. if (el.parentNode) {
  18148. el.parentNode.removeChild(el);
  18149. }
  18150. // remove any child track or source nodes to prevent their loading
  18151. while (el.hasChildNodes()) {
  18152. el.removeChild(el.firstChild);
  18153. }
  18154. // remove any src reference. not setting `src=''` because that causes a warning
  18155. // in firefox
  18156. el.removeAttribute('src');
  18157. // force the media element to update its loading state by calling load()
  18158. // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
  18159. if (typeof el.load === 'function') {
  18160. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  18161. (function () {
  18162. try {
  18163. el.load();
  18164. } catch (e) {
  18165. // not supported
  18166. }
  18167. })();
  18168. }
  18169. };
  18170. Html5.resetMediaElement = function (el) {
  18171. if (!el) {
  18172. return;
  18173. }
  18174. const sources = el.querySelectorAll('source');
  18175. let i = sources.length;
  18176. while (i--) {
  18177. el.removeChild(sources[i]);
  18178. }
  18179. // remove any src reference.
  18180. // not setting `src=''` because that throws an error
  18181. el.removeAttribute('src');
  18182. if (typeof el.load === 'function') {
  18183. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  18184. (function () {
  18185. try {
  18186. el.load();
  18187. } catch (e) {
  18188. // satisfy linter
  18189. }
  18190. })();
  18191. }
  18192. };
  18193. /* Native HTML5 element property wrapping ----------------------------------- */
  18194. // Wrap native boolean attributes with getters that check both property and attribute
  18195. // The list is as followed:
  18196. // muted, defaultMuted, autoplay, controls, loop, playsinline
  18197. [
  18198. /**
  18199. * Get the value of `muted` from the media element. `muted` indicates
  18200. * that the volume for the media should be set to silent. This does not actually change
  18201. * the `volume` attribute.
  18202. *
  18203. * @method Html5#muted
  18204. * @return {boolean}
  18205. * - True if the value of `volume` should be ignored and the audio set to silent.
  18206. * - False if the value of `volume` should be used.
  18207. *
  18208. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  18209. */
  18210. 'muted',
  18211. /**
  18212. * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
  18213. * whether the media should start muted or not. Only changes the default state of the
  18214. * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
  18215. * current state.
  18216. *
  18217. * @method Html5#defaultMuted
  18218. * @return {boolean}
  18219. * - The value of `defaultMuted` from the media element.
  18220. * - True indicates that the media should start muted.
  18221. * - False indicates that the media should not start muted
  18222. *
  18223. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  18224. */
  18225. 'defaultMuted',
  18226. /**
  18227. * Get the value of `autoplay` from the media element. `autoplay` indicates
  18228. * that the media should start to play as soon as the page is ready.
  18229. *
  18230. * @method Html5#autoplay
  18231. * @return {boolean}
  18232. * - The value of `autoplay` from the media element.
  18233. * - True indicates that the media should start as soon as the page loads.
  18234. * - False indicates that the media should not start as soon as the page loads.
  18235. *
  18236. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  18237. */
  18238. 'autoplay',
  18239. /**
  18240. * Get the value of `controls` from the media element. `controls` indicates
  18241. * whether the native media controls should be shown or hidden.
  18242. *
  18243. * @method Html5#controls
  18244. * @return {boolean}
  18245. * - The value of `controls` from the media element.
  18246. * - True indicates that native controls should be showing.
  18247. * - False indicates that native controls should be hidden.
  18248. *
  18249. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
  18250. */
  18251. 'controls',
  18252. /**
  18253. * Get the value of `loop` from the media element. `loop` indicates
  18254. * that the media should return to the start of the media and continue playing once
  18255. * it reaches the end.
  18256. *
  18257. * @method Html5#loop
  18258. * @return {boolean}
  18259. * - The value of `loop` from the media element.
  18260. * - True indicates that playback should seek back to start once
  18261. * the end of a media is reached.
  18262. * - False indicates that playback should not loop back to the start when the
  18263. * end of the media is reached.
  18264. *
  18265. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  18266. */
  18267. 'loop',
  18268. /**
  18269. * Get the value of `playsinline` from the media element. `playsinline` indicates
  18270. * to the browser that non-fullscreen playback is preferred when fullscreen
  18271. * playback is the native default, such as in iOS Safari.
  18272. *
  18273. * @method Html5#playsinline
  18274. * @return {boolean}
  18275. * - The value of `playsinline` from the media element.
  18276. * - True indicates that the media should play inline.
  18277. * - False indicates that the media should not play inline.
  18278. *
  18279. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  18280. */
  18281. 'playsinline'].forEach(function (prop) {
  18282. Html5.prototype[prop] = function () {
  18283. return this.el_[prop] || this.el_.hasAttribute(prop);
  18284. };
  18285. });
  18286. // Wrap native boolean attributes with setters that set both property and attribute
  18287. // The list is as followed:
  18288. // setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline
  18289. // setControls is special-cased above
  18290. [
  18291. /**
  18292. * Set the value of `muted` on the media element. `muted` indicates that the current
  18293. * audio level should be silent.
  18294. *
  18295. * @method Html5#setMuted
  18296. * @param {boolean} muted
  18297. * - True if the audio should be set to silent
  18298. * - False otherwise
  18299. *
  18300. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  18301. */
  18302. 'muted',
  18303. /**
  18304. * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
  18305. * audio level should be silent, but will only effect the muted level on initial playback..
  18306. *
  18307. * @method Html5.prototype.setDefaultMuted
  18308. * @param {boolean} defaultMuted
  18309. * - True if the audio should be set to silent
  18310. * - False otherwise
  18311. *
  18312. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  18313. */
  18314. 'defaultMuted',
  18315. /**
  18316. * Set the value of `autoplay` on the media element. `autoplay` indicates
  18317. * that the media should start to play as soon as the page is ready.
  18318. *
  18319. * @method Html5#setAutoplay
  18320. * @param {boolean} autoplay
  18321. * - True indicates that the media should start as soon as the page loads.
  18322. * - False indicates that the media should not start as soon as the page loads.
  18323. *
  18324. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  18325. */
  18326. 'autoplay',
  18327. /**
  18328. * Set the value of `loop` on the media element. `loop` indicates
  18329. * that the media should return to the start of the media and continue playing once
  18330. * it reaches the end.
  18331. *
  18332. * @method Html5#setLoop
  18333. * @param {boolean} loop
  18334. * - True indicates that playback should seek back to start once
  18335. * the end of a media is reached.
  18336. * - False indicates that playback should not loop back to the start when the
  18337. * end of the media is reached.
  18338. *
  18339. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  18340. */
  18341. 'loop',
  18342. /**
  18343. * Set the value of `playsinline` from the media element. `playsinline` indicates
  18344. * to the browser that non-fullscreen playback is preferred when fullscreen
  18345. * playback is the native default, such as in iOS Safari.
  18346. *
  18347. * @method Html5#setPlaysinline
  18348. * @param {boolean} playsinline
  18349. * - True indicates that the media should play inline.
  18350. * - False indicates that the media should not play inline.
  18351. *
  18352. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  18353. */
  18354. 'playsinline'].forEach(function (prop) {
  18355. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  18356. this.el_[prop] = v;
  18357. if (v) {
  18358. this.el_.setAttribute(prop, prop);
  18359. } else {
  18360. this.el_.removeAttribute(prop);
  18361. }
  18362. };
  18363. });
  18364. // Wrap native properties with a getter
  18365. // The list is as followed
  18366. // paused, currentTime, buffered, volume, poster, preload, error, seeking
  18367. // seekable, ended, playbackRate, defaultPlaybackRate, disablePictureInPicture
  18368. // played, networkState, readyState, videoWidth, videoHeight, crossOrigin
  18369. [
  18370. /**
  18371. * Get the value of `paused` from the media element. `paused` indicates whether the media element
  18372. * is currently paused or not.
  18373. *
  18374. * @method Html5#paused
  18375. * @return {boolean}
  18376. * The value of `paused` from the media element.
  18377. *
  18378. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
  18379. */
  18380. 'paused',
  18381. /**
  18382. * Get the value of `currentTime` from the media element. `currentTime` indicates
  18383. * the current second that the media is at in playback.
  18384. *
  18385. * @method Html5#currentTime
  18386. * @return {number}
  18387. * The value of `currentTime` from the media element.
  18388. *
  18389. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
  18390. */
  18391. 'currentTime',
  18392. /**
  18393. * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
  18394. * object that represents the parts of the media that are already downloaded and
  18395. * available for playback.
  18396. *
  18397. * @method Html5#buffered
  18398. * @return {TimeRange}
  18399. * The value of `buffered` from the media element.
  18400. *
  18401. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
  18402. */
  18403. 'buffered',
  18404. /**
  18405. * Get the value of `volume` from the media element. `volume` indicates
  18406. * the current playback volume of audio for a media. `volume` will be a value from 0
  18407. * (silent) to 1 (loudest and default).
  18408. *
  18409. * @method Html5#volume
  18410. * @return {number}
  18411. * The value of `volume` from the media element. Value will be between 0-1.
  18412. *
  18413. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  18414. */
  18415. 'volume',
  18416. /**
  18417. * Get the value of `poster` from the media element. `poster` indicates
  18418. * that the url of an image file that can/will be shown when no media data is available.
  18419. *
  18420. * @method Html5#poster
  18421. * @return {string}
  18422. * The value of `poster` from the media element. Value will be a url to an
  18423. * image.
  18424. *
  18425. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
  18426. */
  18427. 'poster',
  18428. /**
  18429. * Get the value of `preload` from the media element. `preload` indicates
  18430. * what should download before the media is interacted with. It can have the following
  18431. * values:
  18432. * - none: nothing should be downloaded
  18433. * - metadata: poster and the first few frames of the media may be downloaded to get
  18434. * media dimensions and other metadata
  18435. * - auto: allow the media and metadata for the media to be downloaded before
  18436. * interaction
  18437. *
  18438. * @method Html5#preload
  18439. * @return {string}
  18440. * The value of `preload` from the media element. Will be 'none', 'metadata',
  18441. * or 'auto'.
  18442. *
  18443. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  18444. */
  18445. 'preload',
  18446. /**
  18447. * Get the value of the `error` from the media element. `error` indicates any
  18448. * MediaError that may have occurred during playback. If error returns null there is no
  18449. * current error.
  18450. *
  18451. * @method Html5#error
  18452. * @return {MediaError|null}
  18453. * The value of `error` from the media element. Will be `MediaError` if there
  18454. * is a current error and null otherwise.
  18455. *
  18456. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
  18457. */
  18458. 'error',
  18459. /**
  18460. * Get the value of `seeking` from the media element. `seeking` indicates whether the
  18461. * media is currently seeking to a new position or not.
  18462. *
  18463. * @method Html5#seeking
  18464. * @return {boolean}
  18465. * - The value of `seeking` from the media element.
  18466. * - True indicates that the media is currently seeking to a new position.
  18467. * - False indicates that the media is not seeking to a new position at this time.
  18468. *
  18469. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
  18470. */
  18471. 'seeking',
  18472. /**
  18473. * Get the value of `seekable` from the media element. `seekable` returns a
  18474. * `TimeRange` object indicating ranges of time that can currently be `seeked` to.
  18475. *
  18476. * @method Html5#seekable
  18477. * @return {TimeRange}
  18478. * The value of `seekable` from the media element. A `TimeRange` object
  18479. * indicating the current ranges of time that can be seeked to.
  18480. *
  18481. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
  18482. */
  18483. 'seekable',
  18484. /**
  18485. * Get the value of `ended` from the media element. `ended` indicates whether
  18486. * the media has reached the end or not.
  18487. *
  18488. * @method Html5#ended
  18489. * @return {boolean}
  18490. * - The value of `ended` from the media element.
  18491. * - True indicates that the media has ended.
  18492. * - False indicates that the media has not ended.
  18493. *
  18494. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
  18495. */
  18496. 'ended',
  18497. /**
  18498. * Get the value of `playbackRate` from the media element. `playbackRate` indicates
  18499. * the rate at which the media is currently playing back. Examples:
  18500. * - if playbackRate is set to 2, media will play twice as fast.
  18501. * - if playbackRate is set to 0.5, media will play half as fast.
  18502. *
  18503. * @method Html5#playbackRate
  18504. * @return {number}
  18505. * The value of `playbackRate` from the media element. A number indicating
  18506. * the current playback speed of the media, where 1 is normal speed.
  18507. *
  18508. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18509. */
  18510. 'playbackRate',
  18511. /**
  18512. * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
  18513. * the rate at which the media is currently playing back. This value will not indicate the current
  18514. * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
  18515. *
  18516. * Examples:
  18517. * - if defaultPlaybackRate is set to 2, media will play twice as fast.
  18518. * - if defaultPlaybackRate is set to 0.5, media will play half as fast.
  18519. *
  18520. * @method Html5.prototype.defaultPlaybackRate
  18521. * @return {number}
  18522. * The value of `defaultPlaybackRate` from the media element. A number indicating
  18523. * the current playback speed of the media, where 1 is normal speed.
  18524. *
  18525. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18526. */
  18527. 'defaultPlaybackRate',
  18528. /**
  18529. * Get the value of 'disablePictureInPicture' from the video element.
  18530. *
  18531. * @method Html5#disablePictureInPicture
  18532. * @return {boolean} value
  18533. * - The value of `disablePictureInPicture` from the video element.
  18534. * - True indicates that the video can't be played in Picture-In-Picture mode
  18535. * - False indicates that the video can be played in Picture-In-Picture mode
  18536. *
  18537. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  18538. */
  18539. 'disablePictureInPicture',
  18540. /**
  18541. * Get the value of `played` from the media element. `played` returns a `TimeRange`
  18542. * object representing points in the media timeline that have been played.
  18543. *
  18544. * @method Html5#played
  18545. * @return {TimeRange}
  18546. * The value of `played` from the media element. A `TimeRange` object indicating
  18547. * the ranges of time that have been played.
  18548. *
  18549. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
  18550. */
  18551. 'played',
  18552. /**
  18553. * Get the value of `networkState` from the media element. `networkState` indicates
  18554. * the current network state. It returns an enumeration from the following list:
  18555. * - 0: NETWORK_EMPTY
  18556. * - 1: NETWORK_IDLE
  18557. * - 2: NETWORK_LOADING
  18558. * - 3: NETWORK_NO_SOURCE
  18559. *
  18560. * @method Html5#networkState
  18561. * @return {number}
  18562. * The value of `networkState` from the media element. This will be a number
  18563. * from the list in the description.
  18564. *
  18565. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
  18566. */
  18567. 'networkState',
  18568. /**
  18569. * Get the value of `readyState` from the media element. `readyState` indicates
  18570. * the current state of the media element. It returns an enumeration from the
  18571. * following list:
  18572. * - 0: HAVE_NOTHING
  18573. * - 1: HAVE_METADATA
  18574. * - 2: HAVE_CURRENT_DATA
  18575. * - 3: HAVE_FUTURE_DATA
  18576. * - 4: HAVE_ENOUGH_DATA
  18577. *
  18578. * @method Html5#readyState
  18579. * @return {number}
  18580. * The value of `readyState` from the media element. This will be a number
  18581. * from the list in the description.
  18582. *
  18583. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
  18584. */
  18585. 'readyState',
  18586. /**
  18587. * Get the value of `videoWidth` from the video element. `videoWidth` indicates
  18588. * the current width of the video in css pixels.
  18589. *
  18590. * @method Html5#videoWidth
  18591. * @return {number}
  18592. * The value of `videoWidth` from the video element. This will be a number
  18593. * in css pixels.
  18594. *
  18595. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  18596. */
  18597. 'videoWidth',
  18598. /**
  18599. * Get the value of `videoHeight` from the video element. `videoHeight` indicates
  18600. * the current height of the video in css pixels.
  18601. *
  18602. * @method Html5#videoHeight
  18603. * @return {number}
  18604. * The value of `videoHeight` from the video element. This will be a number
  18605. * in css pixels.
  18606. *
  18607. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  18608. */
  18609. 'videoHeight',
  18610. /**
  18611. * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates
  18612. * to the browser that should sent the cookies along with the requests for the
  18613. * different assets/playlists
  18614. *
  18615. * @method Html5#crossOrigin
  18616. * @return {string}
  18617. * - anonymous indicates that the media should not sent cookies.
  18618. * - use-credentials indicates that the media should sent cookies along the requests.
  18619. *
  18620. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  18621. */
  18622. 'crossOrigin'].forEach(function (prop) {
  18623. Html5.prototype[prop] = function () {
  18624. return this.el_[prop];
  18625. };
  18626. });
  18627. // Wrap native properties with a setter in this format:
  18628. // set + toTitleCase(name)
  18629. // The list is as follows:
  18630. // setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate,
  18631. // setDisablePictureInPicture, setCrossOrigin
  18632. [
  18633. /**
  18634. * Set the value of `volume` on the media element. `volume` indicates the current
  18635. * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
  18636. * so on.
  18637. *
  18638. * @method Html5#setVolume
  18639. * @param {number} percentAsDecimal
  18640. * The volume percent as a decimal. Valid range is from 0-1.
  18641. *
  18642. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  18643. */
  18644. 'volume',
  18645. /**
  18646. * Set the value of `src` on the media element. `src` indicates the current
  18647. * {@link Tech~SourceObject} for the media.
  18648. *
  18649. * @method Html5#setSrc
  18650. * @param {Tech~SourceObject} src
  18651. * The source object to set as the current source.
  18652. *
  18653. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
  18654. */
  18655. 'src',
  18656. /**
  18657. * Set the value of `poster` on the media element. `poster` is the url to
  18658. * an image file that can/will be shown when no media data is available.
  18659. *
  18660. * @method Html5#setPoster
  18661. * @param {string} poster
  18662. * The url to an image that should be used as the `poster` for the media
  18663. * element.
  18664. *
  18665. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
  18666. */
  18667. 'poster',
  18668. /**
  18669. * Set the value of `preload` on the media element. `preload` indicates
  18670. * what should download before the media is interacted with. It can have the following
  18671. * values:
  18672. * - none: nothing should be downloaded
  18673. * - metadata: poster and the first few frames of the media may be downloaded to get
  18674. * media dimensions and other metadata
  18675. * - auto: allow the media and metadata for the media to be downloaded before
  18676. * interaction
  18677. *
  18678. * @method Html5#setPreload
  18679. * @param {string} preload
  18680. * The value of `preload` to set on the media element. Must be 'none', 'metadata',
  18681. * or 'auto'.
  18682. *
  18683. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  18684. */
  18685. 'preload',
  18686. /**
  18687. * Set the value of `playbackRate` on the media element. `playbackRate` indicates
  18688. * the rate at which the media should play back. Examples:
  18689. * - if playbackRate is set to 2, media will play twice as fast.
  18690. * - if playbackRate is set to 0.5, media will play half as fast.
  18691. *
  18692. * @method Html5#setPlaybackRate
  18693. * @return {number}
  18694. * The value of `playbackRate` from the media element. A number indicating
  18695. * the current playback speed of the media, where 1 is normal speed.
  18696. *
  18697. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18698. */
  18699. 'playbackRate',
  18700. /**
  18701. * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
  18702. * the rate at which the media should play back upon initial startup. Changing this value
  18703. * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
  18704. *
  18705. * Example Values:
  18706. * - if playbackRate is set to 2, media will play twice as fast.
  18707. * - if playbackRate is set to 0.5, media will play half as fast.
  18708. *
  18709. * @method Html5.prototype.setDefaultPlaybackRate
  18710. * @return {number}
  18711. * The value of `defaultPlaybackRate` from the media element. A number indicating
  18712. * the current playback speed of the media, where 1 is normal speed.
  18713. *
  18714. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
  18715. */
  18716. 'defaultPlaybackRate',
  18717. /**
  18718. * Prevents the browser from suggesting a Picture-in-Picture context menu
  18719. * or to request Picture-in-Picture automatically in some cases.
  18720. *
  18721. * @method Html5#setDisablePictureInPicture
  18722. * @param {boolean} value
  18723. * The true value will disable Picture-in-Picture mode.
  18724. *
  18725. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  18726. */
  18727. 'disablePictureInPicture',
  18728. /**
  18729. * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates
  18730. * to the browser that should sent the cookies along with the requests for the
  18731. * different assets/playlists
  18732. *
  18733. * @method Html5#setCrossOrigin
  18734. * @param {string} crossOrigin
  18735. * - anonymous indicates that the media should not sent cookies.
  18736. * - use-credentials indicates that the media should sent cookies along the requests.
  18737. *
  18738. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  18739. */
  18740. 'crossOrigin'].forEach(function (prop) {
  18741. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  18742. this.el_[prop] = v;
  18743. };
  18744. });
  18745. // wrap native functions with a function
  18746. // The list is as follows:
  18747. // pause, load, play
  18748. [
  18749. /**
  18750. * A wrapper around the media elements `pause` function. This will call the `HTML5`
  18751. * media elements `pause` function.
  18752. *
  18753. * @method Html5#pause
  18754. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
  18755. */
  18756. 'pause',
  18757. /**
  18758. * A wrapper around the media elements `load` function. This will call the `HTML5`s
  18759. * media element `load` function.
  18760. *
  18761. * @method Html5#load
  18762. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
  18763. */
  18764. 'load',
  18765. /**
  18766. * A wrapper around the media elements `play` function. This will call the `HTML5`s
  18767. * media element `play` function.
  18768. *
  18769. * @method Html5#play
  18770. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
  18771. */
  18772. 'play'].forEach(function (prop) {
  18773. Html5.prototype[prop] = function () {
  18774. return this.el_[prop]();
  18775. };
  18776. });
  18777. Tech.withSourceHandlers(Html5);
  18778. /**
  18779. * Native source handler for Html5, simply passes the source to the media element.
  18780. *
  18781. * @property {Tech~SourceObject} source
  18782. * The source object
  18783. *
  18784. * @property {Html5} tech
  18785. * The instance of the HTML5 tech.
  18786. */
  18787. Html5.nativeSourceHandler = {};
  18788. /**
  18789. * Check if the media element can play the given mime type.
  18790. *
  18791. * @param {string} type
  18792. * The mimetype to check
  18793. *
  18794. * @return {string}
  18795. * 'probably', 'maybe', or '' (empty string)
  18796. */
  18797. Html5.nativeSourceHandler.canPlayType = function (type) {
  18798. // IE without MediaPlayer throws an error (#519)
  18799. try {
  18800. return Html5.TEST_VID.canPlayType(type);
  18801. } catch (e) {
  18802. return '';
  18803. }
  18804. };
  18805. /**
  18806. * Check if the media element can handle a source natively.
  18807. *
  18808. * @param {Tech~SourceObject} source
  18809. * The source object
  18810. *
  18811. * @param {Object} [options]
  18812. * Options to be passed to the tech.
  18813. *
  18814. * @return {string}
  18815. * 'probably', 'maybe', or '' (empty string).
  18816. */
  18817. Html5.nativeSourceHandler.canHandleSource = function (source, options) {
  18818. // If a type was provided we should rely on that
  18819. if (source.type) {
  18820. return Html5.nativeSourceHandler.canPlayType(source.type);
  18821. // If no type, fall back to checking 'video/[EXTENSION]'
  18822. } else if (source.src) {
  18823. const ext = getFileExtension(source.src);
  18824. return Html5.nativeSourceHandler.canPlayType(`video/${ext}`);
  18825. }
  18826. return '';
  18827. };
  18828. /**
  18829. * Pass the source to the native media element.
  18830. *
  18831. * @param {Tech~SourceObject} source
  18832. * The source object
  18833. *
  18834. * @param {Html5} tech
  18835. * The instance of the Html5 tech
  18836. *
  18837. * @param {Object} [options]
  18838. * The options to pass to the source
  18839. */
  18840. Html5.nativeSourceHandler.handleSource = function (source, tech, options) {
  18841. tech.setSrc(source.src);
  18842. };
  18843. /**
  18844. * A noop for the native dispose function, as cleanup is not needed.
  18845. */
  18846. Html5.nativeSourceHandler.dispose = function () {};
  18847. // Register the native source handler
  18848. Html5.registerSourceHandler(Html5.nativeSourceHandler);
  18849. Tech.registerTech('Html5', Html5);
  18850. /**
  18851. * @file player.js
  18852. */
  18853. // The following tech events are simply re-triggered
  18854. // on the player when they happen
  18855. const TECH_EVENTS_RETRIGGER = [
  18856. /**
  18857. * Fired while the user agent is downloading media data.
  18858. *
  18859. * @event Player#progress
  18860. * @type {Event}
  18861. */
  18862. /**
  18863. * Retrigger the `progress` event that was triggered by the {@link Tech}.
  18864. *
  18865. * @private
  18866. * @method Player#handleTechProgress_
  18867. * @fires Player#progress
  18868. * @listens Tech#progress
  18869. */
  18870. 'progress',
  18871. /**
  18872. * Fires when the loading of an audio/video is aborted.
  18873. *
  18874. * @event Player#abort
  18875. * @type {Event}
  18876. */
  18877. /**
  18878. * Retrigger the `abort` event that was triggered by the {@link Tech}.
  18879. *
  18880. * @private
  18881. * @method Player#handleTechAbort_
  18882. * @fires Player#abort
  18883. * @listens Tech#abort
  18884. */
  18885. 'abort',
  18886. /**
  18887. * Fires when the browser is intentionally not getting media data.
  18888. *
  18889. * @event Player#suspend
  18890. * @type {Event}
  18891. */
  18892. /**
  18893. * Retrigger the `suspend` event that was triggered by the {@link Tech}.
  18894. *
  18895. * @private
  18896. * @method Player#handleTechSuspend_
  18897. * @fires Player#suspend
  18898. * @listens Tech#suspend
  18899. */
  18900. 'suspend',
  18901. /**
  18902. * Fires when the current playlist is empty.
  18903. *
  18904. * @event Player#emptied
  18905. * @type {Event}
  18906. */
  18907. /**
  18908. * Retrigger the `emptied` event that was triggered by the {@link Tech}.
  18909. *
  18910. * @private
  18911. * @method Player#handleTechEmptied_
  18912. * @fires Player#emptied
  18913. * @listens Tech#emptied
  18914. */
  18915. 'emptied',
  18916. /**
  18917. * Fires when the browser is trying to get media data, but data is not available.
  18918. *
  18919. * @event Player#stalled
  18920. * @type {Event}
  18921. */
  18922. /**
  18923. * Retrigger the `stalled` event that was triggered by the {@link Tech}.
  18924. *
  18925. * @private
  18926. * @method Player#handleTechStalled_
  18927. * @fires Player#stalled
  18928. * @listens Tech#stalled
  18929. */
  18930. 'stalled',
  18931. /**
  18932. * Fires when the browser has loaded meta data for the audio/video.
  18933. *
  18934. * @event Player#loadedmetadata
  18935. * @type {Event}
  18936. */
  18937. /**
  18938. * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
  18939. *
  18940. * @private
  18941. * @method Player#handleTechLoadedmetadata_
  18942. * @fires Player#loadedmetadata
  18943. * @listens Tech#loadedmetadata
  18944. */
  18945. 'loadedmetadata',
  18946. /**
  18947. * Fires when the browser has loaded the current frame of the audio/video.
  18948. *
  18949. * @event Player#loadeddata
  18950. * @type {event}
  18951. */
  18952. /**
  18953. * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
  18954. *
  18955. * @private
  18956. * @method Player#handleTechLoaddeddata_
  18957. * @fires Player#loadeddata
  18958. * @listens Tech#loadeddata
  18959. */
  18960. 'loadeddata',
  18961. /**
  18962. * Fires when the current playback position has changed.
  18963. *
  18964. * @event Player#timeupdate
  18965. * @type {event}
  18966. */
  18967. /**
  18968. * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
  18969. *
  18970. * @private
  18971. * @method Player#handleTechTimeUpdate_
  18972. * @fires Player#timeupdate
  18973. * @listens Tech#timeupdate
  18974. */
  18975. 'timeupdate',
  18976. /**
  18977. * Fires when the video's intrinsic dimensions change
  18978. *
  18979. * @event Player#resize
  18980. * @type {event}
  18981. */
  18982. /**
  18983. * Retrigger the `resize` event that was triggered by the {@link Tech}.
  18984. *
  18985. * @private
  18986. * @method Player#handleTechResize_
  18987. * @fires Player#resize
  18988. * @listens Tech#resize
  18989. */
  18990. 'resize',
  18991. /**
  18992. * Fires when the volume has been changed
  18993. *
  18994. * @event Player#volumechange
  18995. * @type {event}
  18996. */
  18997. /**
  18998. * Retrigger the `volumechange` event that was triggered by the {@link Tech}.
  18999. *
  19000. * @private
  19001. * @method Player#handleTechVolumechange_
  19002. * @fires Player#volumechange
  19003. * @listens Tech#volumechange
  19004. */
  19005. 'volumechange',
  19006. /**
  19007. * Fires when the text track has been changed
  19008. *
  19009. * @event Player#texttrackchange
  19010. * @type {event}
  19011. */
  19012. /**
  19013. * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
  19014. *
  19015. * @private
  19016. * @method Player#handleTechTexttrackchange_
  19017. * @fires Player#texttrackchange
  19018. * @listens Tech#texttrackchange
  19019. */
  19020. 'texttrackchange'];
  19021. // events to queue when playback rate is zero
  19022. // this is a hash for the sole purpose of mapping non-camel-cased event names
  19023. // to camel-cased function names
  19024. const TECH_EVENTS_QUEUE = {
  19025. canplay: 'CanPlay',
  19026. canplaythrough: 'CanPlayThrough',
  19027. playing: 'Playing',
  19028. seeked: 'Seeked'
  19029. };
  19030. const BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
  19031. const BREAKPOINT_CLASSES = {};
  19032. // grep: vjs-layout-tiny
  19033. // grep: vjs-layout-x-small
  19034. // grep: vjs-layout-small
  19035. // grep: vjs-layout-medium
  19036. // grep: vjs-layout-large
  19037. // grep: vjs-layout-x-large
  19038. // grep: vjs-layout-huge
  19039. BREAKPOINT_ORDER.forEach(k => {
  19040. const v = k.charAt(0) === 'x' ? `x-${k.substring(1)}` : k;
  19041. BREAKPOINT_CLASSES[k] = `vjs-layout-${v}`;
  19042. });
  19043. const DEFAULT_BREAKPOINTS = {
  19044. tiny: 210,
  19045. xsmall: 320,
  19046. small: 425,
  19047. medium: 768,
  19048. large: 1440,
  19049. xlarge: 2560,
  19050. huge: Infinity
  19051. };
  19052. /**
  19053. * An instance of the `Player` class is created when any of the Video.js setup methods
  19054. * are used to initialize a video.
  19055. *
  19056. * After an instance has been created it can be accessed globally in three ways:
  19057. * 1. By calling `videojs.getPlayer('example_video_1');`
  19058. * 2. By calling `videojs('example_video_1');` (not recomended)
  19059. * 2. By using it directly via `videojs.players.example_video_1;`
  19060. *
  19061. * @extends Component
  19062. * @global
  19063. */
  19064. class Player extends Component$1 {
  19065. /**
  19066. * Create an instance of this class.
  19067. *
  19068. * @param {Element} tag
  19069. * The original video DOM element used for configuring options.
  19070. *
  19071. * @param {Object} [options]
  19072. * Object of option names and values.
  19073. *
  19074. * @param {Function} [ready]
  19075. * Ready callback function.
  19076. */
  19077. constructor(tag, options, ready) {
  19078. // Make sure tag ID exists
  19079. tag.id = tag.id || options.id || `vjs_video_${newGUID()}`;
  19080. // Set Options
  19081. // The options argument overrides options set in the video tag
  19082. // which overrides globally set options.
  19083. // This latter part coincides with the load order
  19084. // (tag must exist before Player)
  19085. options = Object.assign(Player.getTagSettings(tag), options);
  19086. // Delay the initialization of children because we need to set up
  19087. // player properties first, and can't use `this` before `super()`
  19088. options.initChildren = false;
  19089. // Same with creating the element
  19090. options.createEl = false;
  19091. // don't auto mixin the evented mixin
  19092. options.evented = false;
  19093. // we don't want the player to report touch activity on itself
  19094. // see enableTouchActivity in Component
  19095. options.reportTouchActivity = false;
  19096. // If language is not set, get the closest lang attribute
  19097. if (!options.language) {
  19098. const closest = tag.closest('[lang]');
  19099. if (closest) {
  19100. options.language = closest.getAttribute('lang');
  19101. }
  19102. }
  19103. // Run base component initializing with new options
  19104. super(null, options, ready);
  19105. // Create bound methods for document listeners.
  19106. this.boundDocumentFullscreenChange_ = e => this.documentFullscreenChange_(e);
  19107. this.boundFullWindowOnEscKey_ = e => this.fullWindowOnEscKey(e);
  19108. this.boundUpdateStyleEl_ = e => this.updateStyleEl_(e);
  19109. this.boundApplyInitTime_ = e => this.applyInitTime_(e);
  19110. this.boundUpdateCurrentBreakpoint_ = e => this.updateCurrentBreakpoint_(e);
  19111. this.boundHandleTechClick_ = e => this.handleTechClick_(e);
  19112. this.boundHandleTechDoubleClick_ = e => this.handleTechDoubleClick_(e);
  19113. this.boundHandleTechTouchStart_ = e => this.handleTechTouchStart_(e);
  19114. this.boundHandleTechTouchMove_ = e => this.handleTechTouchMove_(e);
  19115. this.boundHandleTechTouchEnd_ = e => this.handleTechTouchEnd_(e);
  19116. this.boundHandleTechTap_ = e => this.handleTechTap_(e);
  19117. // default isFullscreen_ to false
  19118. this.isFullscreen_ = false;
  19119. // create logger
  19120. this.log = createLogger(this.id_);
  19121. // Hold our own reference to fullscreen api so it can be mocked in tests
  19122. this.fsApi_ = FullscreenApi;
  19123. // Tracks when a tech changes the poster
  19124. this.isPosterFromTech_ = false;
  19125. // Holds callback info that gets queued when playback rate is zero
  19126. // and a seek is happening
  19127. this.queuedCallbacks_ = [];
  19128. // Turn off API access because we're loading a new tech that might load asynchronously
  19129. this.isReady_ = false;
  19130. // Init state hasStarted_
  19131. this.hasStarted_ = false;
  19132. // Init state userActive_
  19133. this.userActive_ = false;
  19134. // Init debugEnabled_
  19135. this.debugEnabled_ = false;
  19136. // Init state audioOnlyMode_
  19137. this.audioOnlyMode_ = false;
  19138. // Init state audioPosterMode_
  19139. this.audioPosterMode_ = false;
  19140. // Init state audioOnlyCache_
  19141. this.audioOnlyCache_ = {
  19142. playerHeight: null,
  19143. hiddenChildren: []
  19144. };
  19145. // if the global option object was accidentally blown away by
  19146. // someone, bail early with an informative error
  19147. if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) {
  19148. throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
  19149. }
  19150. // Store the original tag used to set options
  19151. this.tag = tag;
  19152. // Store the tag attributes used to restore html5 element
  19153. this.tagAttributes = tag && getAttributes(tag);
  19154. // Update current language
  19155. this.language(this.options_.language);
  19156. // Update Supported Languages
  19157. if (options.languages) {
  19158. // Normalise player option languages to lowercase
  19159. const languagesToLower = {};
  19160. Object.getOwnPropertyNames(options.languages).forEach(function (name) {
  19161. languagesToLower[name.toLowerCase()] = options.languages[name];
  19162. });
  19163. this.languages_ = languagesToLower;
  19164. } else {
  19165. this.languages_ = Player.prototype.options_.languages;
  19166. }
  19167. this.resetCache_();
  19168. // Set poster
  19169. this.poster_ = options.poster || '';
  19170. // Set controls
  19171. this.controls_ = !!options.controls;
  19172. // Original tag settings stored in options
  19173. // now remove immediately so native controls don't flash.
  19174. // May be turned back on by HTML5 tech if nativeControlsForTouch is true
  19175. tag.controls = false;
  19176. tag.removeAttribute('controls');
  19177. this.changingSrc_ = false;
  19178. this.playCallbacks_ = [];
  19179. this.playTerminatedQueue_ = [];
  19180. // the attribute overrides the option
  19181. if (tag.hasAttribute('autoplay')) {
  19182. this.autoplay(true);
  19183. } else {
  19184. // otherwise use the setter to validate and
  19185. // set the correct value.
  19186. this.autoplay(this.options_.autoplay);
  19187. }
  19188. // check plugins
  19189. if (options.plugins) {
  19190. Object.keys(options.plugins).forEach(name => {
  19191. if (typeof this[name] !== 'function') {
  19192. throw new Error(`plugin "${name}" does not exist`);
  19193. }
  19194. });
  19195. }
  19196. /*
  19197. * Store the internal state of scrubbing
  19198. *
  19199. * @private
  19200. * @return {Boolean} True if the user is scrubbing
  19201. */
  19202. this.scrubbing_ = false;
  19203. this.el_ = this.createEl();
  19204. // Make this an evented object and use `el_` as its event bus.
  19205. evented(this, {
  19206. eventBusKey: 'el_'
  19207. });
  19208. // listen to document and player fullscreenchange handlers so we receive those events
  19209. // before a user can receive them so we can update isFullscreen appropriately.
  19210. // make sure that we listen to fullscreenchange events before everything else to make sure that
  19211. // our isFullscreen method is updated properly for internal components as well as external.
  19212. if (this.fsApi_.requestFullscreen) {
  19213. on(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  19214. this.on(this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  19215. }
  19216. if (this.fluid_) {
  19217. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  19218. }
  19219. // We also want to pass the original player options to each component and plugin
  19220. // as well so they don't need to reach back into the player for options later.
  19221. // We also need to do another copy of this.options_ so we don't end up with
  19222. // an infinite loop.
  19223. const playerOptionsCopy = merge$2(this.options_);
  19224. // Load plugins
  19225. if (options.plugins) {
  19226. Object.keys(options.plugins).forEach(name => {
  19227. this[name](options.plugins[name]);
  19228. });
  19229. }
  19230. // Enable debug mode to fire debugon event for all plugins.
  19231. if (options.debug) {
  19232. this.debug(true);
  19233. }
  19234. this.options_.playerOptions = playerOptionsCopy;
  19235. this.middleware_ = [];
  19236. this.playbackRates(options.playbackRates);
  19237. this.initChildren();
  19238. // Set isAudio based on whether or not an audio tag was used
  19239. this.isAudio(tag.nodeName.toLowerCase() === 'audio');
  19240. // Update controls className. Can't do this when the controls are initially
  19241. // set because the element doesn't exist yet.
  19242. if (this.controls()) {
  19243. this.addClass('vjs-controls-enabled');
  19244. } else {
  19245. this.addClass('vjs-controls-disabled');
  19246. }
  19247. // Set ARIA label and region role depending on player type
  19248. this.el_.setAttribute('role', 'region');
  19249. if (this.isAudio()) {
  19250. this.el_.setAttribute('aria-label', this.localize('Audio Player'));
  19251. } else {
  19252. this.el_.setAttribute('aria-label', this.localize('Video Player'));
  19253. }
  19254. if (this.isAudio()) {
  19255. this.addClass('vjs-audio');
  19256. }
  19257. // TODO: Make this smarter. Toggle user state between touching/mousing
  19258. // using events, since devices can have both touch and mouse events.
  19259. // TODO: Make this check be performed again when the window switches between monitors
  19260. // (See https://github.com/videojs/video.js/issues/5683)
  19261. if (TOUCH_ENABLED) {
  19262. this.addClass('vjs-touch-enabled');
  19263. }
  19264. // iOS Safari has broken hover handling
  19265. if (!IS_IOS) {
  19266. this.addClass('vjs-workinghover');
  19267. }
  19268. // Make player easily findable by ID
  19269. Player.players[this.id_] = this;
  19270. // Add a major version class to aid css in plugins
  19271. const majorVersion = version$5.split('.')[0];
  19272. this.addClass(`vjs-v${majorVersion}`);
  19273. // When the player is first initialized, trigger activity so components
  19274. // like the control bar show themselves if needed
  19275. this.userActive(true);
  19276. this.reportUserActivity();
  19277. this.one('play', e => this.listenForUserActivity_(e));
  19278. this.on('keydown', e => this.handleKeyDown(e));
  19279. this.on('languagechange', e => this.handleLanguagechange(e));
  19280. this.breakpoints(this.options_.breakpoints);
  19281. this.responsive(this.options_.responsive);
  19282. // Calling both the audio mode methods after the player is fully
  19283. // setup to be able to listen to the events triggered by them
  19284. this.on('ready', () => {
  19285. // Calling the audioPosterMode method first so that
  19286. // the audioOnlyMode can take precedence when both options are set to true
  19287. this.audioPosterMode(this.options_.audioPosterMode);
  19288. this.audioOnlyMode(this.options_.audioOnlyMode);
  19289. });
  19290. }
  19291. /**
  19292. * Destroys the video player and does any necessary cleanup.
  19293. *
  19294. * This is especially helpful if you are dynamically adding and removing videos
  19295. * to/from the DOM.
  19296. *
  19297. * @fires Player#dispose
  19298. */
  19299. dispose() {
  19300. /**
  19301. * Called when the player is being disposed of.
  19302. *
  19303. * @event Player#dispose
  19304. * @type {Event}
  19305. */
  19306. this.trigger('dispose');
  19307. // prevent dispose from being called twice
  19308. this.off('dispose');
  19309. // Make sure all player-specific document listeners are unbound. This is
  19310. off(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  19311. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  19312. if (this.styleEl_ && this.styleEl_.parentNode) {
  19313. this.styleEl_.parentNode.removeChild(this.styleEl_);
  19314. this.styleEl_ = null;
  19315. }
  19316. // Kill reference to this player
  19317. Player.players[this.id_] = null;
  19318. if (this.tag && this.tag.player) {
  19319. this.tag.player = null;
  19320. }
  19321. if (this.el_ && this.el_.player) {
  19322. this.el_.player = null;
  19323. }
  19324. if (this.tech_) {
  19325. this.tech_.dispose();
  19326. this.isPosterFromTech_ = false;
  19327. this.poster_ = '';
  19328. }
  19329. if (this.playerElIngest_) {
  19330. this.playerElIngest_ = null;
  19331. }
  19332. if (this.tag) {
  19333. this.tag = null;
  19334. }
  19335. clearCacheForPlayer(this);
  19336. // remove all event handlers for track lists
  19337. // all tracks and track listeners are removed on
  19338. // tech dispose
  19339. ALL.names.forEach(name => {
  19340. const props = ALL[name];
  19341. const list = this[props.getterName]();
  19342. // if it is not a native list
  19343. // we have to manually remove event listeners
  19344. if (list && list.off) {
  19345. list.off();
  19346. }
  19347. });
  19348. // the actual .el_ is removed here, or replaced if
  19349. super.dispose({
  19350. restoreEl: this.options_.restoreEl
  19351. });
  19352. }
  19353. /**
  19354. * Create the `Player`'s DOM element.
  19355. *
  19356. * @return {Element}
  19357. * The DOM element that gets created.
  19358. */
  19359. createEl() {
  19360. let tag = this.tag;
  19361. let el;
  19362. let playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
  19363. const divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
  19364. if (playerElIngest) {
  19365. el = this.el_ = tag.parentNode;
  19366. } else if (!divEmbed) {
  19367. el = this.el_ = super.createEl('div');
  19368. }
  19369. // Copy over all the attributes from the tag, including ID and class
  19370. // ID will now reference player box, not the video tag
  19371. const attrs = getAttributes(tag);
  19372. if (divEmbed) {
  19373. el = this.el_ = tag;
  19374. tag = this.tag = document.createElement('video');
  19375. while (el.children.length) {
  19376. tag.appendChild(el.firstChild);
  19377. }
  19378. if (!hasClass(el, 'video-js')) {
  19379. addClass(el, 'video-js');
  19380. }
  19381. el.appendChild(tag);
  19382. playerElIngest = this.playerElIngest_ = el;
  19383. // move properties over from our custom `video-js` element
  19384. // to our new `video` element. This will move things like
  19385. // `src` or `controls` that were set via js before the player
  19386. // was initialized.
  19387. Object.keys(el).forEach(k => {
  19388. try {
  19389. tag[k] = el[k];
  19390. } catch (e) {
  19391. // we got a a property like outerHTML which we can't actually copy, ignore it
  19392. }
  19393. });
  19394. }
  19395. // set tabindex to -1 to remove the video element from the focus order
  19396. tag.setAttribute('tabindex', '-1');
  19397. attrs.tabindex = '-1';
  19398. // Workaround for #4583 on Chrome (on Windows) with JAWS.
  19399. // See https://github.com/FreedomScientific/VFO-standards-support/issues/78
  19400. // Note that we can't detect if JAWS is being used, but this ARIA attribute
  19401. // doesn't change behavior of Chrome if JAWS is not being used
  19402. if (IS_CHROME && IS_WINDOWS) {
  19403. tag.setAttribute('role', 'application');
  19404. attrs.role = 'application';
  19405. }
  19406. // Remove width/height attrs from tag so CSS can make it 100% width/height
  19407. tag.removeAttribute('width');
  19408. tag.removeAttribute('height');
  19409. if ('width' in attrs) {
  19410. delete attrs.width;
  19411. }
  19412. if ('height' in attrs) {
  19413. delete attrs.height;
  19414. }
  19415. Object.getOwnPropertyNames(attrs).forEach(function (attr) {
  19416. // don't copy over the class attribute to the player element when we're in a div embed
  19417. // the class is already set up properly in the divEmbed case
  19418. // and we want to make sure that the `video-js` class doesn't get lost
  19419. if (!(divEmbed && attr === 'class')) {
  19420. el.setAttribute(attr, attrs[attr]);
  19421. }
  19422. if (divEmbed) {
  19423. tag.setAttribute(attr, attrs[attr]);
  19424. }
  19425. });
  19426. // Update tag id/class for use as HTML5 playback tech
  19427. // Might think we should do this after embedding in container so .vjs-tech class
  19428. // doesn't flash 100% width/height, but class only applies with .video-js parent
  19429. tag.playerId = tag.id;
  19430. tag.id += '_html5_api';
  19431. tag.className = 'vjs-tech';
  19432. // Make player findable on elements
  19433. tag.player = el.player = this;
  19434. // Default state of video is paused
  19435. this.addClass('vjs-paused');
  19436. // Add a style element in the player that we'll use to set the width/height
  19437. // of the player in a way that's still overridable by CSS, just like the
  19438. // video element
  19439. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
  19440. this.styleEl_ = createStyleElement('vjs-styles-dimensions');
  19441. const defaultsStyleEl = $('.vjs-styles-defaults');
  19442. const head = $('head');
  19443. head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
  19444. }
  19445. this.fill_ = false;
  19446. this.fluid_ = false;
  19447. // Pass in the width/height/aspectRatio options which will update the style el
  19448. this.width(this.options_.width);
  19449. this.height(this.options_.height);
  19450. this.fill(this.options_.fill);
  19451. this.fluid(this.options_.fluid);
  19452. this.aspectRatio(this.options_.aspectRatio);
  19453. // support both crossOrigin and crossorigin to reduce confusion and issues around the name
  19454. this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin);
  19455. // Hide any links within the video/audio tag,
  19456. // because IE doesn't hide them completely from screen readers.
  19457. const links = tag.getElementsByTagName('a');
  19458. for (let i = 0; i < links.length; i++) {
  19459. const linkEl = links.item(i);
  19460. addClass(linkEl, 'vjs-hidden');
  19461. linkEl.setAttribute('hidden', 'hidden');
  19462. }
  19463. // insertElFirst seems to cause the networkState to flicker from 3 to 2, so
  19464. // keep track of the original for later so we can know if the source originally failed
  19465. tag.initNetworkState_ = tag.networkState;
  19466. // Wrap video tag in div (el/box) container
  19467. if (tag.parentNode && !playerElIngest) {
  19468. tag.parentNode.insertBefore(el, tag);
  19469. }
  19470. // insert the tag as the first child of the player element
  19471. // then manually add it to the children array so that this.addChild
  19472. // will work properly for other components
  19473. //
  19474. // Breaks iPhone, fixed in HTML5 setup.
  19475. prependTo(tag, el);
  19476. this.children_.unshift(tag);
  19477. // Set lang attr on player to ensure CSS :lang() in consistent with player
  19478. // if it's been set to something different to the doc
  19479. this.el_.setAttribute('lang', this.language_);
  19480. this.el_.setAttribute('translate', 'no');
  19481. this.el_ = el;
  19482. return el;
  19483. }
  19484. /**
  19485. * Get or set the `Player`'s crossOrigin option. For the HTML5 player, this
  19486. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  19487. * behavior.
  19488. *
  19489. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  19490. *
  19491. * @param {string|null} [value]
  19492. * The value to set the `Player`'s crossOrigin to. If an argument is
  19493. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  19494. *
  19495. * @return {string|null|undefined}
  19496. * - The current crossOrigin value of the `Player` when getting.
  19497. * - undefined when setting
  19498. */
  19499. crossOrigin(value) {
  19500. // `null` can be set to unset a value
  19501. if (typeof value === 'undefined') {
  19502. return this.techGet_('crossOrigin');
  19503. }
  19504. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  19505. log$1.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  19506. return;
  19507. }
  19508. this.techCall_('setCrossOrigin', value);
  19509. if (this.posterImage) {
  19510. this.posterImage.crossOrigin(value);
  19511. }
  19512. return;
  19513. }
  19514. /**
  19515. * A getter/setter for the `Player`'s width. Returns the player's configured value.
  19516. * To get the current width use `currentWidth()`.
  19517. *
  19518. * @param {number} [value]
  19519. * The value to set the `Player`'s width to.
  19520. *
  19521. * @return {number}
  19522. * The current width of the `Player` when getting.
  19523. */
  19524. width(value) {
  19525. return this.dimension('width', value);
  19526. }
  19527. /**
  19528. * A getter/setter for the `Player`'s height. Returns the player's configured value.
  19529. * To get the current height use `currentheight()`.
  19530. *
  19531. * @param {number} [value]
  19532. * The value to set the `Player`'s height to.
  19533. *
  19534. * @return {number}
  19535. * The current height of the `Player` when getting.
  19536. */
  19537. height(value) {
  19538. return this.dimension('height', value);
  19539. }
  19540. /**
  19541. * A getter/setter for the `Player`'s width & height.
  19542. *
  19543. * @param {string} dimension
  19544. * This string can be:
  19545. * - 'width'
  19546. * - 'height'
  19547. *
  19548. * @param {number} [value]
  19549. * Value for dimension specified in the first argument.
  19550. *
  19551. * @return {number}
  19552. * The dimension arguments value when getting (width/height).
  19553. */
  19554. dimension(dimension, value) {
  19555. const privDimension = dimension + '_';
  19556. if (value === undefined) {
  19557. return this[privDimension] || 0;
  19558. }
  19559. if (value === '' || value === 'auto') {
  19560. // If an empty string is given, reset the dimension to be automatic
  19561. this[privDimension] = undefined;
  19562. this.updateStyleEl_();
  19563. return;
  19564. }
  19565. const parsedVal = parseFloat(value);
  19566. if (isNaN(parsedVal)) {
  19567. log$1.error(`Improper value "${value}" supplied for for ${dimension}`);
  19568. return;
  19569. }
  19570. this[privDimension] = parsedVal;
  19571. this.updateStyleEl_();
  19572. }
  19573. /**
  19574. * A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
  19575. *
  19576. * Turning this on will turn off fill mode.
  19577. *
  19578. * @param {boolean} [bool]
  19579. * - A value of true adds the class.
  19580. * - A value of false removes the class.
  19581. * - No value will be a getter.
  19582. *
  19583. * @return {boolean|undefined}
  19584. * - The value of fluid when getting.
  19585. * - `undefined` when setting.
  19586. */
  19587. fluid(bool) {
  19588. if (bool === undefined) {
  19589. return !!this.fluid_;
  19590. }
  19591. this.fluid_ = !!bool;
  19592. if (isEvented(this)) {
  19593. this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  19594. }
  19595. if (bool) {
  19596. this.addClass('vjs-fluid');
  19597. this.fill(false);
  19598. addEventedCallback(this, () => {
  19599. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  19600. });
  19601. } else {
  19602. this.removeClass('vjs-fluid');
  19603. }
  19604. this.updateStyleEl_();
  19605. }
  19606. /**
  19607. * A getter/setter/toggler for the vjs-fill `className` on the `Player`.
  19608. *
  19609. * Turning this on will turn off fluid mode.
  19610. *
  19611. * @param {boolean} [bool]
  19612. * - A value of true adds the class.
  19613. * - A value of false removes the class.
  19614. * - No value will be a getter.
  19615. *
  19616. * @return {boolean|undefined}
  19617. * - The value of fluid when getting.
  19618. * - `undefined` when setting.
  19619. */
  19620. fill(bool) {
  19621. if (bool === undefined) {
  19622. return !!this.fill_;
  19623. }
  19624. this.fill_ = !!bool;
  19625. if (bool) {
  19626. this.addClass('vjs-fill');
  19627. this.fluid(false);
  19628. } else {
  19629. this.removeClass('vjs-fill');
  19630. }
  19631. }
  19632. /**
  19633. * Get/Set the aspect ratio
  19634. *
  19635. * @param {string} [ratio]
  19636. * Aspect ratio for player
  19637. *
  19638. * @return {string|undefined}
  19639. * returns the current aspect ratio when getting
  19640. */
  19641. /**
  19642. * A getter/setter for the `Player`'s aspect ratio.
  19643. *
  19644. * @param {string} [ratio]
  19645. * The value to set the `Player`'s aspect ratio to.
  19646. *
  19647. * @return {string|undefined}
  19648. * - The current aspect ratio of the `Player` when getting.
  19649. * - undefined when setting
  19650. */
  19651. aspectRatio(ratio) {
  19652. if (ratio === undefined) {
  19653. return this.aspectRatio_;
  19654. }
  19655. // Check for width:height format
  19656. if (!/^\d+\:\d+$/.test(ratio)) {
  19657. throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
  19658. }
  19659. this.aspectRatio_ = ratio;
  19660. // We're assuming if you set an aspect ratio you want fluid mode,
  19661. // because in fixed mode you could calculate width and height yourself.
  19662. this.fluid(true);
  19663. this.updateStyleEl_();
  19664. }
  19665. /**
  19666. * Update styles of the `Player` element (height, width and aspect ratio).
  19667. *
  19668. * @private
  19669. * @listens Tech#loadedmetadata
  19670. */
  19671. updateStyleEl_() {
  19672. if (window.VIDEOJS_NO_DYNAMIC_STYLE === true) {
  19673. const width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
  19674. const height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
  19675. const techEl = this.tech_ && this.tech_.el();
  19676. if (techEl) {
  19677. if (width >= 0) {
  19678. techEl.width = width;
  19679. }
  19680. if (height >= 0) {
  19681. techEl.height = height;
  19682. }
  19683. }
  19684. return;
  19685. }
  19686. let width;
  19687. let height;
  19688. let aspectRatio;
  19689. let idClass;
  19690. // The aspect ratio is either used directly or to calculate width and height.
  19691. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
  19692. // Use any aspectRatio that's been specifically set
  19693. aspectRatio = this.aspectRatio_;
  19694. } else if (this.videoWidth() > 0) {
  19695. // Otherwise try to get the aspect ratio from the video metadata
  19696. aspectRatio = this.videoWidth() + ':' + this.videoHeight();
  19697. } else {
  19698. // Or use a default. The video element's is 2:1, but 16:9 is more common.
  19699. aspectRatio = '16:9';
  19700. }
  19701. // Get the ratio as a decimal we can use to calculate dimensions
  19702. const ratioParts = aspectRatio.split(':');
  19703. const ratioMultiplier = ratioParts[1] / ratioParts[0];
  19704. if (this.width_ !== undefined) {
  19705. // Use any width that's been specifically set
  19706. width = this.width_;
  19707. } else if (this.height_ !== undefined) {
  19708. // Or calculate the width from the aspect ratio if a height has been set
  19709. width = this.height_ / ratioMultiplier;
  19710. } else {
  19711. // Or use the video's metadata, or use the video el's default of 300
  19712. width = this.videoWidth() || 300;
  19713. }
  19714. if (this.height_ !== undefined) {
  19715. // Use any height that's been specifically set
  19716. height = this.height_;
  19717. } else {
  19718. // Otherwise calculate the height from the ratio and the width
  19719. height = width * ratioMultiplier;
  19720. }
  19721. // Ensure the CSS class is valid by starting with an alpha character
  19722. if (/^[^a-zA-Z]/.test(this.id())) {
  19723. idClass = 'dimensions-' + this.id();
  19724. } else {
  19725. idClass = this.id() + '-dimensions';
  19726. }
  19727. // Ensure the right class is still on the player for the style element
  19728. this.addClass(idClass);
  19729. setTextContent(this.styleEl_, `
  19730. .${idClass} {
  19731. width: ${width}px;
  19732. height: ${height}px;
  19733. }
  19734. .${idClass}.vjs-fluid:not(.vjs-audio-only-mode) {
  19735. padding-top: ${ratioMultiplier * 100}%;
  19736. }
  19737. `);
  19738. }
  19739. /**
  19740. * Load/Create an instance of playback {@link Tech} including element
  19741. * and API methods. Then append the `Tech` element in `Player` as a child.
  19742. *
  19743. * @param {string} techName
  19744. * name of the playback technology
  19745. *
  19746. * @param {string} source
  19747. * video source
  19748. *
  19749. * @private
  19750. */
  19751. loadTech_(techName, source) {
  19752. // Pause and remove current playback technology
  19753. if (this.tech_) {
  19754. this.unloadTech_();
  19755. }
  19756. const titleTechName = toTitleCase$1(techName);
  19757. const camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1);
  19758. // get rid of the HTML5 video tag as soon as we are using another tech
  19759. if (titleTechName !== 'Html5' && this.tag) {
  19760. Tech.getTech('Html5').disposeMediaElement(this.tag);
  19761. this.tag.player = null;
  19762. this.tag = null;
  19763. }
  19764. this.techName_ = titleTechName;
  19765. // Turn off API access because we're loading a new tech that might load asynchronously
  19766. this.isReady_ = false;
  19767. let autoplay = this.autoplay();
  19768. // if autoplay is a string (or `true` with normalizeAutoplay: true) we pass false to the tech
  19769. // because the player is going to handle autoplay on `loadstart`
  19770. if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeAutoplay) {
  19771. autoplay = false;
  19772. }
  19773. // Grab tech-specific options from player options and add source and parent element to use.
  19774. const techOptions = {
  19775. source,
  19776. autoplay,
  19777. 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
  19778. 'playerId': this.id(),
  19779. 'techId': `${this.id()}_${camelTechName}_api`,
  19780. 'playsinline': this.options_.playsinline,
  19781. 'preload': this.options_.preload,
  19782. 'loop': this.options_.loop,
  19783. 'disablePictureInPicture': this.options_.disablePictureInPicture,
  19784. 'muted': this.options_.muted,
  19785. 'poster': this.poster(),
  19786. 'language': this.language(),
  19787. 'playerElIngest': this.playerElIngest_ || false,
  19788. 'vtt.js': this.options_['vtt.js'],
  19789. 'canOverridePoster': !!this.options_.techCanOverridePoster,
  19790. 'enableSourceset': this.options_.enableSourceset
  19791. };
  19792. ALL.names.forEach(name => {
  19793. const props = ALL[name];
  19794. techOptions[props.getterName] = this[props.privateName];
  19795. });
  19796. Object.assign(techOptions, this.options_[titleTechName]);
  19797. Object.assign(techOptions, this.options_[camelTechName]);
  19798. Object.assign(techOptions, this.options_[techName.toLowerCase()]);
  19799. if (this.tag) {
  19800. techOptions.tag = this.tag;
  19801. }
  19802. if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
  19803. techOptions.startTime = this.cache_.currentTime;
  19804. }
  19805. // Initialize tech instance
  19806. const TechClass = Tech.getTech(techName);
  19807. if (!TechClass) {
  19808. throw new Error(`No Tech named '${titleTechName}' exists! '${titleTechName}' should be registered using videojs.registerTech()'`);
  19809. }
  19810. this.tech_ = new TechClass(techOptions);
  19811. // player.triggerReady is always async, so don't need this to be async
  19812. this.tech_.ready(bind_(this, this.handleTechReady_), true);
  19813. textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
  19814. // Listen to all HTML5-defined events and trigger them on the player
  19815. TECH_EVENTS_RETRIGGER.forEach(event => {
  19816. this.on(this.tech_, event, e => this[`handleTech${toTitleCase$1(event)}_`](e));
  19817. });
  19818. Object.keys(TECH_EVENTS_QUEUE).forEach(event => {
  19819. this.on(this.tech_, event, eventObj => {
  19820. if (this.tech_.playbackRate() === 0 && this.tech_.seeking()) {
  19821. this.queuedCallbacks_.push({
  19822. callback: this[`handleTech${TECH_EVENTS_QUEUE[event]}_`].bind(this),
  19823. event: eventObj
  19824. });
  19825. return;
  19826. }
  19827. this[`handleTech${TECH_EVENTS_QUEUE[event]}_`](eventObj);
  19828. });
  19829. });
  19830. this.on(this.tech_, 'loadstart', e => this.handleTechLoadStart_(e));
  19831. this.on(this.tech_, 'sourceset', e => this.handleTechSourceset_(e));
  19832. this.on(this.tech_, 'waiting', e => this.handleTechWaiting_(e));
  19833. this.on(this.tech_, 'ended', e => this.handleTechEnded_(e));
  19834. this.on(this.tech_, 'seeking', e => this.handleTechSeeking_(e));
  19835. this.on(this.tech_, 'play', e => this.handleTechPlay_(e));
  19836. this.on(this.tech_, 'pause', e => this.handleTechPause_(e));
  19837. this.on(this.tech_, 'durationchange', e => this.handleTechDurationChange_(e));
  19838. this.on(this.tech_, 'fullscreenchange', (e, data) => this.handleTechFullscreenChange_(e, data));
  19839. this.on(this.tech_, 'fullscreenerror', (e, err) => this.handleTechFullscreenError_(e, err));
  19840. this.on(this.tech_, 'enterpictureinpicture', e => this.handleTechEnterPictureInPicture_(e));
  19841. this.on(this.tech_, 'leavepictureinpicture', e => this.handleTechLeavePictureInPicture_(e));
  19842. this.on(this.tech_, 'error', e => this.handleTechError_(e));
  19843. this.on(this.tech_, 'posterchange', e => this.handleTechPosterChange_(e));
  19844. this.on(this.tech_, 'textdata', e => this.handleTechTextData_(e));
  19845. this.on(this.tech_, 'ratechange', e => this.handleTechRateChange_(e));
  19846. this.on(this.tech_, 'loadedmetadata', this.boundUpdateStyleEl_);
  19847. this.usingNativeControls(this.techGet_('controls'));
  19848. if (this.controls() && !this.usingNativeControls()) {
  19849. this.addTechControlsListeners_();
  19850. }
  19851. // Add the tech element in the DOM if it was not already there
  19852. // Make sure to not insert the original video element if using Html5
  19853. if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {
  19854. prependTo(this.tech_.el(), this.el());
  19855. }
  19856. // Get rid of the original video tag reference after the first tech is loaded
  19857. if (this.tag) {
  19858. this.tag.player = null;
  19859. this.tag = null;
  19860. }
  19861. }
  19862. /**
  19863. * Unload and dispose of the current playback {@link Tech}.
  19864. *
  19865. * @private
  19866. */
  19867. unloadTech_() {
  19868. // Save the current text tracks so that we can reuse the same text tracks with the next tech
  19869. ALL.names.forEach(name => {
  19870. const props = ALL[name];
  19871. this[props.privateName] = this[props.getterName]();
  19872. });
  19873. this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
  19874. this.isReady_ = false;
  19875. this.tech_.dispose();
  19876. this.tech_ = false;
  19877. if (this.isPosterFromTech_) {
  19878. this.poster_ = '';
  19879. this.trigger('posterchange');
  19880. }
  19881. this.isPosterFromTech_ = false;
  19882. }
  19883. /**
  19884. * Return a reference to the current {@link Tech}.
  19885. * It will print a warning by default about the danger of using the tech directly
  19886. * but any argument that is passed in will silence the warning.
  19887. *
  19888. * @param {*} [safety]
  19889. * Anything passed in to silence the warning
  19890. *
  19891. * @return {Tech}
  19892. * The Tech
  19893. */
  19894. tech(safety) {
  19895. if (safety === undefined) {
  19896. 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');
  19897. }
  19898. return this.tech_;
  19899. }
  19900. /**
  19901. * Set up click and touch listeners for the playback element
  19902. *
  19903. * - On desktops: a click on the video itself will toggle playback
  19904. * - On mobile devices: a click on the video toggles controls
  19905. * which is done by toggling the user state between active and
  19906. * inactive
  19907. * - A tap can signal that a user has become active or has become inactive
  19908. * e.g. a quick tap on an iPhone movie should reveal the controls. Another
  19909. * quick tap should hide them again (signaling the user is in an inactive
  19910. * viewing state)
  19911. * - In addition to this, we still want the user to be considered inactive after
  19912. * a few seconds of inactivity.
  19913. *
  19914. * > Note: the only part of iOS interaction we can't mimic with this setup
  19915. * is a touch and hold on the video element counting as activity in order to
  19916. * keep the controls showing, but that shouldn't be an issue. A touch and hold
  19917. * on any controls will still keep the user active
  19918. *
  19919. * @private
  19920. */
  19921. addTechControlsListeners_() {
  19922. // Make sure to remove all the previous listeners in case we are called multiple times.
  19923. this.removeTechControlsListeners_();
  19924. this.on(this.tech_, 'click', this.boundHandleTechClick_);
  19925. this.on(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  19926. // If the controls were hidden we don't want that to change without a tap event
  19927. // so we'll check if the controls were already showing before reporting user
  19928. // activity
  19929. this.on(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  19930. this.on(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  19931. this.on(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  19932. // The tap listener needs to come after the touchend listener because the tap
  19933. // listener cancels out any reportedUserActivity when setting userActive(false)
  19934. this.on(this.tech_, 'tap', this.boundHandleTechTap_);
  19935. }
  19936. /**
  19937. * Remove the listeners used for click and tap controls. This is needed for
  19938. * toggling to controls disabled, where a tap/touch should do nothing.
  19939. *
  19940. * @private
  19941. */
  19942. removeTechControlsListeners_() {
  19943. // We don't want to just use `this.off()` because there might be other needed
  19944. // listeners added by techs that extend this.
  19945. this.off(this.tech_, 'tap', this.boundHandleTechTap_);
  19946. this.off(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  19947. this.off(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  19948. this.off(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  19949. this.off(this.tech_, 'click', this.boundHandleTechClick_);
  19950. this.off(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  19951. }
  19952. /**
  19953. * Player waits for the tech to be ready
  19954. *
  19955. * @private
  19956. */
  19957. handleTechReady_() {
  19958. this.triggerReady();
  19959. // Keep the same volume as before
  19960. if (this.cache_.volume) {
  19961. this.techCall_('setVolume', this.cache_.volume);
  19962. }
  19963. // Look if the tech found a higher resolution poster while loading
  19964. this.handleTechPosterChange_();
  19965. // Update the duration if available
  19966. this.handleTechDurationChange_();
  19967. }
  19968. /**
  19969. * Retrigger the `loadstart` event that was triggered by the {@link Tech}.
  19970. *
  19971. * @fires Player#loadstart
  19972. * @listens Tech#loadstart
  19973. * @private
  19974. */
  19975. handleTechLoadStart_() {
  19976. // TODO: Update to use `emptied` event instead. See #1277.
  19977. this.removeClass('vjs-ended', 'vjs-seeking');
  19978. // reset the error state
  19979. this.error(null);
  19980. // Update the duration
  19981. this.handleTechDurationChange_();
  19982. if (!this.paused()) {
  19983. /**
  19984. * Fired when the user agent begins looking for media data
  19985. *
  19986. * @event Player#loadstart
  19987. * @type {Event}
  19988. */
  19989. this.trigger('loadstart');
  19990. } else {
  19991. // reset the hasStarted state
  19992. this.hasStarted(false);
  19993. this.trigger('loadstart');
  19994. }
  19995. // autoplay happens after loadstart for the browser,
  19996. // so we mimic that behavior
  19997. this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? 'play' : this.autoplay());
  19998. }
  19999. /**
  20000. * Handle autoplay string values, rather than the typical boolean
  20001. * values that should be handled by the tech. Note that this is not
  20002. * part of any specification. Valid values and what they do can be
  20003. * found on the autoplay getter at Player#autoplay()
  20004. */
  20005. manualAutoplay_(type) {
  20006. if (!this.tech_ || typeof type !== 'string') {
  20007. return;
  20008. }
  20009. // Save original muted() value, set muted to true, and attempt to play().
  20010. // On promise rejection, restore muted from saved value
  20011. const resolveMuted = () => {
  20012. const previouslyMuted = this.muted();
  20013. this.muted(true);
  20014. const restoreMuted = () => {
  20015. this.muted(previouslyMuted);
  20016. };
  20017. // restore muted on play terminatation
  20018. this.playTerminatedQueue_.push(restoreMuted);
  20019. const mutedPromise = this.play();
  20020. if (!isPromise(mutedPromise)) {
  20021. return;
  20022. }
  20023. return mutedPromise.catch(err => {
  20024. restoreMuted();
  20025. throw new Error(`Rejection at manualAutoplay. Restoring muted value. ${err ? err : ''}`);
  20026. });
  20027. };
  20028. let promise;
  20029. // if muted defaults to true
  20030. // the only thing we can do is call play
  20031. if (type === 'any' && !this.muted()) {
  20032. promise = this.play();
  20033. if (isPromise(promise)) {
  20034. promise = promise.catch(resolveMuted);
  20035. }
  20036. } else if (type === 'muted' && !this.muted()) {
  20037. promise = resolveMuted();
  20038. } else {
  20039. promise = this.play();
  20040. }
  20041. if (!isPromise(promise)) {
  20042. return;
  20043. }
  20044. return promise.then(() => {
  20045. this.trigger({
  20046. type: 'autoplay-success',
  20047. autoplay: type
  20048. });
  20049. }).catch(() => {
  20050. this.trigger({
  20051. type: 'autoplay-failure',
  20052. autoplay: type
  20053. });
  20054. });
  20055. }
  20056. /**
  20057. * Update the internal source caches so that we return the correct source from
  20058. * `src()`, `currentSource()`, and `currentSources()`.
  20059. *
  20060. * > Note: `currentSources` will not be updated if the source that is passed in exists
  20061. * in the current `currentSources` cache.
  20062. *
  20063. *
  20064. * @param {Tech~SourceObject} srcObj
  20065. * A string or object source to update our caches to.
  20066. */
  20067. updateSourceCaches_(srcObj = '') {
  20068. let src = srcObj;
  20069. let type = '';
  20070. if (typeof src !== 'string') {
  20071. src = srcObj.src;
  20072. type = srcObj.type;
  20073. }
  20074. // make sure all the caches are set to default values
  20075. // to prevent null checking
  20076. this.cache_.source = this.cache_.source || {};
  20077. this.cache_.sources = this.cache_.sources || [];
  20078. // try to get the type of the src that was passed in
  20079. if (src && !type) {
  20080. type = findMimetype(this, src);
  20081. }
  20082. // update `currentSource` cache always
  20083. this.cache_.source = merge$2({}, srcObj, {
  20084. src,
  20085. type
  20086. });
  20087. const matchingSources = this.cache_.sources.filter(s => s.src && s.src === src);
  20088. const sourceElSources = [];
  20089. const sourceEls = this.$$('source');
  20090. const matchingSourceEls = [];
  20091. for (let i = 0; i < sourceEls.length; i++) {
  20092. const sourceObj = getAttributes(sourceEls[i]);
  20093. sourceElSources.push(sourceObj);
  20094. if (sourceObj.src && sourceObj.src === src) {
  20095. matchingSourceEls.push(sourceObj.src);
  20096. }
  20097. }
  20098. // if we have matching source els but not matching sources
  20099. // the current source cache is not up to date
  20100. if (matchingSourceEls.length && !matchingSources.length) {
  20101. this.cache_.sources = sourceElSources;
  20102. // if we don't have matching source or source els set the
  20103. // sources cache to the `currentSource` cache
  20104. } else if (!matchingSources.length) {
  20105. this.cache_.sources = [this.cache_.source];
  20106. }
  20107. // update the tech `src` cache
  20108. this.cache_.src = src;
  20109. }
  20110. /**
  20111. * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}
  20112. * causing the media element to reload.
  20113. *
  20114. * It will fire for the initial source and each subsequent source.
  20115. * This event is a custom event from Video.js and is triggered by the {@link Tech}.
  20116. *
  20117. * The event object for this event contains a `src` property that will contain the source
  20118. * that was available when the event was triggered. This is generally only necessary if Video.js
  20119. * is switching techs while the source was being changed.
  20120. *
  20121. * It is also fired when `load` is called on the player (or media element)
  20122. * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
  20123. * says that the resource selection algorithm needs to be aborted and restarted.
  20124. * In this case, it is very likely that the `src` property will be set to the
  20125. * empty string `""` to indicate we do not know what the source will be but
  20126. * that it is changing.
  20127. *
  20128. * *This event is currently still experimental and may change in minor releases.*
  20129. * __To use this, pass `enableSourceset` option to the player.__
  20130. *
  20131. * @event Player#sourceset
  20132. * @type {Event}
  20133. * @prop {string} src
  20134. * The source url available when the `sourceset` was triggered.
  20135. * It will be an empty string if we cannot know what the source is
  20136. * but know that the source will change.
  20137. */
  20138. /**
  20139. * Retrigger the `sourceset` event that was triggered by the {@link Tech}.
  20140. *
  20141. * @fires Player#sourceset
  20142. * @listens Tech#sourceset
  20143. * @private
  20144. */
  20145. handleTechSourceset_(event) {
  20146. // only update the source cache when the source
  20147. // was not updated using the player api
  20148. if (!this.changingSrc_) {
  20149. let updateSourceCaches = src => this.updateSourceCaches_(src);
  20150. const playerSrc = this.currentSource().src;
  20151. const eventSrc = event.src;
  20152. // if we have a playerSrc that is not a blob, and a tech src that is a blob
  20153. if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
  20154. // if both the tech source and the player source were updated we assume
  20155. // something like @videojs/http-streaming did the sourceset and skip updating the source cache.
  20156. if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
  20157. updateSourceCaches = () => {};
  20158. }
  20159. }
  20160. // update the source to the initial source right away
  20161. // in some cases this will be empty string
  20162. updateSourceCaches(eventSrc);
  20163. // if the `sourceset` `src` was an empty string
  20164. // wait for a `loadstart` to update the cache to `currentSrc`.
  20165. // If a sourceset happens before a `loadstart`, we reset the state
  20166. if (!event.src) {
  20167. this.tech_.any(['sourceset', 'loadstart'], e => {
  20168. // if a sourceset happens before a `loadstart` there
  20169. // is nothing to do as this `handleTechSourceset_`
  20170. // will be called again and this will be handled there.
  20171. if (e.type === 'sourceset') {
  20172. return;
  20173. }
  20174. const techSrc = this.techGet('currentSrc');
  20175. this.lastSource_.tech = techSrc;
  20176. this.updateSourceCaches_(techSrc);
  20177. });
  20178. }
  20179. }
  20180. this.lastSource_ = {
  20181. player: this.currentSource().src,
  20182. tech: event.src
  20183. };
  20184. this.trigger({
  20185. src: event.src,
  20186. type: 'sourceset'
  20187. });
  20188. }
  20189. /**
  20190. * Add/remove the vjs-has-started class
  20191. *
  20192. *
  20193. * @param {boolean} request
  20194. * - true: adds the class
  20195. * - false: remove the class
  20196. *
  20197. * @return {boolean}
  20198. * the boolean value of hasStarted_
  20199. */
  20200. hasStarted(request) {
  20201. if (request === undefined) {
  20202. // act as getter, if we have no request to change
  20203. return this.hasStarted_;
  20204. }
  20205. if (request === this.hasStarted_) {
  20206. return;
  20207. }
  20208. this.hasStarted_ = request;
  20209. if (this.hasStarted_) {
  20210. this.addClass('vjs-has-started');
  20211. } else {
  20212. this.removeClass('vjs-has-started');
  20213. }
  20214. }
  20215. /**
  20216. * Fired whenever the media begins or resumes playback
  20217. *
  20218. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
  20219. * @fires Player#play
  20220. * @listens Tech#play
  20221. * @private
  20222. */
  20223. handleTechPlay_() {
  20224. this.removeClass('vjs-ended', 'vjs-paused');
  20225. this.addClass('vjs-playing');
  20226. // hide the poster when the user hits play
  20227. this.hasStarted(true);
  20228. /**
  20229. * Triggered whenever an {@link Tech#play} event happens. Indicates that
  20230. * playback has started or resumed.
  20231. *
  20232. * @event Player#play
  20233. * @type {Event}
  20234. */
  20235. this.trigger('play');
  20236. }
  20237. /**
  20238. * Retrigger the `ratechange` event that was triggered by the {@link Tech}.
  20239. *
  20240. * If there were any events queued while the playback rate was zero, fire
  20241. * those events now.
  20242. *
  20243. * @private
  20244. * @method Player#handleTechRateChange_
  20245. * @fires Player#ratechange
  20246. * @listens Tech#ratechange
  20247. */
  20248. handleTechRateChange_() {
  20249. if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
  20250. this.queuedCallbacks_.forEach(queued => queued.callback(queued.event));
  20251. this.queuedCallbacks_ = [];
  20252. }
  20253. this.cache_.lastPlaybackRate = this.tech_.playbackRate();
  20254. /**
  20255. * Fires when the playing speed of the audio/video is changed
  20256. *
  20257. * @event Player#ratechange
  20258. * @type {event}
  20259. */
  20260. this.trigger('ratechange');
  20261. }
  20262. /**
  20263. * Retrigger the `waiting` event that was triggered by the {@link Tech}.
  20264. *
  20265. * @fires Player#waiting
  20266. * @listens Tech#waiting
  20267. * @private
  20268. */
  20269. handleTechWaiting_() {
  20270. this.addClass('vjs-waiting');
  20271. /**
  20272. * A readyState change on the DOM element has caused playback to stop.
  20273. *
  20274. * @event Player#waiting
  20275. * @type {Event}
  20276. */
  20277. this.trigger('waiting');
  20278. // Browsers may emit a timeupdate event after a waiting event. In order to prevent
  20279. // premature removal of the waiting class, wait for the time to change.
  20280. const timeWhenWaiting = this.currentTime();
  20281. const timeUpdateListener = () => {
  20282. if (timeWhenWaiting !== this.currentTime()) {
  20283. this.removeClass('vjs-waiting');
  20284. this.off('timeupdate', timeUpdateListener);
  20285. }
  20286. };
  20287. this.on('timeupdate', timeUpdateListener);
  20288. }
  20289. /**
  20290. * Retrigger the `canplay` event that was triggered by the {@link Tech}.
  20291. * > Note: This is not consistent between browsers. See #1351
  20292. *
  20293. * @fires Player#canplay
  20294. * @listens Tech#canplay
  20295. * @private
  20296. */
  20297. handleTechCanPlay_() {
  20298. this.removeClass('vjs-waiting');
  20299. /**
  20300. * The media has a readyState of HAVE_FUTURE_DATA or greater.
  20301. *
  20302. * @event Player#canplay
  20303. * @type {Event}
  20304. */
  20305. this.trigger('canplay');
  20306. }
  20307. /**
  20308. * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.
  20309. *
  20310. * @fires Player#canplaythrough
  20311. * @listens Tech#canplaythrough
  20312. * @private
  20313. */
  20314. handleTechCanPlayThrough_() {
  20315. this.removeClass('vjs-waiting');
  20316. /**
  20317. * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the
  20318. * entire media file can be played without buffering.
  20319. *
  20320. * @event Player#canplaythrough
  20321. * @type {Event}
  20322. */
  20323. this.trigger('canplaythrough');
  20324. }
  20325. /**
  20326. * Retrigger the `playing` event that was triggered by the {@link Tech}.
  20327. *
  20328. * @fires Player#playing
  20329. * @listens Tech#playing
  20330. * @private
  20331. */
  20332. handleTechPlaying_() {
  20333. this.removeClass('vjs-waiting');
  20334. /**
  20335. * The media is no longer blocked from playback, and has started playing.
  20336. *
  20337. * @event Player#playing
  20338. * @type {Event}
  20339. */
  20340. this.trigger('playing');
  20341. }
  20342. /**
  20343. * Retrigger the `seeking` event that was triggered by the {@link Tech}.
  20344. *
  20345. * @fires Player#seeking
  20346. * @listens Tech#seeking
  20347. * @private
  20348. */
  20349. handleTechSeeking_() {
  20350. this.addClass('vjs-seeking');
  20351. /**
  20352. * Fired whenever the player is jumping to a new time
  20353. *
  20354. * @event Player#seeking
  20355. * @type {Event}
  20356. */
  20357. this.trigger('seeking');
  20358. }
  20359. /**
  20360. * Retrigger the `seeked` event that was triggered by the {@link Tech}.
  20361. *
  20362. * @fires Player#seeked
  20363. * @listens Tech#seeked
  20364. * @private
  20365. */
  20366. handleTechSeeked_() {
  20367. this.removeClass('vjs-seeking', 'vjs-ended');
  20368. /**
  20369. * Fired when the player has finished jumping to a new time
  20370. *
  20371. * @event Player#seeked
  20372. * @type {Event}
  20373. */
  20374. this.trigger('seeked');
  20375. }
  20376. /**
  20377. * Retrigger the `pause` event that was triggered by the {@link Tech}.
  20378. *
  20379. * @fires Player#pause
  20380. * @listens Tech#pause
  20381. * @private
  20382. */
  20383. handleTechPause_() {
  20384. this.removeClass('vjs-playing');
  20385. this.addClass('vjs-paused');
  20386. /**
  20387. * Fired whenever the media has been paused
  20388. *
  20389. * @event Player#pause
  20390. * @type {Event}
  20391. */
  20392. this.trigger('pause');
  20393. }
  20394. /**
  20395. * Retrigger the `ended` event that was triggered by the {@link Tech}.
  20396. *
  20397. * @fires Player#ended
  20398. * @listens Tech#ended
  20399. * @private
  20400. */
  20401. handleTechEnded_() {
  20402. this.addClass('vjs-ended');
  20403. this.removeClass('vjs-waiting');
  20404. if (this.options_.loop) {
  20405. this.currentTime(0);
  20406. this.play();
  20407. } else if (!this.paused()) {
  20408. this.pause();
  20409. }
  20410. /**
  20411. * Fired when the end of the media resource is reached (currentTime == duration)
  20412. *
  20413. * @event Player#ended
  20414. * @type {Event}
  20415. */
  20416. this.trigger('ended');
  20417. }
  20418. /**
  20419. * Fired when the duration of the media resource is first known or changed
  20420. *
  20421. * @listens Tech#durationchange
  20422. * @private
  20423. */
  20424. handleTechDurationChange_() {
  20425. this.duration(this.techGet_('duration'));
  20426. }
  20427. /**
  20428. * Handle a click on the media element to play/pause
  20429. *
  20430. * @param {Event} event
  20431. * the event that caused this function to trigger
  20432. *
  20433. * @listens Tech#click
  20434. * @private
  20435. */
  20436. handleTechClick_(event) {
  20437. // When controls are disabled a click should not toggle playback because
  20438. // the click is considered a control
  20439. if (!this.controls_) {
  20440. return;
  20441. }
  20442. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.click === undefined || this.options_.userActions.click !== false) {
  20443. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.click === 'function') {
  20444. this.options_.userActions.click.call(this, event);
  20445. } else if (this.paused()) {
  20446. silencePromise(this.play());
  20447. } else {
  20448. this.pause();
  20449. }
  20450. }
  20451. }
  20452. /**
  20453. * Handle a double-click on the media element to enter/exit fullscreen
  20454. *
  20455. * @param {Event} event
  20456. * the event that caused this function to trigger
  20457. *
  20458. * @listens Tech#dblclick
  20459. * @private
  20460. */
  20461. handleTechDoubleClick_(event) {
  20462. if (!this.controls_) {
  20463. return;
  20464. }
  20465. // we do not want to toggle fullscreen state
  20466. // when double-clicking inside a control bar or a modal
  20467. const inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), el => el.contains(event.target));
  20468. if (!inAllowedEls) {
  20469. /*
  20470. * options.userActions.doubleClick
  20471. *
  20472. * If `undefined` or `true`, double-click toggles fullscreen if controls are present
  20473. * Set to `false` to disable double-click handling
  20474. * Set to a function to substitute an external double-click handler
  20475. */
  20476. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) {
  20477. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') {
  20478. this.options_.userActions.doubleClick.call(this, event);
  20479. } else if (this.isFullscreen()) {
  20480. this.exitFullscreen();
  20481. } else {
  20482. this.requestFullscreen();
  20483. }
  20484. }
  20485. }
  20486. }
  20487. /**
  20488. * Handle a tap on the media element. It will toggle the user
  20489. * activity state, which hides and shows the controls.
  20490. *
  20491. * @listens Tech#tap
  20492. * @private
  20493. */
  20494. handleTechTap_() {
  20495. this.userActive(!this.userActive());
  20496. }
  20497. /**
  20498. * Handle touch to start
  20499. *
  20500. * @listens Tech#touchstart
  20501. * @private
  20502. */
  20503. handleTechTouchStart_() {
  20504. this.userWasActive = this.userActive();
  20505. }
  20506. /**
  20507. * Handle touch to move
  20508. *
  20509. * @listens Tech#touchmove
  20510. * @private
  20511. */
  20512. handleTechTouchMove_() {
  20513. if (this.userWasActive) {
  20514. this.reportUserActivity();
  20515. }
  20516. }
  20517. /**
  20518. * Handle touch to end
  20519. *
  20520. * @param {Event} event
  20521. * the touchend event that triggered
  20522. * this function
  20523. *
  20524. * @listens Tech#touchend
  20525. * @private
  20526. */
  20527. handleTechTouchEnd_(event) {
  20528. // Stop the mouse events from also happening
  20529. if (event.cancelable) {
  20530. event.preventDefault();
  20531. }
  20532. }
  20533. /**
  20534. * @private
  20535. */
  20536. toggleFullscreenClass_() {
  20537. if (this.isFullscreen()) {
  20538. this.addClass('vjs-fullscreen');
  20539. } else {
  20540. this.removeClass('vjs-fullscreen');
  20541. }
  20542. }
  20543. /**
  20544. * when the document fschange event triggers it calls this
  20545. */
  20546. documentFullscreenChange_(e) {
  20547. const targetPlayer = e.target.player;
  20548. // if another player was fullscreen
  20549. // do a null check for targetPlayer because older firefox's would put document as e.target
  20550. if (targetPlayer && targetPlayer !== this) {
  20551. return;
  20552. }
  20553. const el = this.el();
  20554. let isFs = document[this.fsApi_.fullscreenElement] === el;
  20555. if (!isFs && el.matches) {
  20556. isFs = el.matches(':' + this.fsApi_.fullscreen);
  20557. } else if (!isFs && el.msMatchesSelector) {
  20558. isFs = el.msMatchesSelector(':' + this.fsApi_.fullscreen);
  20559. }
  20560. this.isFullscreen(isFs);
  20561. }
  20562. /**
  20563. * Handle Tech Fullscreen Change
  20564. *
  20565. * @param {Event} event
  20566. * the fullscreenchange event that triggered this function
  20567. *
  20568. * @param {Object} data
  20569. * the data that was sent with the event
  20570. *
  20571. * @private
  20572. * @listens Tech#fullscreenchange
  20573. * @fires Player#fullscreenchange
  20574. */
  20575. handleTechFullscreenChange_(event, data) {
  20576. if (data) {
  20577. if (data.nativeIOSFullscreen) {
  20578. this.addClass('vjs-ios-native-fs');
  20579. this.tech_.one('webkitendfullscreen', () => {
  20580. this.removeClass('vjs-ios-native-fs');
  20581. });
  20582. }
  20583. this.isFullscreen(data.isFullscreen);
  20584. }
  20585. }
  20586. handleTechFullscreenError_(event, err) {
  20587. this.trigger('fullscreenerror', err);
  20588. }
  20589. /**
  20590. * @private
  20591. */
  20592. togglePictureInPictureClass_() {
  20593. if (this.isInPictureInPicture()) {
  20594. this.addClass('vjs-picture-in-picture');
  20595. } else {
  20596. this.removeClass('vjs-picture-in-picture');
  20597. }
  20598. }
  20599. /**
  20600. * Handle Tech Enter Picture-in-Picture.
  20601. *
  20602. * @param {Event} event
  20603. * the enterpictureinpicture event that triggered this function
  20604. *
  20605. * @private
  20606. * @listens Tech#enterpictureinpicture
  20607. */
  20608. handleTechEnterPictureInPicture_(event) {
  20609. this.isInPictureInPicture(true);
  20610. }
  20611. /**
  20612. * Handle Tech Leave Picture-in-Picture.
  20613. *
  20614. * @param {Event} event
  20615. * the leavepictureinpicture event that triggered this function
  20616. *
  20617. * @private
  20618. * @listens Tech#leavepictureinpicture
  20619. */
  20620. handleTechLeavePictureInPicture_(event) {
  20621. this.isInPictureInPicture(false);
  20622. }
  20623. /**
  20624. * Fires when an error occurred during the loading of an audio/video.
  20625. *
  20626. * @private
  20627. * @listens Tech#error
  20628. */
  20629. handleTechError_() {
  20630. const error = this.tech_.error();
  20631. this.error(error);
  20632. }
  20633. /**
  20634. * Retrigger the `textdata` event that was triggered by the {@link Tech}.
  20635. *
  20636. * @fires Player#textdata
  20637. * @listens Tech#textdata
  20638. * @private
  20639. */
  20640. handleTechTextData_() {
  20641. let data = null;
  20642. if (arguments.length > 1) {
  20643. data = arguments[1];
  20644. }
  20645. /**
  20646. * Fires when we get a textdata event from tech
  20647. *
  20648. * @event Player#textdata
  20649. * @type {Event}
  20650. */
  20651. this.trigger('textdata', data);
  20652. }
  20653. /**
  20654. * Get object for cached values.
  20655. *
  20656. * @return {Object}
  20657. * get the current object cache
  20658. */
  20659. getCache() {
  20660. return this.cache_;
  20661. }
  20662. /**
  20663. * Resets the internal cache object.
  20664. *
  20665. * Using this function outside the player constructor or reset method may
  20666. * have unintended side-effects.
  20667. *
  20668. * @private
  20669. */
  20670. resetCache_() {
  20671. this.cache_ = {
  20672. // Right now, the currentTime is not _really_ cached because it is always
  20673. // retrieved from the tech (see: currentTime). However, for completeness,
  20674. // we set it to zero here to ensure that if we do start actually caching
  20675. // it, we reset it along with everything else.
  20676. currentTime: 0,
  20677. initTime: 0,
  20678. inactivityTimeout: this.options_.inactivityTimeout,
  20679. duration: NaN,
  20680. lastVolume: 1,
  20681. lastPlaybackRate: this.defaultPlaybackRate(),
  20682. media: null,
  20683. src: '',
  20684. source: {},
  20685. sources: [],
  20686. playbackRates: [],
  20687. volume: 1
  20688. };
  20689. }
  20690. /**
  20691. * Pass values to the playback tech
  20692. *
  20693. * @param {string} [method]
  20694. * the method to call
  20695. *
  20696. * @param {Object} arg
  20697. * the argument to pass
  20698. *
  20699. * @private
  20700. */
  20701. techCall_(method, arg) {
  20702. // If it's not ready yet, call method when it is
  20703. this.ready(function () {
  20704. if (method in allowedSetters) {
  20705. return set(this.middleware_, this.tech_, method, arg);
  20706. } else if (method in allowedMediators) {
  20707. return mediate(this.middleware_, this.tech_, method, arg);
  20708. }
  20709. try {
  20710. if (this.tech_) {
  20711. this.tech_[method](arg);
  20712. }
  20713. } catch (e) {
  20714. log$1(e);
  20715. throw e;
  20716. }
  20717. }, true);
  20718. }
  20719. /**
  20720. * Mediate attempt to call playback tech method
  20721. * and return the value of the method called.
  20722. *
  20723. * @param {string} method
  20724. * Tech method
  20725. *
  20726. * @return {*}
  20727. * Value returned by the tech method called, undefined if tech
  20728. * is not ready or tech method is not present
  20729. *
  20730. * @private
  20731. */
  20732. techGet_(method) {
  20733. if (!this.tech_ || !this.tech_.isReady_) {
  20734. return;
  20735. }
  20736. if (method in allowedGetters) {
  20737. return get(this.middleware_, this.tech_, method);
  20738. } else if (method in allowedMediators) {
  20739. return mediate(this.middleware_, this.tech_, method);
  20740. }
  20741. // Log error when playback tech object is present but method
  20742. // is undefined or unavailable
  20743. try {
  20744. return this.tech_[method]();
  20745. } catch (e) {
  20746. // When building additional tech libs, an expected method may not be defined yet
  20747. if (this.tech_[method] === undefined) {
  20748. log$1(`Video.js: ${method} method not defined for ${this.techName_} playback technology.`, e);
  20749. throw e;
  20750. }
  20751. // When a method isn't available on the object it throws a TypeError
  20752. if (e.name === 'TypeError') {
  20753. log$1(`Video.js: ${method} unavailable on ${this.techName_} playback technology element.`, e);
  20754. this.tech_.isReady_ = false;
  20755. throw e;
  20756. }
  20757. // If error unknown, just log and throw
  20758. log$1(e);
  20759. throw e;
  20760. }
  20761. }
  20762. /**
  20763. * Attempt to begin playback at the first opportunity.
  20764. *
  20765. * @return {Promise|undefined}
  20766. * Returns a promise if the browser supports Promises (or one
  20767. * was passed in as an option). This promise will be resolved on
  20768. * the return value of play. If this is undefined it will fulfill the
  20769. * promise chain otherwise the promise chain will be fulfilled when
  20770. * the promise from play is fulfilled.
  20771. */
  20772. play() {
  20773. return new Promise(resolve => {
  20774. this.play_(resolve);
  20775. });
  20776. }
  20777. /**
  20778. * The actual logic for play, takes a callback that will be resolved on the
  20779. * return value of play. This allows us to resolve to the play promise if there
  20780. * is one on modern browsers.
  20781. *
  20782. * @private
  20783. * @param {Function} [callback]
  20784. * The callback that should be called when the techs play is actually called
  20785. */
  20786. play_(callback = silencePromise) {
  20787. this.playCallbacks_.push(callback);
  20788. const isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));
  20789. const isSafariOrIOS = Boolean(IS_ANY_SAFARI || IS_IOS);
  20790. // treat calls to play_ somewhat like the `one` event function
  20791. if (this.waitToPlay_) {
  20792. this.off(['ready', 'loadstart'], this.waitToPlay_);
  20793. this.waitToPlay_ = null;
  20794. }
  20795. // if the player/tech is not ready or the src itself is not ready
  20796. // queue up a call to play on `ready` or `loadstart`
  20797. if (!this.isReady_ || !isSrcReady) {
  20798. this.waitToPlay_ = e => {
  20799. this.play_();
  20800. };
  20801. this.one(['ready', 'loadstart'], this.waitToPlay_);
  20802. // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod
  20803. // in that case, we need to prime the video element by calling load so it'll be ready in time
  20804. if (!isSrcReady && isSafariOrIOS) {
  20805. this.load();
  20806. }
  20807. return;
  20808. }
  20809. // If the player/tech is ready and we have a source, we can attempt playback.
  20810. const val = this.techGet_('play');
  20811. // For native playback, reset the progress bar if we get a play call from a replay.
  20812. const isNativeReplay = isSafariOrIOS && this.hasClass('vjs-ended');
  20813. if (isNativeReplay) {
  20814. this.resetProgressBar_();
  20815. }
  20816. // play was terminated if the returned value is null
  20817. if (val === null) {
  20818. this.runPlayTerminatedQueue_();
  20819. } else {
  20820. this.runPlayCallbacks_(val);
  20821. }
  20822. }
  20823. /**
  20824. * These functions will be run when if play is terminated. If play
  20825. * runPlayCallbacks_ is run these function will not be run. This allows us
  20826. * to differentiate between a terminated play and an actual call to play.
  20827. */
  20828. runPlayTerminatedQueue_() {
  20829. const queue = this.playTerminatedQueue_.slice(0);
  20830. this.playTerminatedQueue_ = [];
  20831. queue.forEach(function (q) {
  20832. q();
  20833. });
  20834. }
  20835. /**
  20836. * When a callback to play is delayed we have to run these
  20837. * callbacks when play is actually called on the tech. This function
  20838. * runs the callbacks that were delayed and accepts the return value
  20839. * from the tech.
  20840. *
  20841. * @param {undefined|Promise} val
  20842. * The return value from the tech.
  20843. */
  20844. runPlayCallbacks_(val) {
  20845. const callbacks = this.playCallbacks_.slice(0);
  20846. this.playCallbacks_ = [];
  20847. // clear play terminatedQueue since we finished a real play
  20848. this.playTerminatedQueue_ = [];
  20849. callbacks.forEach(function (cb) {
  20850. cb(val);
  20851. });
  20852. }
  20853. /**
  20854. * Pause the video playback
  20855. *
  20856. * @return {Player}
  20857. * A reference to the player object this function was called on
  20858. */
  20859. pause() {
  20860. this.techCall_('pause');
  20861. }
  20862. /**
  20863. * Check if the player is paused or has yet to play
  20864. *
  20865. * @return {boolean}
  20866. * - false: if the media is currently playing
  20867. * - true: if media is not currently playing
  20868. */
  20869. paused() {
  20870. // The initial state of paused should be true (in Safari it's actually false)
  20871. return this.techGet_('paused') === false ? false : true;
  20872. }
  20873. /**
  20874. * Get a TimeRange object representing the current ranges of time that the user
  20875. * has played.
  20876. *
  20877. * @return { import('./utils/time').TimeRange }
  20878. * A time range object that represents all the increments of time that have
  20879. * been played.
  20880. */
  20881. played() {
  20882. return this.techGet_('played') || createTimeRanges$1(0, 0);
  20883. }
  20884. /**
  20885. * Returns whether or not the user is "scrubbing". Scrubbing is
  20886. * when the user has clicked the progress bar handle and is
  20887. * dragging it along the progress bar.
  20888. *
  20889. * @param {boolean} [isScrubbing]
  20890. * whether the user is or is not scrubbing
  20891. *
  20892. * @return {boolean}
  20893. * The value of scrubbing when getting
  20894. */
  20895. scrubbing(isScrubbing) {
  20896. if (typeof isScrubbing === 'undefined') {
  20897. return this.scrubbing_;
  20898. }
  20899. this.scrubbing_ = !!isScrubbing;
  20900. this.techCall_('setScrubbing', this.scrubbing_);
  20901. if (isScrubbing) {
  20902. this.addClass('vjs-scrubbing');
  20903. } else {
  20904. this.removeClass('vjs-scrubbing');
  20905. }
  20906. }
  20907. /**
  20908. * Get or set the current time (in seconds)
  20909. *
  20910. * @param {number|string} [seconds]
  20911. * The time to seek to in seconds
  20912. *
  20913. * @return {number}
  20914. * - the current time in seconds when getting
  20915. */
  20916. currentTime(seconds) {
  20917. if (typeof seconds !== 'undefined') {
  20918. if (seconds < 0) {
  20919. seconds = 0;
  20920. }
  20921. if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {
  20922. this.cache_.initTime = seconds;
  20923. this.off('canplay', this.boundApplyInitTime_);
  20924. this.one('canplay', this.boundApplyInitTime_);
  20925. return;
  20926. }
  20927. this.techCall_('setCurrentTime', seconds);
  20928. this.cache_.initTime = 0;
  20929. return;
  20930. }
  20931. // cache last currentTime and return. default to 0 seconds
  20932. //
  20933. // Caching the currentTime is meant to prevent a massive amount of reads on the tech's
  20934. // currentTime when scrubbing, but may not provide much performance benefit after all.
  20935. // Should be tested. Also something has to read the actual current time or the cache will
  20936. // never get updated.
  20937. this.cache_.currentTime = this.techGet_('currentTime') || 0;
  20938. return this.cache_.currentTime;
  20939. }
  20940. /**
  20941. * Apply the value of initTime stored in cache as currentTime.
  20942. *
  20943. * @private
  20944. */
  20945. applyInitTime_() {
  20946. this.currentTime(this.cache_.initTime);
  20947. }
  20948. /**
  20949. * Normally gets the length in time of the video in seconds;
  20950. * in all but the rarest use cases an argument will NOT be passed to the method
  20951. *
  20952. * > **NOTE**: The video must have started loading before the duration can be
  20953. * known, and depending on preload behaviour may not be known until the video starts
  20954. * playing.
  20955. *
  20956. * @fires Player#durationchange
  20957. *
  20958. * @param {number} [seconds]
  20959. * The duration of the video to set in seconds
  20960. *
  20961. * @return {number}
  20962. * - The duration of the video in seconds when getting
  20963. */
  20964. duration(seconds) {
  20965. if (seconds === undefined) {
  20966. // return NaN if the duration is not known
  20967. return this.cache_.duration !== undefined ? this.cache_.duration : NaN;
  20968. }
  20969. seconds = parseFloat(seconds);
  20970. // Standardize on Infinity for signaling video is live
  20971. if (seconds < 0) {
  20972. seconds = Infinity;
  20973. }
  20974. if (seconds !== this.cache_.duration) {
  20975. // Cache the last set value for optimized scrubbing
  20976. this.cache_.duration = seconds;
  20977. if (seconds === Infinity) {
  20978. this.addClass('vjs-live');
  20979. } else {
  20980. this.removeClass('vjs-live');
  20981. }
  20982. if (!isNaN(seconds)) {
  20983. // Do not fire durationchange unless the duration value is known.
  20984. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  20985. /**
  20986. * @event Player#durationchange
  20987. * @type {Event}
  20988. */
  20989. this.trigger('durationchange');
  20990. }
  20991. }
  20992. }
  20993. /**
  20994. * Calculates how much time is left in the video. Not part
  20995. * of the native video API.
  20996. *
  20997. * @return {number}
  20998. * The time remaining in seconds
  20999. */
  21000. remainingTime() {
  21001. return this.duration() - this.currentTime();
  21002. }
  21003. /**
  21004. * A remaining time function that is intended to be used when
  21005. * the time is to be displayed directly to the user.
  21006. *
  21007. * @return {number}
  21008. * The rounded time remaining in seconds
  21009. */
  21010. remainingTimeDisplay() {
  21011. return Math.floor(this.duration()) - Math.floor(this.currentTime());
  21012. }
  21013. //
  21014. // Kind of like an array of portions of the video that have been downloaded.
  21015. /**
  21016. * Get a TimeRange object with an array of the times of the video
  21017. * that have been downloaded. If you just want the percent of the
  21018. * video that's been downloaded, use bufferedPercent.
  21019. *
  21020. * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
  21021. *
  21022. * @return { import('./utils/time').TimeRange }
  21023. * A mock {@link TimeRanges} object (following HTML spec)
  21024. */
  21025. buffered() {
  21026. let buffered = this.techGet_('buffered');
  21027. if (!buffered || !buffered.length) {
  21028. buffered = createTimeRanges$1(0, 0);
  21029. }
  21030. return buffered;
  21031. }
  21032. /**
  21033. * Get the percent (as a decimal) of the video that's been downloaded.
  21034. * This method is not a part of the native HTML video API.
  21035. *
  21036. * @return {number}
  21037. * A decimal between 0 and 1 representing the percent
  21038. * that is buffered 0 being 0% and 1 being 100%
  21039. */
  21040. bufferedPercent() {
  21041. return bufferedPercent(this.buffered(), this.duration());
  21042. }
  21043. /**
  21044. * Get the ending time of the last buffered time range
  21045. * This is used in the progress bar to encapsulate all time ranges.
  21046. *
  21047. * @return {number}
  21048. * The end of the last buffered time range
  21049. */
  21050. bufferedEnd() {
  21051. const buffered = this.buffered();
  21052. const duration = this.duration();
  21053. let end = buffered.end(buffered.length - 1);
  21054. if (end > duration) {
  21055. end = duration;
  21056. }
  21057. return end;
  21058. }
  21059. /**
  21060. * Get or set the current volume of the media
  21061. *
  21062. * @param {number} [percentAsDecimal]
  21063. * The new volume as a decimal percent:
  21064. * - 0 is muted/0%/off
  21065. * - 1.0 is 100%/full
  21066. * - 0.5 is half volume or 50%
  21067. *
  21068. * @return {number}
  21069. * The current volume as a percent when getting
  21070. */
  21071. volume(percentAsDecimal) {
  21072. let vol;
  21073. if (percentAsDecimal !== undefined) {
  21074. // Force value to between 0 and 1
  21075. vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal)));
  21076. this.cache_.volume = vol;
  21077. this.techCall_('setVolume', vol);
  21078. if (vol > 0) {
  21079. this.lastVolume_(vol);
  21080. }
  21081. return;
  21082. }
  21083. // Default to 1 when returning current volume.
  21084. vol = parseFloat(this.techGet_('volume'));
  21085. return isNaN(vol) ? 1 : vol;
  21086. }
  21087. /**
  21088. * Get the current muted state, or turn mute on or off
  21089. *
  21090. * @param {boolean} [muted]
  21091. * - true to mute
  21092. * - false to unmute
  21093. *
  21094. * @return {boolean}
  21095. * - true if mute is on and getting
  21096. * - false if mute is off and getting
  21097. */
  21098. muted(muted) {
  21099. if (muted !== undefined) {
  21100. this.techCall_('setMuted', muted);
  21101. return;
  21102. }
  21103. return this.techGet_('muted') || false;
  21104. }
  21105. /**
  21106. * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted
  21107. * indicates the state of muted on initial playback.
  21108. *
  21109. * ```js
  21110. * var myPlayer = videojs('some-player-id');
  21111. *
  21112. * myPlayer.src("http://www.example.com/path/to/video.mp4");
  21113. *
  21114. * // get, should be false
  21115. * console.log(myPlayer.defaultMuted());
  21116. * // set to true
  21117. * myPlayer.defaultMuted(true);
  21118. * // get should be true
  21119. * console.log(myPlayer.defaultMuted());
  21120. * ```
  21121. *
  21122. * @param {boolean} [defaultMuted]
  21123. * - true to mute
  21124. * - false to unmute
  21125. *
  21126. * @return {boolean|Player}
  21127. * - true if defaultMuted is on and getting
  21128. * - false if defaultMuted is off and getting
  21129. * - A reference to the current player when setting
  21130. */
  21131. defaultMuted(defaultMuted) {
  21132. if (defaultMuted !== undefined) {
  21133. return this.techCall_('setDefaultMuted', defaultMuted);
  21134. }
  21135. return this.techGet_('defaultMuted') || false;
  21136. }
  21137. /**
  21138. * Get the last volume, or set it
  21139. *
  21140. * @param {number} [percentAsDecimal]
  21141. * The new last volume as a decimal percent:
  21142. * - 0 is muted/0%/off
  21143. * - 1.0 is 100%/full
  21144. * - 0.5 is half volume or 50%
  21145. *
  21146. * @return {number}
  21147. * the current value of lastVolume as a percent when getting
  21148. *
  21149. * @private
  21150. */
  21151. lastVolume_(percentAsDecimal) {
  21152. if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {
  21153. this.cache_.lastVolume = percentAsDecimal;
  21154. return;
  21155. }
  21156. return this.cache_.lastVolume;
  21157. }
  21158. /**
  21159. * Check if current tech can support native fullscreen
  21160. * (e.g. with built in controls like iOS)
  21161. *
  21162. * @return {boolean}
  21163. * if native fullscreen is supported
  21164. */
  21165. supportsFullScreen() {
  21166. return this.techGet_('supportsFullScreen') || false;
  21167. }
  21168. /**
  21169. * Check if the player is in fullscreen mode or tell the player that it
  21170. * is or is not in fullscreen mode.
  21171. *
  21172. * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
  21173. * property and instead document.fullscreenElement is used. But isFullscreen is
  21174. * still a valuable property for internal player workings.
  21175. *
  21176. * @param {boolean} [isFS]
  21177. * Set the players current fullscreen state
  21178. *
  21179. * @return {boolean}
  21180. * - true if fullscreen is on and getting
  21181. * - false if fullscreen is off and getting
  21182. */
  21183. isFullscreen(isFS) {
  21184. if (isFS !== undefined) {
  21185. const oldValue = this.isFullscreen_;
  21186. this.isFullscreen_ = Boolean(isFS);
  21187. // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange
  21188. // this is the only place where we trigger fullscreenchange events for older browsers
  21189. // fullWindow mode is treated as a prefixed event and will get a fullscreenchange event as well
  21190. if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {
  21191. /**
  21192. * @event Player#fullscreenchange
  21193. * @type {Event}
  21194. */
  21195. this.trigger('fullscreenchange');
  21196. }
  21197. this.toggleFullscreenClass_();
  21198. return;
  21199. }
  21200. return this.isFullscreen_;
  21201. }
  21202. /**
  21203. * Increase the size of the video to full screen
  21204. * In some browsers, full screen is not supported natively, so it enters
  21205. * "full window mode", where the video fills the browser window.
  21206. * In browsers and devices that support native full screen, sometimes the
  21207. * browser's default controls will be shown, and not the Video.js custom skin.
  21208. * This includes most mobile devices (iOS, Android) and older versions of
  21209. * Safari.
  21210. *
  21211. * @param {Object} [fullscreenOptions]
  21212. * Override the player fullscreen options
  21213. *
  21214. * @fires Player#fullscreenchange
  21215. */
  21216. requestFullscreen(fullscreenOptions) {
  21217. if (this.isInPictureInPicture()) {
  21218. this.exitPictureInPicture();
  21219. }
  21220. const self = this;
  21221. return new Promise((resolve, reject) => {
  21222. function offHandler() {
  21223. self.off('fullscreenerror', errorHandler);
  21224. self.off('fullscreenchange', changeHandler);
  21225. }
  21226. function changeHandler() {
  21227. offHandler();
  21228. resolve();
  21229. }
  21230. function errorHandler(e, err) {
  21231. offHandler();
  21232. reject(err);
  21233. }
  21234. self.one('fullscreenchange', changeHandler);
  21235. self.one('fullscreenerror', errorHandler);
  21236. const promise = self.requestFullscreenHelper_(fullscreenOptions);
  21237. if (promise) {
  21238. promise.then(offHandler, offHandler);
  21239. promise.then(resolve, reject);
  21240. }
  21241. });
  21242. }
  21243. requestFullscreenHelper_(fullscreenOptions) {
  21244. let fsOptions;
  21245. // Only pass fullscreen options to requestFullscreen in spec-compliant browsers.
  21246. // Use defaults or player configured option unless passed directly to this method.
  21247. if (!this.fsApi_.prefixed) {
  21248. fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
  21249. if (fullscreenOptions !== undefined) {
  21250. fsOptions = fullscreenOptions;
  21251. }
  21252. }
  21253. // This method works as follows:
  21254. // 1. if a fullscreen api is available, use it
  21255. // 1. call requestFullscreen with potential options
  21256. // 2. if we got a promise from above, use it to update isFullscreen()
  21257. // 2. otherwise, if the tech supports fullscreen, call `enterFullScreen` on it.
  21258. // This is particularly used for iPhone, older iPads, and non-safari browser on iOS.
  21259. // 3. otherwise, use "fullWindow" mode
  21260. if (this.fsApi_.requestFullscreen) {
  21261. const promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);
  21262. // Even on browsers with promise support this may not return a promise
  21263. if (promise) {
  21264. promise.then(() => this.isFullscreen(true), () => this.isFullscreen(false));
  21265. }
  21266. return promise;
  21267. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  21268. // we can't take the video.js controls fullscreen but we can go fullscreen
  21269. // with native controls
  21270. this.techCall_('enterFullScreen');
  21271. } else {
  21272. // fullscreen isn't supported so we'll just stretch the video element to
  21273. // fill the viewport
  21274. this.enterFullWindow();
  21275. }
  21276. }
  21277. /**
  21278. * Return the video to its normal size after having been in full screen mode
  21279. *
  21280. * @fires Player#fullscreenchange
  21281. */
  21282. exitFullscreen() {
  21283. const self = this;
  21284. return new Promise((resolve, reject) => {
  21285. function offHandler() {
  21286. self.off('fullscreenerror', errorHandler);
  21287. self.off('fullscreenchange', changeHandler);
  21288. }
  21289. function changeHandler() {
  21290. offHandler();
  21291. resolve();
  21292. }
  21293. function errorHandler(e, err) {
  21294. offHandler();
  21295. reject(err);
  21296. }
  21297. self.one('fullscreenchange', changeHandler);
  21298. self.one('fullscreenerror', errorHandler);
  21299. const promise = self.exitFullscreenHelper_();
  21300. if (promise) {
  21301. promise.then(offHandler, offHandler);
  21302. // map the promise to our resolve/reject methods
  21303. promise.then(resolve, reject);
  21304. }
  21305. });
  21306. }
  21307. exitFullscreenHelper_() {
  21308. if (this.fsApi_.requestFullscreen) {
  21309. const promise = document[this.fsApi_.exitFullscreen]();
  21310. // Even on browsers with promise support this may not return a promise
  21311. if (promise) {
  21312. // we're splitting the promise here, so, we want to catch the
  21313. // potential error so that this chain doesn't have unhandled errors
  21314. silencePromise(promise.then(() => this.isFullscreen(false)));
  21315. }
  21316. return promise;
  21317. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  21318. this.techCall_('exitFullScreen');
  21319. } else {
  21320. this.exitFullWindow();
  21321. }
  21322. }
  21323. /**
  21324. * When fullscreen isn't supported we can stretch the
  21325. * video container to as wide as the browser will let us.
  21326. *
  21327. * @fires Player#enterFullWindow
  21328. */
  21329. enterFullWindow() {
  21330. this.isFullscreen(true);
  21331. this.isFullWindow = true;
  21332. // Storing original doc overflow value to return to when fullscreen is off
  21333. this.docOrigOverflow = document.documentElement.style.overflow;
  21334. // Add listener for esc key to exit fullscreen
  21335. on(document, 'keydown', this.boundFullWindowOnEscKey_);
  21336. // Hide any scroll bars
  21337. document.documentElement.style.overflow = 'hidden';
  21338. // Apply fullscreen styles
  21339. addClass(document.body, 'vjs-full-window');
  21340. /**
  21341. * @event Player#enterFullWindow
  21342. * @type {Event}
  21343. */
  21344. this.trigger('enterFullWindow');
  21345. }
  21346. /**
  21347. * Check for call to either exit full window or
  21348. * full screen on ESC key
  21349. *
  21350. * @param {string} event
  21351. * Event to check for key press
  21352. */
  21353. fullWindowOnEscKey(event) {
  21354. if (keycode.isEventKey(event, 'Esc')) {
  21355. if (this.isFullscreen() === true) {
  21356. if (!this.isFullWindow) {
  21357. this.exitFullscreen();
  21358. } else {
  21359. this.exitFullWindow();
  21360. }
  21361. }
  21362. }
  21363. }
  21364. /**
  21365. * Exit full window
  21366. *
  21367. * @fires Player#exitFullWindow
  21368. */
  21369. exitFullWindow() {
  21370. this.isFullscreen(false);
  21371. this.isFullWindow = false;
  21372. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  21373. // Unhide scroll bars.
  21374. document.documentElement.style.overflow = this.docOrigOverflow;
  21375. // Remove fullscreen styles
  21376. removeClass(document.body, 'vjs-full-window');
  21377. // Resize the box, controller, and poster to original sizes
  21378. // this.positionAll();
  21379. /**
  21380. * @event Player#exitFullWindow
  21381. * @type {Event}
  21382. */
  21383. this.trigger('exitFullWindow');
  21384. }
  21385. /**
  21386. * Disable Picture-in-Picture mode.
  21387. *
  21388. * @param {boolean} value
  21389. * - true will disable Picture-in-Picture mode
  21390. * - false will enable Picture-in-Picture mode
  21391. */
  21392. disablePictureInPicture(value) {
  21393. if (value === undefined) {
  21394. return this.techGet_('disablePictureInPicture');
  21395. }
  21396. this.techCall_('setDisablePictureInPicture', value);
  21397. this.options_.disablePictureInPicture = value;
  21398. this.trigger('disablepictureinpicturechanged');
  21399. }
  21400. /**
  21401. * Check if the player is in Picture-in-Picture mode or tell the player that it
  21402. * is or is not in Picture-in-Picture mode.
  21403. *
  21404. * @param {boolean} [isPiP]
  21405. * Set the players current Picture-in-Picture state
  21406. *
  21407. * @return {boolean}
  21408. * - true if Picture-in-Picture is on and getting
  21409. * - false if Picture-in-Picture is off and getting
  21410. */
  21411. isInPictureInPicture(isPiP) {
  21412. if (isPiP !== undefined) {
  21413. this.isInPictureInPicture_ = !!isPiP;
  21414. this.togglePictureInPictureClass_();
  21415. return;
  21416. }
  21417. return !!this.isInPictureInPicture_;
  21418. }
  21419. /**
  21420. * Create a floating video window always on top of other windows so that users may
  21421. * continue consuming media while they interact with other content sites, or
  21422. * applications on their device.
  21423. *
  21424. * This can use document picture-in-picture or element picture in picture
  21425. *
  21426. * Set `enableDocumentPictureInPicture` to `true` to use docPiP on a supported browser
  21427. * Else set `disablePictureInPicture` to `false` to disable elPiP on a supported browser
  21428. *
  21429. *
  21430. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/}
  21431. * @see [Spec]{@link https://wicg.github.io/document-picture-in-picture/}
  21432. *
  21433. * @fires Player#enterpictureinpicture
  21434. *
  21435. * @return {Promise}
  21436. * A promise with a Picture-in-Picture window.
  21437. */
  21438. requestPictureInPicture() {
  21439. if (this.options_.enableDocumentPictureInPicture && window.documentPictureInPicture) {
  21440. const pipContainer = document.createElement(this.el().tagName);
  21441. pipContainer.classList = this.el().classList;
  21442. pipContainer.classList.add('vjs-pip-container');
  21443. if (this.posterImage) {
  21444. pipContainer.appendChild(this.posterImage.el().cloneNode(true));
  21445. }
  21446. if (this.titleBar) {
  21447. pipContainer.appendChild(this.titleBar.el().cloneNode(true));
  21448. }
  21449. pipContainer.appendChild(createEl('p', {
  21450. className: 'vjs-pip-text'
  21451. }, {}, this.localize('Playing in picture-in-picture')));
  21452. return window.documentPictureInPicture.requestWindow({
  21453. // The aspect ratio won't be correct, Chrome bug https://crbug.com/1407629
  21454. initialAspectRatio: this.videoWidth() / this.videoHeight(),
  21455. copyStyleSheets: true
  21456. }).then(pipWindow => {
  21457. this.el_.parentNode.insertBefore(pipContainer, this.el_);
  21458. pipWindow.document.body.append(this.el_);
  21459. pipWindow.document.body.classList.add('vjs-pip-window');
  21460. this.player_.isInPictureInPicture(true);
  21461. this.player_.trigger('enterpictureinpicture');
  21462. // Listen for the PiP closing event to move the video back.
  21463. pipWindow.addEventListener('unload', event => {
  21464. const pipVideo = event.target.querySelector('.video-js');
  21465. pipContainer.replaceWith(pipVideo);
  21466. this.player_.isInPictureInPicture(false);
  21467. this.player_.trigger('leavepictureinpicture');
  21468. });
  21469. return pipWindow;
  21470. });
  21471. }
  21472. if ('pictureInPictureEnabled' in document && this.disablePictureInPicture() === false) {
  21473. /**
  21474. * This event fires when the player enters picture in picture mode
  21475. *
  21476. * @event Player#enterpictureinpicture
  21477. * @type {Event}
  21478. */
  21479. return this.techGet_('requestPictureInPicture');
  21480. }
  21481. return Promise.reject('No PiP mode is available');
  21482. }
  21483. /**
  21484. * Exit Picture-in-Picture mode.
  21485. *
  21486. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  21487. *
  21488. * @fires Player#leavepictureinpicture
  21489. *
  21490. * @return {Promise}
  21491. * A promise.
  21492. */
  21493. exitPictureInPicture() {
  21494. if (window.documentPictureInPicture && window.documentPictureInPicture.window) {
  21495. // With documentPictureInPicture, Player#leavepictureinpicture is fired in the unload handler
  21496. window.documentPictureInPicture.window.close();
  21497. return Promise.resolve();
  21498. }
  21499. if ('pictureInPictureEnabled' in document) {
  21500. /**
  21501. * This event fires when the player leaves picture in picture mode
  21502. *
  21503. * @event Player#leavepictureinpicture
  21504. * @type {Event}
  21505. */
  21506. return document.exitPictureInPicture();
  21507. }
  21508. }
  21509. /**
  21510. * Called when this Player has focus and a key gets pressed down, or when
  21511. * any Component of this player receives a key press that it doesn't handle.
  21512. * This allows player-wide hotkeys (either as defined below, or optionally
  21513. * by an external function).
  21514. *
  21515. * @param {Event} event
  21516. * The `keydown` event that caused this function to be called.
  21517. *
  21518. * @listens keydown
  21519. */
  21520. handleKeyDown(event) {
  21521. const {
  21522. userActions
  21523. } = this.options_;
  21524. // Bail out if hotkeys are not configured.
  21525. if (!userActions || !userActions.hotkeys) {
  21526. return;
  21527. }
  21528. // Function that determines whether or not to exclude an element from
  21529. // hotkeys handling.
  21530. const excludeElement = el => {
  21531. const tagName = el.tagName.toLowerCase();
  21532. // The first and easiest test is for `contenteditable` elements.
  21533. if (el.isContentEditable) {
  21534. return true;
  21535. }
  21536. // Inputs matching these types will still trigger hotkey handling as
  21537. // they are not text inputs.
  21538. const allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];
  21539. if (tagName === 'input') {
  21540. return allowedInputTypes.indexOf(el.type) === -1;
  21541. }
  21542. // The final test is by tag name. These tags will be excluded entirely.
  21543. const excludedTags = ['textarea'];
  21544. return excludedTags.indexOf(tagName) !== -1;
  21545. };
  21546. // Bail out if the user is focused on an interactive form element.
  21547. if (excludeElement(this.el_.ownerDocument.activeElement)) {
  21548. return;
  21549. }
  21550. if (typeof userActions.hotkeys === 'function') {
  21551. userActions.hotkeys.call(this, event);
  21552. } else {
  21553. this.handleHotkeys(event);
  21554. }
  21555. }
  21556. /**
  21557. * Called when this Player receives a hotkey keydown event.
  21558. * Supported player-wide hotkeys are:
  21559. *
  21560. * f - toggle fullscreen
  21561. * m - toggle mute
  21562. * k or Space - toggle play/pause
  21563. *
  21564. * @param {Event} event
  21565. * The `keydown` event that caused this function to be called.
  21566. */
  21567. handleHotkeys(event) {
  21568. const hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {};
  21569. // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set
  21570. const {
  21571. fullscreenKey = keydownEvent => keycode.isEventKey(keydownEvent, 'f'),
  21572. muteKey = keydownEvent => keycode.isEventKey(keydownEvent, 'm'),
  21573. playPauseKey = keydownEvent => keycode.isEventKey(keydownEvent, 'k') || keycode.isEventKey(keydownEvent, 'Space')
  21574. } = hotkeys;
  21575. if (fullscreenKey.call(this, event)) {
  21576. event.preventDefault();
  21577. event.stopPropagation();
  21578. const FSToggle = Component$1.getComponent('FullscreenToggle');
  21579. if (document[this.fsApi_.fullscreenEnabled] !== false) {
  21580. FSToggle.prototype.handleClick.call(this, event);
  21581. }
  21582. } else if (muteKey.call(this, event)) {
  21583. event.preventDefault();
  21584. event.stopPropagation();
  21585. const MuteToggle = Component$1.getComponent('MuteToggle');
  21586. MuteToggle.prototype.handleClick.call(this, event);
  21587. } else if (playPauseKey.call(this, event)) {
  21588. event.preventDefault();
  21589. event.stopPropagation();
  21590. const PlayToggle = Component$1.getComponent('PlayToggle');
  21591. PlayToggle.prototype.handleClick.call(this, event);
  21592. }
  21593. }
  21594. /**
  21595. * Check whether the player can play a given mimetype
  21596. *
  21597. * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype
  21598. *
  21599. * @param {string} type
  21600. * The mimetype to check
  21601. *
  21602. * @return {string}
  21603. * 'probably', 'maybe', or '' (empty string)
  21604. */
  21605. canPlayType(type) {
  21606. let can;
  21607. // Loop through each playback technology in the options order
  21608. for (let i = 0, j = this.options_.techOrder; i < j.length; i++) {
  21609. const techName = j[i];
  21610. let tech = Tech.getTech(techName);
  21611. // Support old behavior of techs being registered as components.
  21612. // Remove once that deprecated behavior is removed.
  21613. if (!tech) {
  21614. tech = Component$1.getComponent(techName);
  21615. }
  21616. // Check if the current tech is defined before continuing
  21617. if (!tech) {
  21618. log$1.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  21619. continue;
  21620. }
  21621. // Check if the browser supports this technology
  21622. if (tech.isSupported()) {
  21623. can = tech.canPlayType(type);
  21624. if (can) {
  21625. return can;
  21626. }
  21627. }
  21628. }
  21629. return '';
  21630. }
  21631. /**
  21632. * Select source based on tech-order or source-order
  21633. * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
  21634. * defaults to tech-order selection
  21635. *
  21636. * @param {Array} sources
  21637. * The sources for a media asset
  21638. *
  21639. * @return {Object|boolean}
  21640. * Object of source and tech order or false
  21641. */
  21642. selectSource(sources) {
  21643. // Get only the techs specified in `techOrder` that exist and are supported by the
  21644. // current platform
  21645. const techs = this.options_.techOrder.map(techName => {
  21646. return [techName, Tech.getTech(techName)];
  21647. }).filter(([techName, tech]) => {
  21648. // Check if the current tech is defined before continuing
  21649. if (tech) {
  21650. // Check if the browser supports this technology
  21651. return tech.isSupported();
  21652. }
  21653. log$1.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  21654. return false;
  21655. });
  21656. // Iterate over each `innerArray` element once per `outerArray` element and execute
  21657. // `tester` with both. If `tester` returns a non-falsy value, exit early and return
  21658. // that value.
  21659. const findFirstPassingTechSourcePair = function (outerArray, innerArray, tester) {
  21660. let found;
  21661. outerArray.some(outerChoice => {
  21662. return innerArray.some(innerChoice => {
  21663. found = tester(outerChoice, innerChoice);
  21664. if (found) {
  21665. return true;
  21666. }
  21667. });
  21668. });
  21669. return found;
  21670. };
  21671. let foundSourceAndTech;
  21672. const flip = fn => (a, b) => fn(b, a);
  21673. const finder = ([techName, tech], source) => {
  21674. if (tech.canPlaySource(source, this.options_[techName.toLowerCase()])) {
  21675. return {
  21676. source,
  21677. tech: techName
  21678. };
  21679. }
  21680. };
  21681. // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
  21682. // to select from them based on their priority.
  21683. if (this.options_.sourceOrder) {
  21684. // Source-first ordering
  21685. foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
  21686. } else {
  21687. // Tech-first ordering
  21688. foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
  21689. }
  21690. return foundSourceAndTech || false;
  21691. }
  21692. /**
  21693. * Executes source setting and getting logic
  21694. *
  21695. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  21696. * A SourceObject, an array of SourceObjects, or a string referencing
  21697. * a URL to a media source. It is _highly recommended_ that an object
  21698. * or array of objects is used here, so that source selection
  21699. * algorithms can take the `type` into account.
  21700. *
  21701. * If not provided, this method acts as a getter.
  21702. * @param {boolean} isRetry
  21703. * Indicates whether this is being called internally as a result of a retry
  21704. *
  21705. * @return {string|undefined}
  21706. * If the `source` argument is missing, returns the current source
  21707. * URL. Otherwise, returns nothing/undefined.
  21708. */
  21709. handleSrc_(source, isRetry) {
  21710. // getter usage
  21711. if (typeof source === 'undefined') {
  21712. return this.cache_.src || '';
  21713. }
  21714. // Reset retry behavior for new source
  21715. if (this.resetRetryOnError_) {
  21716. this.resetRetryOnError_();
  21717. }
  21718. // filter out invalid sources and turn our source into
  21719. // an array of source objects
  21720. const sources = filterSource(source);
  21721. // if a source was passed in then it is invalid because
  21722. // it was filtered to a zero length Array. So we have to
  21723. // show an error
  21724. if (!sources.length) {
  21725. this.setTimeout(function () {
  21726. this.error({
  21727. code: 4,
  21728. message: this.options_.notSupportedMessage
  21729. });
  21730. }, 0);
  21731. return;
  21732. }
  21733. // initial sources
  21734. this.changingSrc_ = true;
  21735. // Only update the cached source list if we are not retrying a new source after error,
  21736. // since in that case we want to include the failed source(s) in the cache
  21737. if (!isRetry) {
  21738. this.cache_.sources = sources;
  21739. }
  21740. this.updateSourceCaches_(sources[0]);
  21741. // middlewareSource is the source after it has been changed by middleware
  21742. setSource(this, sources[0], (middlewareSource, mws) => {
  21743. this.middleware_ = mws;
  21744. // since sourceSet is async we have to update the cache again after we select a source since
  21745. // the source that is selected could be out of order from the cache update above this callback.
  21746. if (!isRetry) {
  21747. this.cache_.sources = sources;
  21748. }
  21749. this.updateSourceCaches_(middlewareSource);
  21750. const err = this.src_(middlewareSource);
  21751. if (err) {
  21752. if (sources.length > 1) {
  21753. return this.handleSrc_(sources.slice(1));
  21754. }
  21755. this.changingSrc_ = false;
  21756. // We need to wrap this in a timeout to give folks a chance to add error event handlers
  21757. this.setTimeout(function () {
  21758. this.error({
  21759. code: 4,
  21760. message: this.options_.notSupportedMessage
  21761. });
  21762. }, 0);
  21763. // we could not find an appropriate tech, but let's still notify the delegate that this is it
  21764. // this needs a better comment about why this is needed
  21765. this.triggerReady();
  21766. return;
  21767. }
  21768. setTech(mws, this.tech_);
  21769. });
  21770. // Try another available source if this one fails before playback.
  21771. if (sources.length > 1) {
  21772. const retry = () => {
  21773. // Remove the error modal
  21774. this.error(null);
  21775. this.handleSrc_(sources.slice(1), true);
  21776. };
  21777. const stopListeningForErrors = () => {
  21778. this.off('error', retry);
  21779. };
  21780. this.one('error', retry);
  21781. this.one('playing', stopListeningForErrors);
  21782. this.resetRetryOnError_ = () => {
  21783. this.off('error', retry);
  21784. this.off('playing', stopListeningForErrors);
  21785. };
  21786. }
  21787. }
  21788. /**
  21789. * Get or set the video source.
  21790. *
  21791. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  21792. * A SourceObject, an array of SourceObjects, or a string referencing
  21793. * a URL to a media source. It is _highly recommended_ that an object
  21794. * or array of objects is used here, so that source selection
  21795. * algorithms can take the `type` into account.
  21796. *
  21797. * If not provided, this method acts as a getter.
  21798. *
  21799. * @return {string|undefined}
  21800. * If the `source` argument is missing, returns the current source
  21801. * URL. Otherwise, returns nothing/undefined.
  21802. */
  21803. src(source) {
  21804. return this.handleSrc_(source, false);
  21805. }
  21806. /**
  21807. * Set the source object on the tech, returns a boolean that indicates whether
  21808. * there is a tech that can play the source or not
  21809. *
  21810. * @param {Tech~SourceObject} source
  21811. * The source object to set on the Tech
  21812. *
  21813. * @return {boolean}
  21814. * - True if there is no Tech to playback this source
  21815. * - False otherwise
  21816. *
  21817. * @private
  21818. */
  21819. src_(source) {
  21820. const sourceTech = this.selectSource([source]);
  21821. if (!sourceTech) {
  21822. return true;
  21823. }
  21824. if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
  21825. this.changingSrc_ = true;
  21826. // load this technology with the chosen source
  21827. this.loadTech_(sourceTech.tech, sourceTech.source);
  21828. this.tech_.ready(() => {
  21829. this.changingSrc_ = false;
  21830. });
  21831. return false;
  21832. }
  21833. // wait until the tech is ready to set the source
  21834. // and set it synchronously if possible (#2326)
  21835. this.ready(function () {
  21836. // The setSource tech method was added with source handlers
  21837. // so older techs won't support it
  21838. // We need to check the direct prototype for the case where subclasses
  21839. // of the tech do not support source handlers
  21840. if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {
  21841. this.techCall_('setSource', source);
  21842. } else {
  21843. this.techCall_('src', source.src);
  21844. }
  21845. this.changingSrc_ = false;
  21846. }, true);
  21847. return false;
  21848. }
  21849. /**
  21850. * Begin loading the src data.
  21851. */
  21852. load() {
  21853. this.techCall_('load');
  21854. }
  21855. /**
  21856. * Reset the player. Loads the first tech in the techOrder,
  21857. * removes all the text tracks in the existing `tech`,
  21858. * and calls `reset` on the `tech`.
  21859. */
  21860. reset() {
  21861. if (this.paused()) {
  21862. this.doReset_();
  21863. } else {
  21864. const playPromise = this.play();
  21865. silencePromise(playPromise.then(() => this.doReset_()));
  21866. }
  21867. }
  21868. doReset_() {
  21869. if (this.tech_) {
  21870. this.tech_.clearTracks('text');
  21871. }
  21872. this.resetCache_();
  21873. this.poster('');
  21874. this.loadTech_(this.options_.techOrder[0], null);
  21875. this.techCall_('reset');
  21876. this.resetControlBarUI_();
  21877. if (isEvented(this)) {
  21878. this.trigger('playerreset');
  21879. }
  21880. }
  21881. /**
  21882. * Reset Control Bar's UI by calling sub-methods that reset
  21883. * all of Control Bar's components
  21884. */
  21885. resetControlBarUI_() {
  21886. this.resetProgressBar_();
  21887. this.resetPlaybackRate_();
  21888. this.resetVolumeBar_();
  21889. }
  21890. /**
  21891. * Reset tech's progress so progress bar is reset in the UI
  21892. */
  21893. resetProgressBar_() {
  21894. this.currentTime(0);
  21895. const {
  21896. currentTimeDisplay,
  21897. durationDisplay,
  21898. progressControl,
  21899. remainingTimeDisplay
  21900. } = this.controlBar || {};
  21901. const {
  21902. seekBar
  21903. } = progressControl || {};
  21904. if (currentTimeDisplay) {
  21905. currentTimeDisplay.updateContent();
  21906. }
  21907. if (durationDisplay) {
  21908. durationDisplay.updateContent();
  21909. }
  21910. if (remainingTimeDisplay) {
  21911. remainingTimeDisplay.updateContent();
  21912. }
  21913. if (seekBar) {
  21914. seekBar.update();
  21915. if (seekBar.loadProgressBar) {
  21916. seekBar.loadProgressBar.update();
  21917. }
  21918. }
  21919. }
  21920. /**
  21921. * Reset Playback ratio
  21922. */
  21923. resetPlaybackRate_() {
  21924. this.playbackRate(this.defaultPlaybackRate());
  21925. this.handleTechRateChange_();
  21926. }
  21927. /**
  21928. * Reset Volume bar
  21929. */
  21930. resetVolumeBar_() {
  21931. this.volume(1.0);
  21932. this.trigger('volumechange');
  21933. }
  21934. /**
  21935. * Returns all of the current source objects.
  21936. *
  21937. * @return {Tech~SourceObject[]}
  21938. * The current source objects
  21939. */
  21940. currentSources() {
  21941. const source = this.currentSource();
  21942. const sources = [];
  21943. // assume `{}` or `{ src }`
  21944. if (Object.keys(source).length !== 0) {
  21945. sources.push(source);
  21946. }
  21947. return this.cache_.sources || sources;
  21948. }
  21949. /**
  21950. * Returns the current source object.
  21951. *
  21952. * @return {Tech~SourceObject}
  21953. * The current source object
  21954. */
  21955. currentSource() {
  21956. return this.cache_.source || {};
  21957. }
  21958. /**
  21959. * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
  21960. * Can be used in conjunction with `currentType` to assist in rebuilding the current source object.
  21961. *
  21962. * @return {string}
  21963. * The current source
  21964. */
  21965. currentSrc() {
  21966. return this.currentSource() && this.currentSource().src || '';
  21967. }
  21968. /**
  21969. * Get the current source type e.g. video/mp4
  21970. * This can allow you rebuild the current source object so that you could load the same
  21971. * source and tech later
  21972. *
  21973. * @return {string}
  21974. * The source MIME type
  21975. */
  21976. currentType() {
  21977. return this.currentSource() && this.currentSource().type || '';
  21978. }
  21979. /**
  21980. * Get or set the preload attribute
  21981. *
  21982. * @param {boolean} [value]
  21983. * - true means that we should preload
  21984. * - false means that we should not preload
  21985. *
  21986. * @return {string}
  21987. * The preload attribute value when getting
  21988. */
  21989. preload(value) {
  21990. if (value !== undefined) {
  21991. this.techCall_('setPreload', value);
  21992. this.options_.preload = value;
  21993. return;
  21994. }
  21995. return this.techGet_('preload');
  21996. }
  21997. /**
  21998. * Get or set the autoplay option. When this is a boolean it will
  21999. * modify the attribute on the tech. When this is a string the attribute on
  22000. * the tech will be removed and `Player` will handle autoplay on loadstarts.
  22001. *
  22002. * @param {boolean|string} [value]
  22003. * - true: autoplay using the browser behavior
  22004. * - false: do not autoplay
  22005. * - 'play': call play() on every loadstart
  22006. * - 'muted': call muted() then play() on every loadstart
  22007. * - 'any': call play() on every loadstart. if that fails call muted() then play().
  22008. * - *: values other than those listed here will be set `autoplay` to true
  22009. *
  22010. * @return {boolean|string}
  22011. * The current value of autoplay when getting
  22012. */
  22013. autoplay(value) {
  22014. // getter usage
  22015. if (value === undefined) {
  22016. return this.options_.autoplay || false;
  22017. }
  22018. let techAutoplay;
  22019. // if the value is a valid string set it to that, or normalize `true` to 'play', if need be
  22020. if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {
  22021. this.options_.autoplay = value;
  22022. this.manualAutoplay_(typeof value === 'string' ? value : 'play');
  22023. techAutoplay = false;
  22024. // any falsy value sets autoplay to false in the browser,
  22025. // lets do the same
  22026. } else if (!value) {
  22027. this.options_.autoplay = false;
  22028. // any other value (ie truthy) sets autoplay to true
  22029. } else {
  22030. this.options_.autoplay = true;
  22031. }
  22032. techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay;
  22033. // if we don't have a tech then we do not queue up
  22034. // a setAutoplay call on tech ready. We do this because the
  22035. // autoplay option will be passed in the constructor and we
  22036. // do not need to set it twice
  22037. if (this.tech_) {
  22038. this.techCall_('setAutoplay', techAutoplay);
  22039. }
  22040. }
  22041. /**
  22042. * Set or unset the playsinline attribute.
  22043. * Playsinline tells the browser that non-fullscreen playback is preferred.
  22044. *
  22045. * @param {boolean} [value]
  22046. * - true means that we should try to play inline by default
  22047. * - false means that we should use the browser's default playback mode,
  22048. * which in most cases is inline. iOS Safari is a notable exception
  22049. * and plays fullscreen by default.
  22050. *
  22051. * @return {string|Player}
  22052. * - the current value of playsinline
  22053. * - the player when setting
  22054. *
  22055. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  22056. */
  22057. playsinline(value) {
  22058. if (value !== undefined) {
  22059. this.techCall_('setPlaysinline', value);
  22060. this.options_.playsinline = value;
  22061. return this;
  22062. }
  22063. return this.techGet_('playsinline');
  22064. }
  22065. /**
  22066. * Get or set the loop attribute on the video element.
  22067. *
  22068. * @param {boolean} [value]
  22069. * - true means that we should loop the video
  22070. * - false means that we should not loop the video
  22071. *
  22072. * @return {boolean}
  22073. * The current value of loop when getting
  22074. */
  22075. loop(value) {
  22076. if (value !== undefined) {
  22077. this.techCall_('setLoop', value);
  22078. this.options_.loop = value;
  22079. return;
  22080. }
  22081. return this.techGet_('loop');
  22082. }
  22083. /**
  22084. * Get or set the poster image source url
  22085. *
  22086. * @fires Player#posterchange
  22087. *
  22088. * @param {string} [src]
  22089. * Poster image source URL
  22090. *
  22091. * @return {string}
  22092. * The current value of poster when getting
  22093. */
  22094. poster(src) {
  22095. if (src === undefined) {
  22096. return this.poster_;
  22097. }
  22098. // The correct way to remove a poster is to set as an empty string
  22099. // other falsey values will throw errors
  22100. if (!src) {
  22101. src = '';
  22102. }
  22103. if (src === this.poster_) {
  22104. return;
  22105. }
  22106. // update the internal poster variable
  22107. this.poster_ = src;
  22108. // update the tech's poster
  22109. this.techCall_('setPoster', src);
  22110. this.isPosterFromTech_ = false;
  22111. // alert components that the poster has been set
  22112. /**
  22113. * This event fires when the poster image is changed on the player.
  22114. *
  22115. * @event Player#posterchange
  22116. * @type {Event}
  22117. */
  22118. this.trigger('posterchange');
  22119. }
  22120. /**
  22121. * Some techs (e.g. YouTube) can provide a poster source in an
  22122. * asynchronous way. We want the poster component to use this
  22123. * poster source so that it covers up the tech's controls.
  22124. * (YouTube's play button). However we only want to use this
  22125. * source if the player user hasn't set a poster through
  22126. * the normal APIs.
  22127. *
  22128. * @fires Player#posterchange
  22129. * @listens Tech#posterchange
  22130. * @private
  22131. */
  22132. handleTechPosterChange_() {
  22133. if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
  22134. const newPoster = this.tech_.poster() || '';
  22135. if (newPoster !== this.poster_) {
  22136. this.poster_ = newPoster;
  22137. this.isPosterFromTech_ = true;
  22138. // Let components know the poster has changed
  22139. this.trigger('posterchange');
  22140. }
  22141. }
  22142. }
  22143. /**
  22144. * Get or set whether or not the controls are showing.
  22145. *
  22146. * @fires Player#controlsenabled
  22147. *
  22148. * @param {boolean} [bool]
  22149. * - true to turn controls on
  22150. * - false to turn controls off
  22151. *
  22152. * @return {boolean}
  22153. * The current value of controls when getting
  22154. */
  22155. controls(bool) {
  22156. if (bool === undefined) {
  22157. return !!this.controls_;
  22158. }
  22159. bool = !!bool;
  22160. // Don't trigger a change event unless it actually changed
  22161. if (this.controls_ === bool) {
  22162. return;
  22163. }
  22164. this.controls_ = bool;
  22165. if (this.usingNativeControls()) {
  22166. this.techCall_('setControls', bool);
  22167. }
  22168. if (this.controls_) {
  22169. this.removeClass('vjs-controls-disabled');
  22170. this.addClass('vjs-controls-enabled');
  22171. /**
  22172. * @event Player#controlsenabled
  22173. * @type {Event}
  22174. */
  22175. this.trigger('controlsenabled');
  22176. if (!this.usingNativeControls()) {
  22177. this.addTechControlsListeners_();
  22178. }
  22179. } else {
  22180. this.removeClass('vjs-controls-enabled');
  22181. this.addClass('vjs-controls-disabled');
  22182. /**
  22183. * @event Player#controlsdisabled
  22184. * @type {Event}
  22185. */
  22186. this.trigger('controlsdisabled');
  22187. if (!this.usingNativeControls()) {
  22188. this.removeTechControlsListeners_();
  22189. }
  22190. }
  22191. }
  22192. /**
  22193. * Toggle native controls on/off. Native controls are the controls built into
  22194. * devices (e.g. default iPhone controls) or other techs
  22195. * (e.g. Vimeo Controls)
  22196. * **This should only be set by the current tech, because only the tech knows
  22197. * if it can support native controls**
  22198. *
  22199. * @fires Player#usingnativecontrols
  22200. * @fires Player#usingcustomcontrols
  22201. *
  22202. * @param {boolean} [bool]
  22203. * - true to turn native controls on
  22204. * - false to turn native controls off
  22205. *
  22206. * @return {boolean}
  22207. * The current value of native controls when getting
  22208. */
  22209. usingNativeControls(bool) {
  22210. if (bool === undefined) {
  22211. return !!this.usingNativeControls_;
  22212. }
  22213. bool = !!bool;
  22214. // Don't trigger a change event unless it actually changed
  22215. if (this.usingNativeControls_ === bool) {
  22216. return;
  22217. }
  22218. this.usingNativeControls_ = bool;
  22219. if (this.usingNativeControls_) {
  22220. this.addClass('vjs-using-native-controls');
  22221. /**
  22222. * player is using the native device controls
  22223. *
  22224. * @event Player#usingnativecontrols
  22225. * @type {Event}
  22226. */
  22227. this.trigger('usingnativecontrols');
  22228. } else {
  22229. this.removeClass('vjs-using-native-controls');
  22230. /**
  22231. * player is using the custom HTML controls
  22232. *
  22233. * @event Player#usingcustomcontrols
  22234. * @type {Event}
  22235. */
  22236. this.trigger('usingcustomcontrols');
  22237. }
  22238. }
  22239. /**
  22240. * Set or get the current MediaError
  22241. *
  22242. * @fires Player#error
  22243. *
  22244. * @param {MediaError|string|number} [err]
  22245. * A MediaError or a string/number to be turned
  22246. * into a MediaError
  22247. *
  22248. * @return {MediaError|null}
  22249. * The current MediaError when getting (or null)
  22250. */
  22251. error(err) {
  22252. if (err === undefined) {
  22253. return this.error_ || null;
  22254. }
  22255. // allow hooks to modify error object
  22256. hooks('beforeerror').forEach(hookFunction => {
  22257. const newErr = hookFunction(this, err);
  22258. if (!(isObject$1(newErr) && !Array.isArray(newErr) || typeof newErr === 'string' || typeof newErr === 'number' || newErr === null)) {
  22259. this.log.error('please return a value that MediaError expects in beforeerror hooks');
  22260. return;
  22261. }
  22262. err = newErr;
  22263. });
  22264. // Suppress the first error message for no compatible source until
  22265. // user interaction
  22266. if (this.options_.suppressNotSupportedError && err && err.code === 4) {
  22267. const triggerSuppressedError = function () {
  22268. this.error(err);
  22269. };
  22270. this.options_.suppressNotSupportedError = false;
  22271. this.any(['click', 'touchstart'], triggerSuppressedError);
  22272. this.one('loadstart', function () {
  22273. this.off(['click', 'touchstart'], triggerSuppressedError);
  22274. });
  22275. return;
  22276. }
  22277. // restoring to default
  22278. if (err === null) {
  22279. this.error_ = err;
  22280. this.removeClass('vjs-error');
  22281. if (this.errorDisplay) {
  22282. this.errorDisplay.close();
  22283. }
  22284. return;
  22285. }
  22286. this.error_ = new MediaError(err);
  22287. // add the vjs-error classname to the player
  22288. this.addClass('vjs-error');
  22289. // log the name of the error type and any message
  22290. // IE11 logs "[object object]" and required you to expand message to see error object
  22291. log$1.error(`(CODE:${this.error_.code} ${MediaError.errorTypes[this.error_.code]})`, this.error_.message, this.error_);
  22292. /**
  22293. * @event Player#error
  22294. * @type {Event}
  22295. */
  22296. this.trigger('error');
  22297. // notify hooks of the per player error
  22298. hooks('error').forEach(hookFunction => hookFunction(this, this.error_));
  22299. return;
  22300. }
  22301. /**
  22302. * Report user activity
  22303. *
  22304. * @param {Object} event
  22305. * Event object
  22306. */
  22307. reportUserActivity(event) {
  22308. this.userActivity_ = true;
  22309. }
  22310. /**
  22311. * Get/set if user is active
  22312. *
  22313. * @fires Player#useractive
  22314. * @fires Player#userinactive
  22315. *
  22316. * @param {boolean} [bool]
  22317. * - true if the user is active
  22318. * - false if the user is inactive
  22319. *
  22320. * @return {boolean}
  22321. * The current value of userActive when getting
  22322. */
  22323. userActive(bool) {
  22324. if (bool === undefined) {
  22325. return this.userActive_;
  22326. }
  22327. bool = !!bool;
  22328. if (bool === this.userActive_) {
  22329. return;
  22330. }
  22331. this.userActive_ = bool;
  22332. if (this.userActive_) {
  22333. this.userActivity_ = true;
  22334. this.removeClass('vjs-user-inactive');
  22335. this.addClass('vjs-user-active');
  22336. /**
  22337. * @event Player#useractive
  22338. * @type {Event}
  22339. */
  22340. this.trigger('useractive');
  22341. return;
  22342. }
  22343. // Chrome/Safari/IE have bugs where when you change the cursor it can
  22344. // trigger a mousemove event. This causes an issue when you're hiding
  22345. // the cursor when the user is inactive, and a mousemove signals user
  22346. // activity. Making it impossible to go into inactive mode. Specifically
  22347. // this happens in fullscreen when we really need to hide the cursor.
  22348. //
  22349. // When this gets resolved in ALL browsers it can be removed
  22350. // https://code.google.com/p/chromium/issues/detail?id=103041
  22351. if (this.tech_) {
  22352. this.tech_.one('mousemove', function (e) {
  22353. e.stopPropagation();
  22354. e.preventDefault();
  22355. });
  22356. }
  22357. this.userActivity_ = false;
  22358. this.removeClass('vjs-user-active');
  22359. this.addClass('vjs-user-inactive');
  22360. /**
  22361. * @event Player#userinactive
  22362. * @type {Event}
  22363. */
  22364. this.trigger('userinactive');
  22365. }
  22366. /**
  22367. * Listen for user activity based on timeout value
  22368. *
  22369. * @private
  22370. */
  22371. listenForUserActivity_() {
  22372. let mouseInProgress;
  22373. let lastMoveX;
  22374. let lastMoveY;
  22375. const handleActivity = bind_(this, this.reportUserActivity);
  22376. const handleMouseMove = function (e) {
  22377. // #1068 - Prevent mousemove spamming
  22378. // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
  22379. if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
  22380. lastMoveX = e.screenX;
  22381. lastMoveY = e.screenY;
  22382. handleActivity();
  22383. }
  22384. };
  22385. const handleMouseDown = function () {
  22386. handleActivity();
  22387. // For as long as the they are touching the device or have their mouse down,
  22388. // we consider them active even if they're not moving their finger or mouse.
  22389. // So we want to continue to update that they are active
  22390. this.clearInterval(mouseInProgress);
  22391. // Setting userActivity=true now and setting the interval to the same time
  22392. // as the activityCheck interval (250) should ensure we never miss the
  22393. // next activityCheck
  22394. mouseInProgress = this.setInterval(handleActivity, 250);
  22395. };
  22396. const handleMouseUpAndMouseLeave = function (event) {
  22397. handleActivity();
  22398. // Stop the interval that maintains activity if the mouse/touch is down
  22399. this.clearInterval(mouseInProgress);
  22400. };
  22401. // Any mouse movement will be considered user activity
  22402. this.on('mousedown', handleMouseDown);
  22403. this.on('mousemove', handleMouseMove);
  22404. this.on('mouseup', handleMouseUpAndMouseLeave);
  22405. this.on('mouseleave', handleMouseUpAndMouseLeave);
  22406. const controlBar = this.getChild('controlBar');
  22407. // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed)
  22408. // controlBar would no longer be hidden by default timeout.
  22409. if (controlBar && !IS_IOS && !IS_ANDROID) {
  22410. controlBar.on('mouseenter', function (event) {
  22411. if (this.player().options_.inactivityTimeout !== 0) {
  22412. this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;
  22413. }
  22414. this.player().options_.inactivityTimeout = 0;
  22415. });
  22416. controlBar.on('mouseleave', function (event) {
  22417. this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;
  22418. });
  22419. }
  22420. // Listen for keyboard navigation
  22421. // Shouldn't need to use inProgress interval because of key repeat
  22422. this.on('keydown', handleActivity);
  22423. this.on('keyup', handleActivity);
  22424. // Run an interval every 250 milliseconds instead of stuffing everything into
  22425. // the mousemove/touchmove function itself, to prevent performance degradation.
  22426. // `this.reportUserActivity` simply sets this.userActivity_ to true, which
  22427. // then gets picked up by this loop
  22428. // http://ejohn.org/blog/learning-from-twitter/
  22429. let inactivityTimeout;
  22430. this.setInterval(function () {
  22431. // Check to see if mouse/touch activity has happened
  22432. if (!this.userActivity_) {
  22433. return;
  22434. }
  22435. // Reset the activity tracker
  22436. this.userActivity_ = false;
  22437. // If the user state was inactive, set the state to active
  22438. this.userActive(true);
  22439. // Clear any existing inactivity timeout to start the timer over
  22440. this.clearTimeout(inactivityTimeout);
  22441. const timeout = this.options_.inactivityTimeout;
  22442. if (timeout <= 0) {
  22443. return;
  22444. }
  22445. // In <timeout> milliseconds, if no more activity has occurred the
  22446. // user will be considered inactive
  22447. inactivityTimeout = this.setTimeout(function () {
  22448. // Protect against the case where the inactivityTimeout can trigger just
  22449. // before the next user activity is picked up by the activity check loop
  22450. // causing a flicker
  22451. if (!this.userActivity_) {
  22452. this.userActive(false);
  22453. }
  22454. }, timeout);
  22455. }, 250);
  22456. }
  22457. /**
  22458. * Gets or sets the current playback rate. A playback rate of
  22459. * 1.0 represents normal speed and 0.5 would indicate half-speed
  22460. * playback, for instance.
  22461. *
  22462. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
  22463. *
  22464. * @param {number} [rate]
  22465. * New playback rate to set.
  22466. *
  22467. * @return {number}
  22468. * The current playback rate when getting or 1.0
  22469. */
  22470. playbackRate(rate) {
  22471. if (rate !== undefined) {
  22472. // NOTE: this.cache_.lastPlaybackRate is set from the tech handler
  22473. // that is registered above
  22474. this.techCall_('setPlaybackRate', rate);
  22475. return;
  22476. }
  22477. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  22478. return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');
  22479. }
  22480. return 1.0;
  22481. }
  22482. /**
  22483. * Gets or sets the current default playback rate. A default playback rate of
  22484. * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
  22485. * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not
  22486. * not the current playbackRate.
  22487. *
  22488. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
  22489. *
  22490. * @param {number} [rate]
  22491. * New default playback rate to set.
  22492. *
  22493. * @return {number|Player}
  22494. * - The default playback rate when getting or 1.0
  22495. * - the player when setting
  22496. */
  22497. defaultPlaybackRate(rate) {
  22498. if (rate !== undefined) {
  22499. return this.techCall_('setDefaultPlaybackRate', rate);
  22500. }
  22501. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  22502. return this.techGet_('defaultPlaybackRate');
  22503. }
  22504. return 1.0;
  22505. }
  22506. /**
  22507. * Gets or sets the audio flag
  22508. *
  22509. * @param {boolean} bool
  22510. * - true signals that this is an audio player
  22511. * - false signals that this is not an audio player
  22512. *
  22513. * @return {boolean}
  22514. * The current value of isAudio when getting
  22515. */
  22516. isAudio(bool) {
  22517. if (bool !== undefined) {
  22518. this.isAudio_ = !!bool;
  22519. return;
  22520. }
  22521. return !!this.isAudio_;
  22522. }
  22523. enableAudioOnlyUI_() {
  22524. // Update styling immediately to show the control bar so we can get its height
  22525. this.addClass('vjs-audio-only-mode');
  22526. const playerChildren = this.children();
  22527. const controlBar = this.getChild('ControlBar');
  22528. const controlBarHeight = controlBar && controlBar.currentHeight();
  22529. // Hide all player components except the control bar. Control bar components
  22530. // needed only for video are hidden with CSS
  22531. playerChildren.forEach(child => {
  22532. if (child === controlBar) {
  22533. return;
  22534. }
  22535. if (child.el_ && !child.hasClass('vjs-hidden')) {
  22536. child.hide();
  22537. this.audioOnlyCache_.hiddenChildren.push(child);
  22538. }
  22539. });
  22540. this.audioOnlyCache_.playerHeight = this.currentHeight();
  22541. // Set the player height the same as the control bar
  22542. this.height(controlBarHeight);
  22543. this.trigger('audioonlymodechange');
  22544. }
  22545. disableAudioOnlyUI_() {
  22546. this.removeClass('vjs-audio-only-mode');
  22547. // Show player components that were previously hidden
  22548. this.audioOnlyCache_.hiddenChildren.forEach(child => child.show());
  22549. // Reset player height
  22550. this.height(this.audioOnlyCache_.playerHeight);
  22551. this.trigger('audioonlymodechange');
  22552. }
  22553. /**
  22554. * Get the current audioOnlyMode state or set audioOnlyMode to true or false.
  22555. *
  22556. * Setting this to `true` will hide all player components except the control bar,
  22557. * as well as control bar components needed only for video.
  22558. *
  22559. * @param {boolean} [value]
  22560. * The value to set audioOnlyMode to.
  22561. *
  22562. * @return {Promise|boolean}
  22563. * A Promise is returned when setting the state, and a boolean when getting
  22564. * the present state
  22565. */
  22566. audioOnlyMode(value) {
  22567. if (typeof value !== 'boolean' || value === this.audioOnlyMode_) {
  22568. return this.audioOnlyMode_;
  22569. }
  22570. this.audioOnlyMode_ = value;
  22571. // Enable Audio Only Mode
  22572. if (value) {
  22573. const exitPromises = [];
  22574. // Fullscreen and PiP are not supported in audioOnlyMode, so exit if we need to.
  22575. if (this.isInPictureInPicture()) {
  22576. exitPromises.push(this.exitPictureInPicture());
  22577. }
  22578. if (this.isFullscreen()) {
  22579. exitPromises.push(this.exitFullscreen());
  22580. }
  22581. if (this.audioPosterMode()) {
  22582. exitPromises.push(this.audioPosterMode(false));
  22583. }
  22584. return Promise.all(exitPromises).then(() => this.enableAudioOnlyUI_());
  22585. }
  22586. // Disable Audio Only Mode
  22587. return Promise.resolve().then(() => this.disableAudioOnlyUI_());
  22588. }
  22589. enablePosterModeUI_() {
  22590. // Hide the video element and show the poster image to enable posterModeUI
  22591. const tech = this.tech_ && this.tech_;
  22592. tech.hide();
  22593. this.addClass('vjs-audio-poster-mode');
  22594. this.trigger('audiopostermodechange');
  22595. }
  22596. disablePosterModeUI_() {
  22597. // Show the video element and hide the poster image to disable posterModeUI
  22598. const tech = this.tech_ && this.tech_;
  22599. tech.show();
  22600. this.removeClass('vjs-audio-poster-mode');
  22601. this.trigger('audiopostermodechange');
  22602. }
  22603. /**
  22604. * Get the current audioPosterMode state or set audioPosterMode to true or false
  22605. *
  22606. * @param {boolean} [value]
  22607. * The value to set audioPosterMode to.
  22608. *
  22609. * @return {Promise|boolean}
  22610. * A Promise is returned when setting the state, and a boolean when getting
  22611. * the present state
  22612. */
  22613. audioPosterMode(value) {
  22614. if (typeof value !== 'boolean' || value === this.audioPosterMode_) {
  22615. return this.audioPosterMode_;
  22616. }
  22617. this.audioPosterMode_ = value;
  22618. if (value) {
  22619. if (this.audioOnlyMode()) {
  22620. const audioOnlyModePromise = this.audioOnlyMode(false);
  22621. return audioOnlyModePromise.then(() => {
  22622. // enable audio poster mode after audio only mode is disabled
  22623. this.enablePosterModeUI_();
  22624. });
  22625. }
  22626. return Promise.resolve().then(() => {
  22627. // enable audio poster mode
  22628. this.enablePosterModeUI_();
  22629. });
  22630. }
  22631. return Promise.resolve().then(() => {
  22632. // disable audio poster mode
  22633. this.disablePosterModeUI_();
  22634. });
  22635. }
  22636. /**
  22637. * A helper method for adding a {@link TextTrack} to our
  22638. * {@link TextTrackList}.
  22639. *
  22640. * In addition to the W3C settings we allow adding additional info through options.
  22641. *
  22642. * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
  22643. *
  22644. * @param {string} [kind]
  22645. * the kind of TextTrack you are adding
  22646. *
  22647. * @param {string} [label]
  22648. * the label to give the TextTrack label
  22649. *
  22650. * @param {string} [language]
  22651. * the language to set on the TextTrack
  22652. *
  22653. * @return {TextTrack|undefined}
  22654. * the TextTrack that was added or undefined
  22655. * if there is no tech
  22656. */
  22657. addTextTrack(kind, label, language) {
  22658. if (this.tech_) {
  22659. return this.tech_.addTextTrack(kind, label, language);
  22660. }
  22661. }
  22662. /**
  22663. * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}.
  22664. *
  22665. * @param {Object} options
  22666. * Options to pass to {@link HTMLTrackElement} during creation. See
  22667. * {@link HTMLTrackElement} for object properties that you should use.
  22668. *
  22669. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack will not be removed
  22670. * from the TextTrackList and HtmlTrackElementList
  22671. * after a source change
  22672. *
  22673. * @return { import('./tracks/html-track-element').default }
  22674. * the HTMLTrackElement that was created and added
  22675. * to the HtmlTrackElementList and the remote
  22676. * TextTrackList
  22677. *
  22678. */
  22679. addRemoteTextTrack(options, manualCleanup) {
  22680. if (this.tech_) {
  22681. return this.tech_.addRemoteTextTrack(options, manualCleanup);
  22682. }
  22683. }
  22684. /**
  22685. * Remove a remote {@link TextTrack} from the respective
  22686. * {@link TextTrackList} and {@link HtmlTrackElementList}.
  22687. *
  22688. * @param {Object} track
  22689. * Remote {@link TextTrack} to remove
  22690. *
  22691. * @return {undefined}
  22692. * does not return anything
  22693. */
  22694. removeRemoteTextTrack(obj = {}) {
  22695. let {
  22696. track
  22697. } = obj;
  22698. if (!track) {
  22699. track = obj;
  22700. }
  22701. // destructure the input into an object with a track argument, defaulting to arguments[0]
  22702. // default the whole argument to an empty object if nothing was passed in
  22703. if (this.tech_) {
  22704. return this.tech_.removeRemoteTextTrack(track);
  22705. }
  22706. }
  22707. /**
  22708. * Gets available media playback quality metrics as specified by the W3C's Media
  22709. * Playback Quality API.
  22710. *
  22711. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  22712. *
  22713. * @return {Object|undefined}
  22714. * An object with supported media playback quality metrics or undefined if there
  22715. * is no tech or the tech does not support it.
  22716. */
  22717. getVideoPlaybackQuality() {
  22718. return this.techGet_('getVideoPlaybackQuality');
  22719. }
  22720. /**
  22721. * Get video width
  22722. *
  22723. * @return {number}
  22724. * current video width
  22725. */
  22726. videoWidth() {
  22727. return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
  22728. }
  22729. /**
  22730. * Get video height
  22731. *
  22732. * @return {number}
  22733. * current video height
  22734. */
  22735. videoHeight() {
  22736. return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
  22737. }
  22738. /**
  22739. * The player's language code.
  22740. *
  22741. * Changing the language will trigger
  22742. * [languagechange]{@link Player#event:languagechange}
  22743. * which Components can use to update control text.
  22744. * ClickableComponent will update its control text by default on
  22745. * [languagechange]{@link Player#event:languagechange}.
  22746. *
  22747. * @fires Player#languagechange
  22748. *
  22749. * @param {string} [code]
  22750. * the language code to set the player to
  22751. *
  22752. * @return {string}
  22753. * The current language code when getting
  22754. */
  22755. language(code) {
  22756. if (code === undefined) {
  22757. return this.language_;
  22758. }
  22759. if (this.language_ !== String(code).toLowerCase()) {
  22760. this.language_ = String(code).toLowerCase();
  22761. // during first init, it's possible some things won't be evented
  22762. if (isEvented(this)) {
  22763. /**
  22764. * fires when the player language change
  22765. *
  22766. * @event Player#languagechange
  22767. * @type {Event}
  22768. */
  22769. this.trigger('languagechange');
  22770. }
  22771. }
  22772. }
  22773. /**
  22774. * Get the player's language dictionary
  22775. * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
  22776. * Languages specified directly in the player options have precedence
  22777. *
  22778. * @return {Array}
  22779. * An array of of supported languages
  22780. */
  22781. languages() {
  22782. return merge$2(Player.prototype.options_.languages, this.languages_);
  22783. }
  22784. /**
  22785. * returns a JavaScript object representing the current track
  22786. * information. **DOES not return it as JSON**
  22787. *
  22788. * @return {Object}
  22789. * Object representing the current of track info
  22790. */
  22791. toJSON() {
  22792. const options = merge$2(this.options_);
  22793. const tracks = options.tracks;
  22794. options.tracks = [];
  22795. for (let i = 0; i < tracks.length; i++) {
  22796. let track = tracks[i];
  22797. // deep merge tracks and null out player so no circular references
  22798. track = merge$2(track);
  22799. track.player = undefined;
  22800. options.tracks[i] = track;
  22801. }
  22802. return options;
  22803. }
  22804. /**
  22805. * Creates a simple modal dialog (an instance of the {@link ModalDialog}
  22806. * component) that immediately overlays the player with arbitrary
  22807. * content and removes itself when closed.
  22808. *
  22809. * @param {string|Function|Element|Array|null} content
  22810. * Same as {@link ModalDialog#content}'s param of the same name.
  22811. * The most straight-forward usage is to provide a string or DOM
  22812. * element.
  22813. *
  22814. * @param {Object} [options]
  22815. * Extra options which will be passed on to the {@link ModalDialog}.
  22816. *
  22817. * @return {ModalDialog}
  22818. * the {@link ModalDialog} that was created
  22819. */
  22820. createModal(content, options) {
  22821. options = options || {};
  22822. options.content = content || '';
  22823. const modal = new ModalDialog(this, options);
  22824. this.addChild(modal);
  22825. modal.on('dispose', () => {
  22826. this.removeChild(modal);
  22827. });
  22828. modal.open();
  22829. return modal;
  22830. }
  22831. /**
  22832. * Change breakpoint classes when the player resizes.
  22833. *
  22834. * @private
  22835. */
  22836. updateCurrentBreakpoint_() {
  22837. if (!this.responsive()) {
  22838. return;
  22839. }
  22840. const currentBreakpoint = this.currentBreakpoint();
  22841. const currentWidth = this.currentWidth();
  22842. for (let i = 0; i < BREAKPOINT_ORDER.length; i++) {
  22843. const candidateBreakpoint = BREAKPOINT_ORDER[i];
  22844. const maxWidth = this.breakpoints_[candidateBreakpoint];
  22845. if (currentWidth <= maxWidth) {
  22846. // The current breakpoint did not change, nothing to do.
  22847. if (currentBreakpoint === candidateBreakpoint) {
  22848. return;
  22849. }
  22850. // Only remove a class if there is a current breakpoint.
  22851. if (currentBreakpoint) {
  22852. this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
  22853. }
  22854. this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
  22855. this.breakpoint_ = candidateBreakpoint;
  22856. break;
  22857. }
  22858. }
  22859. }
  22860. /**
  22861. * Removes the current breakpoint.
  22862. *
  22863. * @private
  22864. */
  22865. removeCurrentBreakpoint_() {
  22866. const className = this.currentBreakpointClass();
  22867. this.breakpoint_ = '';
  22868. if (className) {
  22869. this.removeClass(className);
  22870. }
  22871. }
  22872. /**
  22873. * Get or set breakpoints on the player.
  22874. *
  22875. * Calling this method with an object or `true` will remove any previous
  22876. * custom breakpoints and start from the defaults again.
  22877. *
  22878. * @param {Object|boolean} [breakpoints]
  22879. * If an object is given, it can be used to provide custom
  22880. * breakpoints. If `true` is given, will set default breakpoints.
  22881. * If this argument is not given, will simply return the current
  22882. * breakpoints.
  22883. *
  22884. * @param {number} [breakpoints.tiny]
  22885. * The maximum width for the "vjs-layout-tiny" class.
  22886. *
  22887. * @param {number} [breakpoints.xsmall]
  22888. * The maximum width for the "vjs-layout-x-small" class.
  22889. *
  22890. * @param {number} [breakpoints.small]
  22891. * The maximum width for the "vjs-layout-small" class.
  22892. *
  22893. * @param {number} [breakpoints.medium]
  22894. * The maximum width for the "vjs-layout-medium" class.
  22895. *
  22896. * @param {number} [breakpoints.large]
  22897. * The maximum width for the "vjs-layout-large" class.
  22898. *
  22899. * @param {number} [breakpoints.xlarge]
  22900. * The maximum width for the "vjs-layout-x-large" class.
  22901. *
  22902. * @param {number} [breakpoints.huge]
  22903. * The maximum width for the "vjs-layout-huge" class.
  22904. *
  22905. * @return {Object}
  22906. * An object mapping breakpoint names to maximum width values.
  22907. */
  22908. breakpoints(breakpoints) {
  22909. // Used as a getter.
  22910. if (breakpoints === undefined) {
  22911. return Object.assign(this.breakpoints_);
  22912. }
  22913. this.breakpoint_ = '';
  22914. this.breakpoints_ = Object.assign({}, DEFAULT_BREAKPOINTS, breakpoints);
  22915. // When breakpoint definitions change, we need to update the currently
  22916. // selected breakpoint.
  22917. this.updateCurrentBreakpoint_();
  22918. // Clone the breakpoints before returning.
  22919. return Object.assign(this.breakpoints_);
  22920. }
  22921. /**
  22922. * Get or set a flag indicating whether or not this player should adjust
  22923. * its UI based on its dimensions.
  22924. *
  22925. * @param {boolean} value
  22926. * Should be `true` if the player should adjust its UI based on its
  22927. * dimensions; otherwise, should be `false`.
  22928. *
  22929. * @return {boolean}
  22930. * Will be `true` if this player should adjust its UI based on its
  22931. * dimensions; otherwise, will be `false`.
  22932. */
  22933. responsive(value) {
  22934. // Used as a getter.
  22935. if (value === undefined) {
  22936. return this.responsive_;
  22937. }
  22938. value = Boolean(value);
  22939. const current = this.responsive_;
  22940. // Nothing changed.
  22941. if (value === current) {
  22942. return;
  22943. }
  22944. // The value actually changed, set it.
  22945. this.responsive_ = value;
  22946. // Start listening for breakpoints and set the initial breakpoint if the
  22947. // player is now responsive.
  22948. if (value) {
  22949. this.on('playerresize', this.boundUpdateCurrentBreakpoint_);
  22950. this.updateCurrentBreakpoint_();
  22951. // Stop listening for breakpoints if the player is no longer responsive.
  22952. } else {
  22953. this.off('playerresize', this.boundUpdateCurrentBreakpoint_);
  22954. this.removeCurrentBreakpoint_();
  22955. }
  22956. return value;
  22957. }
  22958. /**
  22959. * Get current breakpoint name, if any.
  22960. *
  22961. * @return {string}
  22962. * If there is currently a breakpoint set, returns a the key from the
  22963. * breakpoints object matching it. Otherwise, returns an empty string.
  22964. */
  22965. currentBreakpoint() {
  22966. return this.breakpoint_;
  22967. }
  22968. /**
  22969. * Get the current breakpoint class name.
  22970. *
  22971. * @return {string}
  22972. * The matching class name (e.g. `"vjs-layout-tiny"` or
  22973. * `"vjs-layout-large"`) for the current breakpoint. Empty string if
  22974. * there is no current breakpoint.
  22975. */
  22976. currentBreakpointClass() {
  22977. return BREAKPOINT_CLASSES[this.breakpoint_] || '';
  22978. }
  22979. /**
  22980. * An object that describes a single piece of media.
  22981. *
  22982. * Properties that are not part of this type description will be retained; so,
  22983. * this can be viewed as a generic metadata storage mechanism as well.
  22984. *
  22985. * @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}
  22986. * @typedef {Object} Player~MediaObject
  22987. *
  22988. * @property {string} [album]
  22989. * Unused, except if this object is passed to the `MediaSession`
  22990. * API.
  22991. *
  22992. * @property {string} [artist]
  22993. * Unused, except if this object is passed to the `MediaSession`
  22994. * API.
  22995. *
  22996. * @property {Object[]} [artwork]
  22997. * Unused, except if this object is passed to the `MediaSession`
  22998. * API. If not specified, will be populated via the `poster`, if
  22999. * available.
  23000. *
  23001. * @property {string} [poster]
  23002. * URL to an image that will display before playback.
  23003. *
  23004. * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src]
  23005. * A single source object, an array of source objects, or a string
  23006. * referencing a URL to a media source. It is _highly recommended_
  23007. * that an object or array of objects is used here, so that source
  23008. * selection algorithms can take the `type` into account.
  23009. *
  23010. * @property {string} [title]
  23011. * Unused, except if this object is passed to the `MediaSession`
  23012. * API.
  23013. *
  23014. * @property {Object[]} [textTracks]
  23015. * An array of objects to be used to create text tracks, following
  23016. * the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}.
  23017. * For ease of removal, these will be created as "remote" text
  23018. * tracks and set to automatically clean up on source changes.
  23019. *
  23020. * These objects may have properties like `src`, `kind`, `label`,
  23021. * and `language`, see {@link Tech#createRemoteTextTrack}.
  23022. */
  23023. /**
  23024. * Populate the player using a {@link Player~MediaObject|MediaObject}.
  23025. *
  23026. * @param {Player~MediaObject} media
  23027. * A media object.
  23028. *
  23029. * @param {Function} ready
  23030. * A callback to be called when the player is ready.
  23031. */
  23032. loadMedia(media, ready) {
  23033. if (!media || typeof media !== 'object') {
  23034. return;
  23035. }
  23036. this.reset();
  23037. // Clone the media object so it cannot be mutated from outside.
  23038. this.cache_.media = merge$2(media);
  23039. const {
  23040. artist,
  23041. artwork,
  23042. description,
  23043. poster,
  23044. src,
  23045. textTracks,
  23046. title
  23047. } = this.cache_.media;
  23048. // If `artwork` is not given, create it using `poster`.
  23049. if (!artwork && poster) {
  23050. this.cache_.media.artwork = [{
  23051. src: poster,
  23052. type: getMimetype(poster)
  23053. }];
  23054. }
  23055. if (src) {
  23056. this.src(src);
  23057. }
  23058. if (poster) {
  23059. this.poster(poster);
  23060. }
  23061. if (Array.isArray(textTracks)) {
  23062. textTracks.forEach(tt => this.addRemoteTextTrack(tt, false));
  23063. }
  23064. if (this.titleBar) {
  23065. this.titleBar.update({
  23066. title,
  23067. description: description || artist || ''
  23068. });
  23069. }
  23070. this.ready(ready);
  23071. }
  23072. /**
  23073. * Get a clone of the current {@link Player~MediaObject} for this player.
  23074. *
  23075. * If the `loadMedia` method has not been used, will attempt to return a
  23076. * {@link Player~MediaObject} based on the current state of the player.
  23077. *
  23078. * @return {Player~MediaObject}
  23079. */
  23080. getMedia() {
  23081. if (!this.cache_.media) {
  23082. const poster = this.poster();
  23083. const src = this.currentSources();
  23084. const textTracks = Array.prototype.map.call(this.remoteTextTracks(), tt => ({
  23085. kind: tt.kind,
  23086. label: tt.label,
  23087. language: tt.language,
  23088. src: tt.src
  23089. }));
  23090. const media = {
  23091. src,
  23092. textTracks
  23093. };
  23094. if (poster) {
  23095. media.poster = poster;
  23096. media.artwork = [{
  23097. src: media.poster,
  23098. type: getMimetype(media.poster)
  23099. }];
  23100. }
  23101. return media;
  23102. }
  23103. return merge$2(this.cache_.media);
  23104. }
  23105. /**
  23106. * Gets tag settings
  23107. *
  23108. * @param {Element} tag
  23109. * The player tag
  23110. *
  23111. * @return {Object}
  23112. * An object containing all of the settings
  23113. * for a player tag
  23114. */
  23115. static getTagSettings(tag) {
  23116. const baseOptions = {
  23117. sources: [],
  23118. tracks: []
  23119. };
  23120. const tagOptions = getAttributes(tag);
  23121. const dataSetup = tagOptions['data-setup'];
  23122. if (hasClass(tag, 'vjs-fill')) {
  23123. tagOptions.fill = true;
  23124. }
  23125. if (hasClass(tag, 'vjs-fluid')) {
  23126. tagOptions.fluid = true;
  23127. }
  23128. // Check if data-setup attr exists.
  23129. if (dataSetup !== null) {
  23130. // Parse options JSON
  23131. // If empty string, make it a parsable json object.
  23132. const [err, data] = tuple(dataSetup || '{}');
  23133. if (err) {
  23134. log$1.error(err);
  23135. }
  23136. Object.assign(tagOptions, data);
  23137. }
  23138. Object.assign(baseOptions, tagOptions);
  23139. // Get tag children settings
  23140. if (tag.hasChildNodes()) {
  23141. const children = tag.childNodes;
  23142. for (let i = 0, j = children.length; i < j; i++) {
  23143. const child = children[i];
  23144. // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
  23145. const childName = child.nodeName.toLowerCase();
  23146. if (childName === 'source') {
  23147. baseOptions.sources.push(getAttributes(child));
  23148. } else if (childName === 'track') {
  23149. baseOptions.tracks.push(getAttributes(child));
  23150. }
  23151. }
  23152. }
  23153. return baseOptions;
  23154. }
  23155. /**
  23156. * Set debug mode to enable/disable logs at info level.
  23157. *
  23158. * @param {boolean} enabled
  23159. * @fires Player#debugon
  23160. * @fires Player#debugoff
  23161. */
  23162. debug(enabled) {
  23163. if (enabled === undefined) {
  23164. return this.debugEnabled_;
  23165. }
  23166. if (enabled) {
  23167. this.trigger('debugon');
  23168. this.previousLogLevel_ = this.log.level;
  23169. this.log.level('debug');
  23170. this.debugEnabled_ = true;
  23171. } else {
  23172. this.trigger('debugoff');
  23173. this.log.level(this.previousLogLevel_);
  23174. this.previousLogLevel_ = undefined;
  23175. this.debugEnabled_ = false;
  23176. }
  23177. }
  23178. /**
  23179. * Set or get current playback rates.
  23180. * Takes an array and updates the playback rates menu with the new items.
  23181. * Pass in an empty array to hide the menu.
  23182. * Values other than arrays are ignored.
  23183. *
  23184. * @fires Player#playbackrateschange
  23185. * @param {number[]} newRates
  23186. * The new rates that the playback rates menu should update to.
  23187. * An empty array will hide the menu
  23188. * @return {number[]} When used as a getter will return the current playback rates
  23189. */
  23190. playbackRates(newRates) {
  23191. if (newRates === undefined) {
  23192. return this.cache_.playbackRates;
  23193. }
  23194. // ignore any value that isn't an array
  23195. if (!Array.isArray(newRates)) {
  23196. return;
  23197. }
  23198. // ignore any arrays that don't only contain numbers
  23199. if (!newRates.every(rate => typeof rate === 'number')) {
  23200. return;
  23201. }
  23202. this.cache_.playbackRates = newRates;
  23203. /**
  23204. * fires when the playback rates in a player are changed
  23205. *
  23206. * @event Player#playbackrateschange
  23207. * @type {Event}
  23208. */
  23209. this.trigger('playbackrateschange');
  23210. }
  23211. }
  23212. /**
  23213. * Get the {@link VideoTrackList}
  23214. *
  23215. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
  23216. *
  23217. * @return {VideoTrackList}
  23218. * the current video track list
  23219. *
  23220. * @method Player.prototype.videoTracks
  23221. */
  23222. /**
  23223. * Get the {@link AudioTrackList}
  23224. *
  23225. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
  23226. *
  23227. * @return {AudioTrackList}
  23228. * the current audio track list
  23229. *
  23230. * @method Player.prototype.audioTracks
  23231. */
  23232. /**
  23233. * Get the {@link TextTrackList}
  23234. *
  23235. * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
  23236. *
  23237. * @return {TextTrackList}
  23238. * the current text track list
  23239. *
  23240. * @method Player.prototype.textTracks
  23241. */
  23242. /**
  23243. * Get the remote {@link TextTrackList}
  23244. *
  23245. * @return {TextTrackList}
  23246. * The current remote text track list
  23247. *
  23248. * @method Player.prototype.remoteTextTracks
  23249. */
  23250. /**
  23251. * Get the remote {@link HtmlTrackElementList} tracks.
  23252. *
  23253. * @return {HtmlTrackElementList}
  23254. * The current remote text track element list
  23255. *
  23256. * @method Player.prototype.remoteTextTrackEls
  23257. */
  23258. ALL.names.forEach(function (name) {
  23259. const props = ALL[name];
  23260. Player.prototype[props.getterName] = function () {
  23261. if (this.tech_) {
  23262. return this.tech_[props.getterName]();
  23263. }
  23264. // if we have not yet loadTech_, we create {video,audio,text}Tracks_
  23265. // these will be passed to the tech during loading
  23266. this[props.privateName] = this[props.privateName] || new props.ListClass();
  23267. return this[props.privateName];
  23268. };
  23269. });
  23270. /**
  23271. * Get or set the `Player`'s crossorigin option. For the HTML5 player, this
  23272. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  23273. * behavior.
  23274. *
  23275. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  23276. *
  23277. * @param {string} [value]
  23278. * The value to set the `Player`'s crossorigin to. If an argument is
  23279. * given, must be one of `anonymous` or `use-credentials`.
  23280. *
  23281. * @return {string|undefined}
  23282. * - The current crossorigin value of the `Player` when getting.
  23283. * - undefined when setting
  23284. */
  23285. Player.prototype.crossorigin = Player.prototype.crossOrigin;
  23286. /**
  23287. * Global enumeration of players.
  23288. *
  23289. * The keys are the player IDs and the values are either the {@link Player}
  23290. * instance or `null` for disposed players.
  23291. *
  23292. * @type {Object}
  23293. */
  23294. Player.players = {};
  23295. const navigator = window.navigator;
  23296. /*
  23297. * Player instance options, surfaced using options
  23298. * options = Player.prototype.options_
  23299. * Make changes in options, not here.
  23300. *
  23301. * @type {Object}
  23302. * @private
  23303. */
  23304. Player.prototype.options_ = {
  23305. // Default order of fallback technology
  23306. techOrder: Tech.defaultTechOrder_,
  23307. html5: {},
  23308. // enable sourceset by default
  23309. enableSourceset: true,
  23310. // default inactivity timeout
  23311. inactivityTimeout: 2000,
  23312. // default playback rates
  23313. playbackRates: [],
  23314. // Add playback rate selection by adding rates
  23315. // 'playbackRates': [0.5, 1, 1.5, 2],
  23316. liveui: false,
  23317. // Included control sets
  23318. children: ['mediaLoader', 'posterImage', 'titleBar', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'],
  23319. language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',
  23320. // locales and their language translations
  23321. languages: {},
  23322. // Default message to show when a video cannot be played.
  23323. notSupportedMessage: 'No compatible source was found for this media.',
  23324. normalizeAutoplay: false,
  23325. fullscreen: {
  23326. options: {
  23327. navigationUI: 'hide'
  23328. }
  23329. },
  23330. breakpoints: {},
  23331. responsive: false,
  23332. audioOnlyMode: false,
  23333. audioPosterMode: false
  23334. };
  23335. [
  23336. /**
  23337. * Returns whether or not the player is in the "ended" state.
  23338. *
  23339. * @return {Boolean} True if the player is in the ended state, false if not.
  23340. * @method Player#ended
  23341. */
  23342. 'ended',
  23343. /**
  23344. * Returns whether or not the player is in the "seeking" state.
  23345. *
  23346. * @return {Boolean} True if the player is in the seeking state, false if not.
  23347. * @method Player#seeking
  23348. */
  23349. 'seeking',
  23350. /**
  23351. * Returns the TimeRanges of the media that are currently available
  23352. * for seeking to.
  23353. *
  23354. * @return {TimeRanges} the seekable intervals of the media timeline
  23355. * @method Player#seekable
  23356. */
  23357. 'seekable',
  23358. /**
  23359. * Returns the current state of network activity for the element, from
  23360. * the codes in the list below.
  23361. * - NETWORK_EMPTY (numeric value 0)
  23362. * The element has not yet been initialised. All attributes are in
  23363. * their initial states.
  23364. * - NETWORK_IDLE (numeric value 1)
  23365. * The element's resource selection algorithm is active and has
  23366. * selected a resource, but it is not actually using the network at
  23367. * this time.
  23368. * - NETWORK_LOADING (numeric value 2)
  23369. * The user agent is actively trying to download data.
  23370. * - NETWORK_NO_SOURCE (numeric value 3)
  23371. * The element's resource selection algorithm is active, but it has
  23372. * not yet found a resource to use.
  23373. *
  23374. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
  23375. * @return {number} the current network activity state
  23376. * @method Player#networkState
  23377. */
  23378. 'networkState',
  23379. /**
  23380. * Returns a value that expresses the current state of the element
  23381. * with respect to rendering the current playback position, from the
  23382. * codes in the list below.
  23383. * - HAVE_NOTHING (numeric value 0)
  23384. * No information regarding the media resource is available.
  23385. * - HAVE_METADATA (numeric value 1)
  23386. * Enough of the resource has been obtained that the duration of the
  23387. * resource is available.
  23388. * - HAVE_CURRENT_DATA (numeric value 2)
  23389. * Data for the immediate current playback position is available.
  23390. * - HAVE_FUTURE_DATA (numeric value 3)
  23391. * Data for the immediate current playback position is available, as
  23392. * well as enough data for the user agent to advance the current
  23393. * playback position in the direction of playback.
  23394. * - HAVE_ENOUGH_DATA (numeric value 4)
  23395. * The user agent estimates that enough data is available for
  23396. * playback to proceed uninterrupted.
  23397. *
  23398. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
  23399. * @return {number} the current playback rendering state
  23400. * @method Player#readyState
  23401. */
  23402. 'readyState'].forEach(function (fn) {
  23403. Player.prototype[fn] = function () {
  23404. return this.techGet_(fn);
  23405. };
  23406. });
  23407. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  23408. Player.prototype[`handleTech${toTitleCase$1(event)}_`] = function () {
  23409. return this.trigger(event);
  23410. };
  23411. });
  23412. /**
  23413. * Fired when the player has initial duration and dimension information
  23414. *
  23415. * @event Player#loadedmetadata
  23416. * @type {Event}
  23417. */
  23418. /**
  23419. * Fired when the player has downloaded data at the current playback position
  23420. *
  23421. * @event Player#loadeddata
  23422. * @type {Event}
  23423. */
  23424. /**
  23425. * Fired when the current playback position has changed *
  23426. * During playback this is fired every 15-250 milliseconds, depending on the
  23427. * playback technology in use.
  23428. *
  23429. * @event Player#timeupdate
  23430. * @type {Event}
  23431. */
  23432. /**
  23433. * Fired when the volume changes
  23434. *
  23435. * @event Player#volumechange
  23436. * @type {Event}
  23437. */
  23438. /**
  23439. * Reports whether or not a player has a plugin available.
  23440. *
  23441. * This does not report whether or not the plugin has ever been initialized
  23442. * on this player. For that, [usingPlugin]{@link Player#usingPlugin}.
  23443. *
  23444. * @method Player#hasPlugin
  23445. * @param {string} name
  23446. * The name of a plugin.
  23447. *
  23448. * @return {boolean}
  23449. * Whether or not this player has the requested plugin available.
  23450. */
  23451. /**
  23452. * Reports whether or not a player is using a plugin by name.
  23453. *
  23454. * For basic plugins, this only reports whether the plugin has _ever_ been
  23455. * initialized on this player.
  23456. *
  23457. * @method Player#usingPlugin
  23458. * @param {string} name
  23459. * The name of a plugin.
  23460. *
  23461. * @return {boolean}
  23462. * Whether or not this player is using the requested plugin.
  23463. */
  23464. Component$1.registerComponent('Player', Player);
  23465. /**
  23466. * @file plugin.js
  23467. */
  23468. /**
  23469. * The base plugin name.
  23470. *
  23471. * @private
  23472. * @constant
  23473. * @type {string}
  23474. */
  23475. const BASE_PLUGIN_NAME = 'plugin';
  23476. /**
  23477. * The key on which a player's active plugins cache is stored.
  23478. *
  23479. * @private
  23480. * @constant
  23481. * @type {string}
  23482. */
  23483. const PLUGIN_CACHE_KEY = 'activePlugins_';
  23484. /**
  23485. * Stores registered plugins in a private space.
  23486. *
  23487. * @private
  23488. * @type {Object}
  23489. */
  23490. const pluginStorage = {};
  23491. /**
  23492. * Reports whether or not a plugin has been registered.
  23493. *
  23494. * @private
  23495. * @param {string} name
  23496. * The name of a plugin.
  23497. *
  23498. * @return {boolean}
  23499. * Whether or not the plugin has been registered.
  23500. */
  23501. const pluginExists = name => pluginStorage.hasOwnProperty(name);
  23502. /**
  23503. * Get a single registered plugin by name.
  23504. *
  23505. * @private
  23506. * @param {string} name
  23507. * The name of a plugin.
  23508. *
  23509. * @return {typeof Plugin|Function|undefined}
  23510. * The plugin (or undefined).
  23511. */
  23512. const getPlugin = name => pluginExists(name) ? pluginStorage[name] : undefined;
  23513. /**
  23514. * Marks a plugin as "active" on a player.
  23515. *
  23516. * Also, ensures that the player has an object for tracking active plugins.
  23517. *
  23518. * @private
  23519. * @param {Player} player
  23520. * A Video.js player instance.
  23521. *
  23522. * @param {string} name
  23523. * The name of a plugin.
  23524. */
  23525. const markPluginAsActive = (player, name) => {
  23526. player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
  23527. player[PLUGIN_CACHE_KEY][name] = true;
  23528. };
  23529. /**
  23530. * Triggers a pair of plugin setup events.
  23531. *
  23532. * @private
  23533. * @param {Player} player
  23534. * A Video.js player instance.
  23535. *
  23536. * @param {Plugin~PluginEventHash} hash
  23537. * A plugin event hash.
  23538. *
  23539. * @param {boolean} [before]
  23540. * If true, prefixes the event name with "before". In other words,
  23541. * use this to trigger "beforepluginsetup" instead of "pluginsetup".
  23542. */
  23543. const triggerSetupEvent = (player, hash, before) => {
  23544. const eventName = (before ? 'before' : '') + 'pluginsetup';
  23545. player.trigger(eventName, hash);
  23546. player.trigger(eventName + ':' + hash.name, hash);
  23547. };
  23548. /**
  23549. * Takes a basic plugin function and returns a wrapper function which marks
  23550. * on the player that the plugin has been activated.
  23551. *
  23552. * @private
  23553. * @param {string} name
  23554. * The name of the plugin.
  23555. *
  23556. * @param {Function} plugin
  23557. * The basic plugin.
  23558. *
  23559. * @return {Function}
  23560. * A wrapper function for the given plugin.
  23561. */
  23562. const createBasicPlugin = function (name, plugin) {
  23563. const basicPluginWrapper = function () {
  23564. // We trigger the "beforepluginsetup" and "pluginsetup" events on the player
  23565. // regardless, but we want the hash to be consistent with the hash provided
  23566. // for advanced plugins.
  23567. //
  23568. // The only potentially counter-intuitive thing here is the `instance` in
  23569. // the "pluginsetup" event is the value returned by the `plugin` function.
  23570. triggerSetupEvent(this, {
  23571. name,
  23572. plugin,
  23573. instance: null
  23574. }, true);
  23575. const instance = plugin.apply(this, arguments);
  23576. markPluginAsActive(this, name);
  23577. triggerSetupEvent(this, {
  23578. name,
  23579. plugin,
  23580. instance
  23581. });
  23582. return instance;
  23583. };
  23584. Object.keys(plugin).forEach(function (prop) {
  23585. basicPluginWrapper[prop] = plugin[prop];
  23586. });
  23587. return basicPluginWrapper;
  23588. };
  23589. /**
  23590. * Takes a plugin sub-class and returns a factory function for generating
  23591. * instances of it.
  23592. *
  23593. * This factory function will replace itself with an instance of the requested
  23594. * sub-class of Plugin.
  23595. *
  23596. * @private
  23597. * @param {string} name
  23598. * The name of the plugin.
  23599. *
  23600. * @param {Plugin} PluginSubClass
  23601. * The advanced plugin.
  23602. *
  23603. * @return {Function}
  23604. */
  23605. const createPluginFactory = (name, PluginSubClass) => {
  23606. // Add a `name` property to the plugin prototype so that each plugin can
  23607. // refer to itself by name.
  23608. PluginSubClass.prototype.name = name;
  23609. return function (...args) {
  23610. triggerSetupEvent(this, {
  23611. name,
  23612. plugin: PluginSubClass,
  23613. instance: null
  23614. }, true);
  23615. const instance = new PluginSubClass(...[this, ...args]);
  23616. // The plugin is replaced by a function that returns the current instance.
  23617. this[name] = () => instance;
  23618. triggerSetupEvent(this, instance.getEventHash());
  23619. return instance;
  23620. };
  23621. };
  23622. /**
  23623. * Parent class for all advanced plugins.
  23624. *
  23625. * @mixes module:evented~EventedMixin
  23626. * @mixes module:stateful~StatefulMixin
  23627. * @fires Player#beforepluginsetup
  23628. * @fires Player#beforepluginsetup:$name
  23629. * @fires Player#pluginsetup
  23630. * @fires Player#pluginsetup:$name
  23631. * @listens Player#dispose
  23632. * @throws {Error}
  23633. * If attempting to instantiate the base {@link Plugin} class
  23634. * directly instead of via a sub-class.
  23635. */
  23636. class Plugin {
  23637. /**
  23638. * Creates an instance of this class.
  23639. *
  23640. * Sub-classes should call `super` to ensure plugins are properly initialized.
  23641. *
  23642. * @param {Player} player
  23643. * A Video.js player instance.
  23644. */
  23645. constructor(player) {
  23646. if (this.constructor === Plugin) {
  23647. throw new Error('Plugin must be sub-classed; not directly instantiated.');
  23648. }
  23649. this.player = player;
  23650. if (!this.log) {
  23651. this.log = this.player.log.createLogger(this.name);
  23652. }
  23653. // Make this object evented, but remove the added `trigger` method so we
  23654. // use the prototype version instead.
  23655. evented(this);
  23656. delete this.trigger;
  23657. stateful(this, this.constructor.defaultState);
  23658. markPluginAsActive(player, this.name);
  23659. // Auto-bind the dispose method so we can use it as a listener and unbind
  23660. // it later easily.
  23661. this.dispose = this.dispose.bind(this);
  23662. // If the player is disposed, dispose the plugin.
  23663. player.on('dispose', this.dispose);
  23664. }
  23665. /**
  23666. * Get the version of the plugin that was set on <pluginName>.VERSION
  23667. */
  23668. version() {
  23669. return this.constructor.VERSION;
  23670. }
  23671. /**
  23672. * Each event triggered by plugins includes a hash of additional data with
  23673. * conventional properties.
  23674. *
  23675. * This returns that object or mutates an existing hash.
  23676. *
  23677. * @param {Object} [hash={}]
  23678. * An object to be used as event an event hash.
  23679. *
  23680. * @return {Plugin~PluginEventHash}
  23681. * An event hash object with provided properties mixed-in.
  23682. */
  23683. getEventHash(hash = {}) {
  23684. hash.name = this.name;
  23685. hash.plugin = this.constructor;
  23686. hash.instance = this;
  23687. return hash;
  23688. }
  23689. /**
  23690. * Triggers an event on the plugin object and overrides
  23691. * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.
  23692. *
  23693. * @param {string|Object} event
  23694. * An event type or an object with a type property.
  23695. *
  23696. * @param {Object} [hash={}]
  23697. * Additional data hash to merge with a
  23698. * {@link Plugin~PluginEventHash|PluginEventHash}.
  23699. *
  23700. * @return {boolean}
  23701. * Whether or not default was prevented.
  23702. */
  23703. trigger(event, hash = {}) {
  23704. return trigger(this.eventBusEl_, event, this.getEventHash(hash));
  23705. }
  23706. /**
  23707. * Handles "statechanged" events on the plugin. No-op by default, override by
  23708. * subclassing.
  23709. *
  23710. * @abstract
  23711. * @param {Event} e
  23712. * An event object provided by a "statechanged" event.
  23713. *
  23714. * @param {Object} e.changes
  23715. * An object describing changes that occurred with the "statechanged"
  23716. * event.
  23717. */
  23718. handleStateChanged(e) {}
  23719. /**
  23720. * Disposes a plugin.
  23721. *
  23722. * Subclasses can override this if they want, but for the sake of safety,
  23723. * it's probably best to subscribe the "dispose" event.
  23724. *
  23725. * @fires Plugin#dispose
  23726. */
  23727. dispose() {
  23728. const {
  23729. name,
  23730. player
  23731. } = this;
  23732. /**
  23733. * Signals that a advanced plugin is about to be disposed.
  23734. *
  23735. * @event Plugin#dispose
  23736. * @type {Event}
  23737. */
  23738. this.trigger('dispose');
  23739. this.off();
  23740. player.off('dispose', this.dispose);
  23741. // Eliminate any possible sources of leaking memory by clearing up
  23742. // references between the player and the plugin instance and nulling out
  23743. // the plugin's state and replacing methods with a function that throws.
  23744. player[PLUGIN_CACHE_KEY][name] = false;
  23745. this.player = this.state = null;
  23746. // Finally, replace the plugin name on the player with a new factory
  23747. // function, so that the plugin is ready to be set up again.
  23748. player[name] = createPluginFactory(name, pluginStorage[name]);
  23749. }
  23750. /**
  23751. * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).
  23752. *
  23753. * @param {string|Function} plugin
  23754. * If a string, matches the name of a plugin. If a function, will be
  23755. * tested directly.
  23756. *
  23757. * @return {boolean}
  23758. * Whether or not a plugin is a basic plugin.
  23759. */
  23760. static isBasic(plugin) {
  23761. const p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;
  23762. return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);
  23763. }
  23764. /**
  23765. * Register a Video.js plugin.
  23766. *
  23767. * @param {string} name
  23768. * The name of the plugin to be registered. Must be a string and
  23769. * must not match an existing plugin or a method on the `Player`
  23770. * prototype.
  23771. *
  23772. * @param {typeof Plugin|Function} plugin
  23773. * A sub-class of `Plugin` or a function for basic plugins.
  23774. *
  23775. * @return {typeof Plugin|Function}
  23776. * For advanced plugins, a factory function for that plugin. For
  23777. * basic plugins, a wrapper function that initializes the plugin.
  23778. */
  23779. static registerPlugin(name, plugin) {
  23780. if (typeof name !== 'string') {
  23781. throw new Error(`Illegal plugin name, "${name}", must be a string, was ${typeof name}.`);
  23782. }
  23783. if (pluginExists(name)) {
  23784. log$1.warn(`A plugin named "${name}" already exists. You may want to avoid re-registering plugins!`);
  23785. } else if (Player.prototype.hasOwnProperty(name)) {
  23786. throw new Error(`Illegal plugin name, "${name}", cannot share a name with an existing player method!`);
  23787. }
  23788. if (typeof plugin !== 'function') {
  23789. throw new Error(`Illegal plugin for "${name}", must be a function, was ${typeof plugin}.`);
  23790. }
  23791. pluginStorage[name] = plugin;
  23792. // Add a player prototype method for all sub-classed plugins (but not for
  23793. // the base Plugin class).
  23794. if (name !== BASE_PLUGIN_NAME) {
  23795. if (Plugin.isBasic(plugin)) {
  23796. Player.prototype[name] = createBasicPlugin(name, plugin);
  23797. } else {
  23798. Player.prototype[name] = createPluginFactory(name, plugin);
  23799. }
  23800. }
  23801. return plugin;
  23802. }
  23803. /**
  23804. * De-register a Video.js plugin.
  23805. *
  23806. * @param {string} name
  23807. * The name of the plugin to be de-registered. Must be a string that
  23808. * matches an existing plugin.
  23809. *
  23810. * @throws {Error}
  23811. * If an attempt is made to de-register the base plugin.
  23812. */
  23813. static deregisterPlugin(name) {
  23814. if (name === BASE_PLUGIN_NAME) {
  23815. throw new Error('Cannot de-register base plugin.');
  23816. }
  23817. if (pluginExists(name)) {
  23818. delete pluginStorage[name];
  23819. delete Player.prototype[name];
  23820. }
  23821. }
  23822. /**
  23823. * Gets an object containing multiple Video.js plugins.
  23824. *
  23825. * @param {Array} [names]
  23826. * If provided, should be an array of plugin names. Defaults to _all_
  23827. * plugin names.
  23828. *
  23829. * @return {Object|undefined}
  23830. * An object containing plugin(s) associated with their name(s) or
  23831. * `undefined` if no matching plugins exist).
  23832. */
  23833. static getPlugins(names = Object.keys(pluginStorage)) {
  23834. let result;
  23835. names.forEach(name => {
  23836. const plugin = getPlugin(name);
  23837. if (plugin) {
  23838. result = result || {};
  23839. result[name] = plugin;
  23840. }
  23841. });
  23842. return result;
  23843. }
  23844. /**
  23845. * Gets a plugin's version, if available
  23846. *
  23847. * @param {string} name
  23848. * The name of a plugin.
  23849. *
  23850. * @return {string}
  23851. * The plugin's version or an empty string.
  23852. */
  23853. static getPluginVersion(name) {
  23854. const plugin = getPlugin(name);
  23855. return plugin && plugin.VERSION || '';
  23856. }
  23857. }
  23858. /**
  23859. * Gets a plugin by name if it exists.
  23860. *
  23861. * @static
  23862. * @method getPlugin
  23863. * @memberOf Plugin
  23864. * @param {string} name
  23865. * The name of a plugin.
  23866. *
  23867. * @returns {typeof Plugin|Function|undefined}
  23868. * The plugin (or `undefined`).
  23869. */
  23870. Plugin.getPlugin = getPlugin;
  23871. /**
  23872. * The name of the base plugin class as it is registered.
  23873. *
  23874. * @type {string}
  23875. */
  23876. Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
  23877. Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
  23878. /**
  23879. * Documented in player.js
  23880. *
  23881. * @ignore
  23882. */
  23883. Player.prototype.usingPlugin = function (name) {
  23884. return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
  23885. };
  23886. /**
  23887. * Documented in player.js
  23888. *
  23889. * @ignore
  23890. */
  23891. Player.prototype.hasPlugin = function (name) {
  23892. return !!pluginExists(name);
  23893. };
  23894. /**
  23895. * Signals that a plugin is about to be set up on a player.
  23896. *
  23897. * @event Player#beforepluginsetup
  23898. * @type {Plugin~PluginEventHash}
  23899. */
  23900. /**
  23901. * Signals that a plugin is about to be set up on a player - by name. The name
  23902. * is the name of the plugin.
  23903. *
  23904. * @event Player#beforepluginsetup:$name
  23905. * @type {Plugin~PluginEventHash}
  23906. */
  23907. /**
  23908. * Signals that a plugin has just been set up on a player.
  23909. *
  23910. * @event Player#pluginsetup
  23911. * @type {Plugin~PluginEventHash}
  23912. */
  23913. /**
  23914. * Signals that a plugin has just been set up on a player - by name. The name
  23915. * is the name of the plugin.
  23916. *
  23917. * @event Player#pluginsetup:$name
  23918. * @type {Plugin~PluginEventHash}
  23919. */
  23920. /**
  23921. * @typedef {Object} Plugin~PluginEventHash
  23922. *
  23923. * @property {string} instance
  23924. * For basic plugins, the return value of the plugin function. For
  23925. * advanced plugins, the plugin instance on which the event is fired.
  23926. *
  23927. * @property {string} name
  23928. * The name of the plugin.
  23929. *
  23930. * @property {string} plugin
  23931. * For basic plugins, the plugin function. For advanced plugins, the
  23932. * plugin class/constructor.
  23933. */
  23934. /**
  23935. * @file deprecate.js
  23936. * @module deprecate
  23937. */
  23938. /**
  23939. * Decorate a function with a deprecation message the first time it is called.
  23940. *
  23941. * @param {string} message
  23942. * A deprecation message to log the first time the returned function
  23943. * is called.
  23944. *
  23945. * @param {Function} fn
  23946. * The function to be deprecated.
  23947. *
  23948. * @return {Function}
  23949. * A wrapper function that will log a deprecation warning the first
  23950. * time it is called. The return value will be the return value of
  23951. * the wrapped function.
  23952. */
  23953. function deprecate(message, fn) {
  23954. let warned = false;
  23955. return function (...args) {
  23956. if (!warned) {
  23957. log$1.warn(message);
  23958. }
  23959. warned = true;
  23960. return fn.apply(this, args);
  23961. };
  23962. }
  23963. /**
  23964. * Internal function used to mark a function as deprecated in the next major
  23965. * version with consistent messaging.
  23966. *
  23967. * @param {number} major The major version where it will be removed
  23968. * @param {string} oldName The old function name
  23969. * @param {string} newName The new function name
  23970. * @param {Function} fn The function to deprecate
  23971. * @return {Function} The decorated function
  23972. */
  23973. function deprecateForMajor(major, oldName, newName, fn) {
  23974. return deprecate(`${oldName} is deprecated and will be removed in ${major}.0; please use ${newName} instead.`, fn);
  23975. }
  23976. /**
  23977. * @file video.js
  23978. * @module videojs
  23979. */
  23980. /**
  23981. * Normalize an `id` value by trimming off a leading `#`
  23982. *
  23983. * @private
  23984. * @param {string} id
  23985. * A string, maybe with a leading `#`.
  23986. *
  23987. * @return {string}
  23988. * The string, without any leading `#`.
  23989. */
  23990. const normalizeId = id => id.indexOf('#') === 0 ? id.slice(1) : id;
  23991. /**
  23992. * A callback that is called when a component is ready. Does not have any
  23993. * parameters and any callback value will be ignored. See: {@link Component~ReadyCallback}
  23994. *
  23995. * @callback ReadyCallback
  23996. */
  23997. /**
  23998. * The `videojs()` function doubles as the main function for users to create a
  23999. * {@link Player} instance as well as the main library namespace.
  24000. *
  24001. * It can also be used as a getter for a pre-existing {@link Player} instance.
  24002. * However, we _strongly_ recommend using `videojs.getPlayer()` for this
  24003. * purpose because it avoids any potential for unintended initialization.
  24004. *
  24005. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  24006. * of our JSDoc template, we cannot properly document this as both a function
  24007. * and a namespace, so its function signature is documented here.
  24008. *
  24009. * #### Arguments
  24010. * ##### id
  24011. * string|Element, **required**
  24012. *
  24013. * Video element or video element ID.
  24014. *
  24015. * ##### options
  24016. * Object, optional
  24017. *
  24018. * Options object for providing settings.
  24019. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  24020. *
  24021. * ##### ready
  24022. * {@link Component~ReadyCallback}, optional
  24023. *
  24024. * A function to be called when the {@link Player} and {@link Tech} are ready.
  24025. *
  24026. * #### Return Value
  24027. *
  24028. * The `videojs()` function returns a {@link Player} instance.
  24029. *
  24030. * @namespace
  24031. *
  24032. * @borrows AudioTrack as AudioTrack
  24033. * @borrows Component.getComponent as getComponent
  24034. * @borrows module:events.on as on
  24035. * @borrows module:events.one as one
  24036. * @borrows module:events.off as off
  24037. * @borrows module:events.trigger as trigger
  24038. * @borrows EventTarget as EventTarget
  24039. * @borrows module:middleware.use as use
  24040. * @borrows Player.players as players
  24041. * @borrows Plugin.registerPlugin as registerPlugin
  24042. * @borrows Plugin.deregisterPlugin as deregisterPlugin
  24043. * @borrows Plugin.getPlugins as getPlugins
  24044. * @borrows Plugin.getPlugin as getPlugin
  24045. * @borrows Plugin.getPluginVersion as getPluginVersion
  24046. * @borrows Tech.getTech as getTech
  24047. * @borrows Tech.registerTech as registerTech
  24048. * @borrows TextTrack as TextTrack
  24049. * @borrows VideoTrack as VideoTrack
  24050. *
  24051. * @param {string|Element} id
  24052. * Video element or video element ID.
  24053. *
  24054. * @param {Object} [options]
  24055. * Options object for providing settings.
  24056. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  24057. *
  24058. * @param {ReadyCallback} [ready]
  24059. * A function to be called when the {@link Player} and {@link Tech} are
  24060. * ready.
  24061. *
  24062. * @return {Player}
  24063. * The `videojs()` function returns a {@link Player|Player} instance.
  24064. */
  24065. function videojs(id, options, ready) {
  24066. let player = videojs.getPlayer(id);
  24067. if (player) {
  24068. if (options) {
  24069. log$1.warn(`Player "${id}" is already initialised. Options will not be applied.`);
  24070. }
  24071. if (ready) {
  24072. player.ready(ready);
  24073. }
  24074. return player;
  24075. }
  24076. const el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;
  24077. if (!isEl(el)) {
  24078. throw new TypeError('The element or ID supplied is not valid. (videojs)');
  24079. }
  24080. // document.body.contains(el) will only check if el is contained within that one document.
  24081. // This causes problems for elements in iframes.
  24082. // Instead, use the element's ownerDocument instead of the global document.
  24083. // This will make sure that the element is indeed in the dom of that document.
  24084. // Additionally, check that the document in question has a default view.
  24085. // If the document is no longer attached to the dom, the defaultView of the document will be null.
  24086. if (!el.ownerDocument.defaultView || !el.ownerDocument.body.contains(el)) {
  24087. log$1.warn('The element supplied is not included in the DOM');
  24088. }
  24089. options = options || {};
  24090. // Store a copy of the el before modification, if it is to be restored in destroy()
  24091. // If div ingest, store the parent div
  24092. if (options.restoreEl === true) {
  24093. options.restoreEl = (el.parentNode && el.parentNode.hasAttribute('data-vjs-player') ? el.parentNode : el).cloneNode(true);
  24094. }
  24095. hooks('beforesetup').forEach(hookFunction => {
  24096. const opts = hookFunction(el, merge$2(options));
  24097. if (!isObject$1(opts) || Array.isArray(opts)) {
  24098. log$1.error('please return an object in beforesetup hooks');
  24099. return;
  24100. }
  24101. options = merge$2(options, opts);
  24102. });
  24103. // We get the current "Player" component here in case an integration has
  24104. // replaced it with a custom player.
  24105. const PlayerComponent = Component$1.getComponent('Player');
  24106. player = new PlayerComponent(el, options, ready);
  24107. hooks('setup').forEach(hookFunction => hookFunction(player));
  24108. return player;
  24109. }
  24110. videojs.hooks_ = hooks_;
  24111. videojs.hooks = hooks;
  24112. videojs.hook = hook;
  24113. videojs.hookOnce = hookOnce;
  24114. videojs.removeHook = removeHook;
  24115. // Add default styles
  24116. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
  24117. let style = $('.vjs-styles-defaults');
  24118. if (!style) {
  24119. style = createStyleElement('vjs-styles-defaults');
  24120. const head = $('head');
  24121. if (head) {
  24122. head.insertBefore(style, head.firstChild);
  24123. }
  24124. setTextContent(style, `
  24125. .video-js {
  24126. width: 300px;
  24127. height: 150px;
  24128. }
  24129. .vjs-fluid:not(.vjs-audio-only-mode) {
  24130. padding-top: 56.25%
  24131. }
  24132. `);
  24133. }
  24134. }
  24135. // Run Auto-load players
  24136. // You have to wait at least once in case this script is loaded after your
  24137. // video in the DOM (weird behavior only with minified version)
  24138. autoSetupTimeout(1, videojs);
  24139. /**
  24140. * Current Video.js version. Follows [semantic versioning](https://semver.org/).
  24141. *
  24142. * @type {string}
  24143. */
  24144. videojs.VERSION = version$5;
  24145. /**
  24146. * The global options object. These are the settings that take effect
  24147. * if no overrides are specified when the player is created.
  24148. *
  24149. * @type {Object}
  24150. */
  24151. videojs.options = Player.prototype.options_;
  24152. /**
  24153. * Get an object with the currently created players, keyed by player ID
  24154. *
  24155. * @return {Object}
  24156. * The created players
  24157. */
  24158. videojs.getPlayers = () => Player.players;
  24159. /**
  24160. * Get a single player based on an ID or DOM element.
  24161. *
  24162. * This is useful if you want to check if an element or ID has an associated
  24163. * Video.js player, but not create one if it doesn't.
  24164. *
  24165. * @param {string|Element} id
  24166. * An HTML element - `<video>`, `<audio>`, or `<video-js>` -
  24167. * or a string matching the `id` of such an element.
  24168. *
  24169. * @return {Player|undefined}
  24170. * A player instance or `undefined` if there is no player instance
  24171. * matching the argument.
  24172. */
  24173. videojs.getPlayer = id => {
  24174. const players = Player.players;
  24175. let tag;
  24176. if (typeof id === 'string') {
  24177. const nId = normalizeId(id);
  24178. const player = players[nId];
  24179. if (player) {
  24180. return player;
  24181. }
  24182. tag = $('#' + nId);
  24183. } else {
  24184. tag = id;
  24185. }
  24186. if (isEl(tag)) {
  24187. const {
  24188. player,
  24189. playerId
  24190. } = tag;
  24191. // Element may have a `player` property referring to an already created
  24192. // player instance. If so, return that.
  24193. if (player || players[playerId]) {
  24194. return player || players[playerId];
  24195. }
  24196. }
  24197. };
  24198. /**
  24199. * Returns an array of all current players.
  24200. *
  24201. * @return {Array}
  24202. * An array of all players. The array will be in the order that
  24203. * `Object.keys` provides, which could potentially vary between
  24204. * JavaScript engines.
  24205. *
  24206. */
  24207. videojs.getAllPlayers = () =>
  24208. // Disposed players leave a key with a `null` value, so we need to make sure
  24209. // we filter those out.
  24210. Object.keys(Player.players).map(k => Player.players[k]).filter(Boolean);
  24211. videojs.players = Player.players;
  24212. videojs.getComponent = Component$1.getComponent;
  24213. /**
  24214. * Register a component so it can referred to by name. Used when adding to other
  24215. * components, either through addChild `component.addChild('myComponent')` or through
  24216. * default children options `{ children: ['myComponent'] }`.
  24217. *
  24218. * > NOTE: You could also just initialize the component before adding.
  24219. * `component.addChild(new MyComponent());`
  24220. *
  24221. * @param {string} name
  24222. * The class name of the component
  24223. *
  24224. * @param {Component} comp
  24225. * The component class
  24226. *
  24227. * @return {Component}
  24228. * The newly registered component
  24229. */
  24230. videojs.registerComponent = (name, comp) => {
  24231. if (Tech.isTech(comp)) {
  24232. log$1.warn(`The ${name} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`);
  24233. }
  24234. Component$1.registerComponent.call(Component$1, name, comp);
  24235. };
  24236. videojs.getTech = Tech.getTech;
  24237. videojs.registerTech = Tech.registerTech;
  24238. videojs.use = use;
  24239. /**
  24240. * An object that can be returned by a middleware to signify
  24241. * that the middleware is being terminated.
  24242. *
  24243. * @type {object}
  24244. * @property {object} middleware.TERMINATOR
  24245. */
  24246. Object.defineProperty(videojs, 'middleware', {
  24247. value: {},
  24248. writeable: false,
  24249. enumerable: true
  24250. });
  24251. Object.defineProperty(videojs.middleware, 'TERMINATOR', {
  24252. value: TERMINATOR,
  24253. writeable: false,
  24254. enumerable: true
  24255. });
  24256. /**
  24257. * A reference to the {@link module:browser|browser utility module} as an object.
  24258. *
  24259. * @type {Object}
  24260. * @see {@link module:browser|browser}
  24261. */
  24262. videojs.browser = browser;
  24263. /**
  24264. * A reference to the {@link module:obj|obj utility module} as an object.
  24265. *
  24266. * @type {Object}
  24267. * @see {@link module:obj|obj}
  24268. */
  24269. videojs.obj = Obj;
  24270. /**
  24271. * Deprecated reference to the {@link module:obj.merge|merge function}
  24272. *
  24273. * @type {Function}
  24274. * @see {@link module:obj.merge|merge}
  24275. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.merge instead.
  24276. */
  24277. videojs.mergeOptions = deprecateForMajor(9, 'videojs.mergeOptions', 'videojs.obj.merge', merge$2);
  24278. /**
  24279. * Deprecated reference to the {@link module:obj.defineLazyProperty|defineLazyProperty function}
  24280. *
  24281. * @type {Function}
  24282. * @see {@link module:obj.defineLazyProperty|defineLazyProperty}
  24283. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.defineLazyProperty instead.
  24284. */
  24285. videojs.defineLazyProperty = deprecateForMajor(9, 'videojs.defineLazyProperty', 'videojs.obj.defineLazyProperty', defineLazyProperty);
  24286. /**
  24287. * Deprecated reference to the {@link module:fn.bind_|fn.bind_ function}
  24288. *
  24289. * @type {Function}
  24290. * @see {@link module:fn.bind_|fn.bind_}
  24291. * @deprecated Deprecated and will be removed in 9.0. Please use native Function.prototype.bind instead.
  24292. */
  24293. videojs.bind = deprecateForMajor(9, 'videojs.bind', 'native Function.prototype.bind', bind_);
  24294. videojs.registerPlugin = Plugin.registerPlugin;
  24295. videojs.deregisterPlugin = Plugin.deregisterPlugin;
  24296. /**
  24297. * Deprecated method to register a plugin with Video.js
  24298. *
  24299. * @deprecated Deprecated and will be removed in 9.0. Use videojs.registerPlugin() instead.
  24300. *
  24301. * @param {string} name
  24302. * The plugin name
  24303. *
  24304. * @param {Plugin|Function} plugin
  24305. * The plugin sub-class or function
  24306. */
  24307. videojs.plugin = (name, plugin) => {
  24308. log$1.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');
  24309. return Plugin.registerPlugin(name, plugin);
  24310. };
  24311. videojs.getPlugins = Plugin.getPlugins;
  24312. videojs.getPlugin = Plugin.getPlugin;
  24313. videojs.getPluginVersion = Plugin.getPluginVersion;
  24314. /**
  24315. * Adding languages so that they're available to all players.
  24316. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`
  24317. *
  24318. * @param {string} code
  24319. * The language code or dictionary property
  24320. *
  24321. * @param {Object} data
  24322. * The data values to be translated
  24323. *
  24324. * @return {Object}
  24325. * The resulting language dictionary object
  24326. */
  24327. videojs.addLanguage = function (code, data) {
  24328. code = ('' + code).toLowerCase();
  24329. videojs.options.languages = merge$2(videojs.options.languages, {
  24330. [code]: data
  24331. });
  24332. return videojs.options.languages[code];
  24333. };
  24334. /**
  24335. * A reference to the {@link module:log|log utility module} as an object.
  24336. *
  24337. * @type {Function}
  24338. * @see {@link module:log|log}
  24339. */
  24340. videojs.log = log$1;
  24341. videojs.createLogger = createLogger;
  24342. /**
  24343. * A reference to the {@link module:time|time utility module} as an object.
  24344. *
  24345. * @type {Object}
  24346. * @see {@link module:time|time}
  24347. */
  24348. videojs.time = Time;
  24349. /**
  24350. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  24351. *
  24352. * @type {Function}
  24353. * @see {@link module:time.createTimeRanges|createTimeRanges}
  24354. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  24355. */
  24356. videojs.createTimeRange = deprecateForMajor(9, 'videojs.createTimeRange', 'videojs.time.createTimeRanges', createTimeRanges$1);
  24357. /**
  24358. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  24359. *
  24360. * @type {Function}
  24361. * @see {@link module:time.createTimeRanges|createTimeRanges}
  24362. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  24363. */
  24364. videojs.createTimeRanges = deprecateForMajor(9, 'videojs.createTimeRanges', 'videojs.time.createTimeRanges', createTimeRanges$1);
  24365. /**
  24366. * Deprecated reference to the {@link module:time.formatTime|formatTime function}
  24367. *
  24368. * @type {Function}
  24369. * @see {@link module:time.formatTime|formatTime}
  24370. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.format instead.
  24371. */
  24372. videojs.formatTime = deprecateForMajor(9, 'videojs.formatTime', 'videojs.time.formatTime', formatTime);
  24373. /**
  24374. * Deprecated reference to the {@link module:time.setFormatTime|setFormatTime function}
  24375. *
  24376. * @type {Function}
  24377. * @see {@link module:time.setFormatTime|setFormatTime}
  24378. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.setFormat instead.
  24379. */
  24380. videojs.setFormatTime = deprecateForMajor(9, 'videojs.setFormatTime', 'videojs.time.setFormatTime', setFormatTime);
  24381. /**
  24382. * Deprecated reference to the {@link module:time.resetFormatTime|resetFormatTime function}
  24383. *
  24384. * @type {Function}
  24385. * @see {@link module:time.resetFormatTime|resetFormatTime}
  24386. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.resetFormat instead.
  24387. */
  24388. videojs.resetFormatTime = deprecateForMajor(9, 'videojs.resetFormatTime', 'videojs.time.resetFormatTime', resetFormatTime);
  24389. /**
  24390. * Deprecated reference to the {@link module:url.parseUrl|Url.parseUrl function}
  24391. *
  24392. * @type {Function}
  24393. * @see {@link module:url.parseUrl|parseUrl}
  24394. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.parseUrl instead.
  24395. */
  24396. videojs.parseUrl = deprecateForMajor(9, 'videojs.parseUrl', 'videojs.url.parseUrl', parseUrl);
  24397. /**
  24398. * Deprecated reference to the {@link module:url.isCrossOrigin|Url.isCrossOrigin function}
  24399. *
  24400. * @type {Function}
  24401. * @see {@link module:url.isCrossOrigin|isCrossOrigin}
  24402. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.isCrossOrigin instead.
  24403. */
  24404. videojs.isCrossOrigin = deprecateForMajor(9, 'videojs.isCrossOrigin', 'videojs.url.isCrossOrigin', isCrossOrigin);
  24405. videojs.EventTarget = EventTarget$2;
  24406. videojs.any = any;
  24407. videojs.on = on;
  24408. videojs.one = one;
  24409. videojs.off = off;
  24410. videojs.trigger = trigger;
  24411. /**
  24412. * A cross-browser XMLHttpRequest wrapper.
  24413. *
  24414. * @function
  24415. * @param {Object} options
  24416. * Settings for the request.
  24417. *
  24418. * @return {XMLHttpRequest|XDomainRequest}
  24419. * The request object.
  24420. *
  24421. * @see https://github.com/Raynos/xhr
  24422. */
  24423. videojs.xhr = lib;
  24424. videojs.TextTrack = TextTrack;
  24425. videojs.AudioTrack = AudioTrack;
  24426. videojs.VideoTrack = VideoTrack;
  24427. ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(k => {
  24428. videojs[k] = function () {
  24429. log$1.warn(`videojs.${k}() is deprecated; use videojs.dom.${k}() instead`);
  24430. return Dom[k].apply(null, arguments);
  24431. };
  24432. });
  24433. videojs.computedStyle = deprecateForMajor(9, 'videojs.computedStyle', 'videojs.dom.computedStyle', computedStyle);
  24434. /**
  24435. * A reference to the {@link module:dom|DOM utility module} as an object.
  24436. *
  24437. * @type {Object}
  24438. * @see {@link module:dom|dom}
  24439. */
  24440. videojs.dom = Dom;
  24441. /**
  24442. * A reference to the {@link module:fn|fn utility module} as an object.
  24443. *
  24444. * @type {Object}
  24445. * @see {@link module:fn|fn}
  24446. */
  24447. videojs.fn = Fn;
  24448. /**
  24449. * A reference to the {@link module:num|num utility module} as an object.
  24450. *
  24451. * @type {Object}
  24452. * @see {@link module:num|num}
  24453. */
  24454. videojs.num = Num;
  24455. /**
  24456. * A reference to the {@link module:str|str utility module} as an object.
  24457. *
  24458. * @type {Object}
  24459. * @see {@link module:str|str}
  24460. */
  24461. videojs.str = Str;
  24462. /**
  24463. * A reference to the {@link module:url|URL utility module} as an object.
  24464. *
  24465. * @type {Object}
  24466. * @see {@link module:url|url}
  24467. */
  24468. videojs.url = Url;
  24469. createCommonjsModule(function (module, exports) {
  24470. /*! @name videojs-contrib-quality-levels @version 3.0.0 @license Apache-2.0 */
  24471. (function (global, factory) {
  24472. module.exports = factory(videojs) ;
  24473. })(commonjsGlobal, function (videojs) {
  24474. function _interopDefaultLegacy(e) {
  24475. return e && typeof e === 'object' && 'default' in e ? e : {
  24476. 'default': e
  24477. };
  24478. }
  24479. var videojs__default = /*#__PURE__*/_interopDefaultLegacy(videojs);
  24480. /**
  24481. * A single QualityLevel.
  24482. *
  24483. * interface QualityLevel {
  24484. * readonly attribute DOMString id;
  24485. * attribute DOMString label;
  24486. * readonly attribute long width;
  24487. * readonly attribute long height;
  24488. * readonly attribute long bitrate;
  24489. * attribute boolean enabled;
  24490. * };
  24491. *
  24492. * @class QualityLevel
  24493. */
  24494. class QualityLevel {
  24495. /**
  24496. * Creates a QualityLevel
  24497. *
  24498. * @param {Representation|Object} representation The representation of the quality level
  24499. * @param {string} representation.id Unique id of the QualityLevel
  24500. * @param {number=} representation.width Resolution width of the QualityLevel
  24501. * @param {number=} representation.height Resolution height of the QualityLevel
  24502. * @param {number} representation.bandwidth Bitrate of the QualityLevel
  24503. * @param {number=} representation.frameRate Frame-rate of the QualityLevel
  24504. * @param {Function} representation.enabled Callback to enable/disable QualityLevel
  24505. */
  24506. constructor(representation) {
  24507. let level = this; // eslint-disable-line
  24508. level.id = representation.id;
  24509. level.label = level.id;
  24510. level.width = representation.width;
  24511. level.height = representation.height;
  24512. level.bitrate = representation.bandwidth;
  24513. level.frameRate = representation.frameRate;
  24514. level.enabled_ = representation.enabled;
  24515. Object.defineProperty(level, 'enabled', {
  24516. /**
  24517. * Get whether the QualityLevel is enabled.
  24518. *
  24519. * @return {boolean} True if the QualityLevel is enabled.
  24520. */
  24521. get() {
  24522. return level.enabled_();
  24523. },
  24524. /**
  24525. * Enable or disable the QualityLevel.
  24526. *
  24527. * @param {boolean} enable true to enable QualityLevel, false to disable.
  24528. */
  24529. set(enable) {
  24530. level.enabled_(enable);
  24531. }
  24532. });
  24533. return level;
  24534. }
  24535. }
  24536. /**
  24537. * A list of QualityLevels.
  24538. *
  24539. * interface QualityLevelList : EventTarget {
  24540. * getter QualityLevel (unsigned long index);
  24541. * readonly attribute unsigned long length;
  24542. * readonly attribute long selectedIndex;
  24543. *
  24544. * void addQualityLevel(QualityLevel qualityLevel)
  24545. * void removeQualityLevel(QualityLevel remove)
  24546. * QualityLevel? getQualityLevelById(DOMString id);
  24547. *
  24548. * attribute EventHandler onchange;
  24549. * attribute EventHandler onaddqualitylevel;
  24550. * attribute EventHandler onremovequalitylevel;
  24551. * };
  24552. *
  24553. * @extends videojs.EventTarget
  24554. * @class QualityLevelList
  24555. */
  24556. class QualityLevelList extends videojs__default['default'].EventTarget {
  24557. constructor() {
  24558. super();
  24559. let list = this; // eslint-disable-line
  24560. list.levels_ = [];
  24561. list.selectedIndex_ = -1;
  24562. /**
  24563. * Get the index of the currently selected QualityLevel.
  24564. *
  24565. * @returns {number} The index of the selected QualityLevel. -1 if none selected.
  24566. * @readonly
  24567. */
  24568. Object.defineProperty(list, 'selectedIndex', {
  24569. get() {
  24570. return list.selectedIndex_;
  24571. }
  24572. });
  24573. /**
  24574. * Get the length of the list of QualityLevels.
  24575. *
  24576. * @returns {number} The length of the list.
  24577. * @readonly
  24578. */
  24579. Object.defineProperty(list, 'length', {
  24580. get() {
  24581. return list.levels_.length;
  24582. }
  24583. });
  24584. return list;
  24585. }
  24586. /**
  24587. * Adds a quality level to the list.
  24588. *
  24589. * @param {Representation|Object} representation The representation of the quality level
  24590. * @param {string} representation.id Unique id of the QualityLevel
  24591. * @param {number=} representation.width Resolution width of the QualityLevel
  24592. * @param {number=} representation.height Resolution height of the QualityLevel
  24593. * @param {number} representation.bandwidth Bitrate of the QualityLevel
  24594. * @param {number=} representation.frameRate Frame-rate of the QualityLevel
  24595. * @param {Function} representation.enabled Callback to enable/disable QualityLevel
  24596. * @return {QualityLevel} the QualityLevel added to the list
  24597. * @method addQualityLevel
  24598. */
  24599. addQualityLevel(representation) {
  24600. let qualityLevel = this.getQualityLevelById(representation.id); // Do not add duplicate quality levels
  24601. if (qualityLevel) {
  24602. return qualityLevel;
  24603. }
  24604. const index = this.levels_.length;
  24605. qualityLevel = new QualityLevel(representation);
  24606. if (!('' + index in this)) {
  24607. Object.defineProperty(this, index, {
  24608. get() {
  24609. return this.levels_[index];
  24610. }
  24611. });
  24612. }
  24613. this.levels_.push(qualityLevel);
  24614. this.trigger({
  24615. qualityLevel,
  24616. type: 'addqualitylevel'
  24617. });
  24618. return qualityLevel;
  24619. }
  24620. /**
  24621. * Removes a quality level from the list.
  24622. *
  24623. * @param {QualityLevel} remove QualityLevel to remove to the list.
  24624. * @return {QualityLevel|null} the QualityLevel removed or null if nothing removed
  24625. * @method removeQualityLevel
  24626. */
  24627. removeQualityLevel(qualityLevel) {
  24628. let removed = null;
  24629. for (let i = 0, l = this.length; i < l; i++) {
  24630. if (this[i] === qualityLevel) {
  24631. removed = this.levels_.splice(i, 1)[0];
  24632. if (this.selectedIndex_ === i) {
  24633. this.selectedIndex_ = -1;
  24634. } else if (this.selectedIndex_ > i) {
  24635. this.selectedIndex_--;
  24636. }
  24637. break;
  24638. }
  24639. }
  24640. if (removed) {
  24641. this.trigger({
  24642. qualityLevel,
  24643. type: 'removequalitylevel'
  24644. });
  24645. }
  24646. return removed;
  24647. }
  24648. /**
  24649. * Searches for a QualityLevel with the given id.
  24650. *
  24651. * @param {string} id The id of the QualityLevel to find.
  24652. * @return {QualityLevel|null} The QualityLevel with id, or null if not found.
  24653. * @method getQualityLevelById
  24654. */
  24655. getQualityLevelById(id) {
  24656. for (let i = 0, l = this.length; i < l; i++) {
  24657. const level = this[i];
  24658. if (level.id === id) {
  24659. return level;
  24660. }
  24661. }
  24662. return null;
  24663. }
  24664. /**
  24665. * Resets the list of QualityLevels to empty
  24666. *
  24667. * @method dispose
  24668. */
  24669. dispose() {
  24670. this.selectedIndex_ = -1;
  24671. this.levels_.length = 0;
  24672. }
  24673. }
  24674. /**
  24675. * change - The selected QualityLevel has changed.
  24676. * addqualitylevel - A QualityLevel has been added to the QualityLevelList.
  24677. * removequalitylevel - A QualityLevel has been removed from the QualityLevelList.
  24678. */
  24679. QualityLevelList.prototype.allowedEvents_ = {
  24680. change: 'change',
  24681. addqualitylevel: 'addqualitylevel',
  24682. removequalitylevel: 'removequalitylevel'
  24683. }; // emulate attribute EventHandler support to allow for feature detection
  24684. for (const event in QualityLevelList.prototype.allowedEvents_) {
  24685. QualityLevelList.prototype['on' + event] = null;
  24686. }
  24687. var version = "3.0.0";
  24688. const registerPlugin = videojs__default['default'].registerPlugin || videojs__default['default'].plugin;
  24689. /**
  24690. * Initialization function for the qualityLevels plugin. Sets up the QualityLevelList and
  24691. * event handlers.
  24692. *
  24693. * @param {Player} player Player object.
  24694. * @param {Object} options Plugin options object.
  24695. * @function initPlugin
  24696. */
  24697. const initPlugin = function (player, options) {
  24698. const originalPluginFn = player.qualityLevels;
  24699. const qualityLevelList = new QualityLevelList();
  24700. const disposeHandler = function () {
  24701. qualityLevelList.dispose();
  24702. player.qualityLevels = originalPluginFn;
  24703. player.off('dispose', disposeHandler);
  24704. };
  24705. player.on('dispose', disposeHandler);
  24706. player.qualityLevels = () => qualityLevelList;
  24707. player.qualityLevels.VERSION = version;
  24708. return qualityLevelList;
  24709. };
  24710. /**
  24711. * A video.js plugin.
  24712. *
  24713. * In the plugin function, the value of `this` is a video.js `Player`
  24714. * instance. You cannot rely on the player being in a "ready" state here,
  24715. * depending on how the plugin is invoked. This may or may not be important
  24716. * to you; if not, remove the wait for "ready"!
  24717. *
  24718. * @param {Object} options Plugin options object
  24719. * @function qualityLevels
  24720. */
  24721. const qualityLevels = function (options) {
  24722. return initPlugin(this, videojs__default['default'].mergeOptions({}, options));
  24723. }; // Register the plugin with video.js.
  24724. registerPlugin('qualityLevels', qualityLevels); // Include the version number.
  24725. qualityLevels.VERSION = version;
  24726. return qualityLevels;
  24727. });
  24728. });
  24729. var urlToolkit = createCommonjsModule(function (module, exports) {
  24730. // see https://tools.ietf.org/html/rfc1808
  24731. (function (root) {
  24732. var URL_REGEX = /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  24733. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  24734. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  24735. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  24736. var URLToolkit = {
  24737. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  24738. // E.g
  24739. // With opts.alwaysNormalize = false (default, spec compliant)
  24740. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  24741. // With opts.alwaysNormalize = true (not spec compliant)
  24742. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  24743. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  24744. opts = opts || {};
  24745. // remove any remaining space and CRLF
  24746. baseURL = baseURL.trim();
  24747. relativeURL = relativeURL.trim();
  24748. if (!relativeURL) {
  24749. // 2a) If the embedded URL is entirely empty, it inherits the
  24750. // entire base URL (i.e., is set equal to the base URL)
  24751. // and we are done.
  24752. if (!opts.alwaysNormalize) {
  24753. return baseURL;
  24754. }
  24755. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  24756. if (!basePartsForNormalise) {
  24757. throw new Error('Error trying to parse base URL.');
  24758. }
  24759. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  24760. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  24761. }
  24762. var relativeParts = URLToolkit.parseURL(relativeURL);
  24763. if (!relativeParts) {
  24764. throw new Error('Error trying to parse relative URL.');
  24765. }
  24766. if (relativeParts.scheme) {
  24767. // 2b) If the embedded URL starts with a scheme name, it is
  24768. // interpreted as an absolute URL and we are done.
  24769. if (!opts.alwaysNormalize) {
  24770. return relativeURL;
  24771. }
  24772. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  24773. return URLToolkit.buildURLFromParts(relativeParts);
  24774. }
  24775. var baseParts = URLToolkit.parseURL(baseURL);
  24776. if (!baseParts) {
  24777. throw new Error('Error trying to parse base URL.');
  24778. }
  24779. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  24780. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  24781. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  24782. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  24783. baseParts.netLoc = pathParts[1];
  24784. baseParts.path = pathParts[2];
  24785. }
  24786. if (baseParts.netLoc && !baseParts.path) {
  24787. baseParts.path = '/';
  24788. }
  24789. var builtParts = {
  24790. // 2c) Otherwise, the embedded URL inherits the scheme of
  24791. // the base URL.
  24792. scheme: baseParts.scheme,
  24793. netLoc: relativeParts.netLoc,
  24794. path: null,
  24795. params: relativeParts.params,
  24796. query: relativeParts.query,
  24797. fragment: relativeParts.fragment
  24798. };
  24799. if (!relativeParts.netLoc) {
  24800. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  24801. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  24802. // (if any) of the base URL.
  24803. builtParts.netLoc = baseParts.netLoc;
  24804. // 4) If the embedded URL path is preceded by a slash "/", the
  24805. // path is not relative and we skip to Step 7.
  24806. if (relativeParts.path[0] !== '/') {
  24807. if (!relativeParts.path) {
  24808. // 5) If the embedded URL path is empty (and not preceded by a
  24809. // slash), then the embedded URL inherits the base URL path
  24810. builtParts.path = baseParts.path;
  24811. // 5a) if the embedded URL's <params> is non-empty, we skip to
  24812. // step 7; otherwise, it inherits the <params> of the base
  24813. // URL (if any) and
  24814. if (!relativeParts.params) {
  24815. builtParts.params = baseParts.params;
  24816. // 5b) if the embedded URL's <query> is non-empty, we skip to
  24817. // step 7; otherwise, it inherits the <query> of the base
  24818. // URL (if any) and we skip to step 7.
  24819. if (!relativeParts.query) {
  24820. builtParts.query = baseParts.query;
  24821. }
  24822. }
  24823. } else {
  24824. // 6) The last segment of the base URL's path (anything
  24825. // following the rightmost slash "/", or the entire path if no
  24826. // slash is present) is removed and the embedded URL's path is
  24827. // appended in its place.
  24828. var baseURLPath = baseParts.path;
  24829. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
  24830. builtParts.path = URLToolkit.normalizePath(newPath);
  24831. }
  24832. }
  24833. }
  24834. if (builtParts.path === null) {
  24835. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  24836. }
  24837. return URLToolkit.buildURLFromParts(builtParts);
  24838. },
  24839. parseURL: function (url) {
  24840. var parts = URL_REGEX.exec(url);
  24841. if (!parts) {
  24842. return null;
  24843. }
  24844. return {
  24845. scheme: parts[1] || '',
  24846. netLoc: parts[2] || '',
  24847. path: parts[3] || '',
  24848. params: parts[4] || '',
  24849. query: parts[5] || '',
  24850. fragment: parts[6] || ''
  24851. };
  24852. },
  24853. normalizePath: function (path) {
  24854. // The following operations are
  24855. // then applied, in order, to the new path:
  24856. // 6a) All occurrences of "./", where "." is a complete path
  24857. // segment, are removed.
  24858. // 6b) If the path ends with "." as a complete path segment,
  24859. // that "." is removed.
  24860. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  24861. // 6c) All occurrences of "<segment>/../", where <segment> is a
  24862. // complete path segment not equal to "..", are removed.
  24863. // Removal of these path segments is performed iteratively,
  24864. // removing the leftmost matching pattern on each iteration,
  24865. // until no matching pattern remains.
  24866. // 6d) If the path ends with "<segment>/..", where <segment> is a
  24867. // complete path segment not equal to "..", that
  24868. // "<segment>/.." is removed.
  24869. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {}
  24870. return path.split('').reverse().join('');
  24871. },
  24872. buildURLFromParts: function (parts) {
  24873. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  24874. }
  24875. };
  24876. module.exports = URLToolkit;
  24877. })();
  24878. });
  24879. var DEFAULT_LOCATION$1 = 'http://example.com';
  24880. var resolveUrl$2 = function resolveUrl(baseUrl, relativeUrl) {
  24881. // return early if we don't need to resolve
  24882. if (/^[a-z]+:/i.test(relativeUrl)) {
  24883. return relativeUrl;
  24884. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  24885. if (/^data:/.test(baseUrl)) {
  24886. baseUrl = window.location && window.location.href || '';
  24887. } // IE11 supports URL but not the URL constructor
  24888. // feature detect the behavior we want
  24889. var nativeURL = typeof window.URL === 'function';
  24890. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  24891. // and if baseUrl isn't an absolute url
  24892. var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  24893. if (nativeURL) {
  24894. baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION$1);
  24895. } else if (!/\/\//i.test(baseUrl)) {
  24896. baseUrl = urlToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
  24897. }
  24898. if (nativeURL) {
  24899. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  24900. // and if we're location-less, remove the location
  24901. // otherwise, return the url unmodified
  24902. if (removeLocation) {
  24903. return newUrl.href.slice(DEFAULT_LOCATION$1.length);
  24904. } else if (protocolLess) {
  24905. return newUrl.href.slice(newUrl.protocol.length);
  24906. }
  24907. return newUrl.href;
  24908. }
  24909. return urlToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
  24910. };
  24911. /**
  24912. * @file stream.js
  24913. */
  24914. /**
  24915. * A lightweight readable stream implemention that handles event dispatching.
  24916. *
  24917. * @class Stream
  24918. */
  24919. var Stream = /*#__PURE__*/function () {
  24920. function Stream() {
  24921. this.listeners = {};
  24922. }
  24923. /**
  24924. * Add a listener for a specified event type.
  24925. *
  24926. * @param {string} type the event name
  24927. * @param {Function} listener the callback to be invoked when an event of
  24928. * the specified type occurs
  24929. */
  24930. var _proto = Stream.prototype;
  24931. _proto.on = function on(type, listener) {
  24932. if (!this.listeners[type]) {
  24933. this.listeners[type] = [];
  24934. }
  24935. this.listeners[type].push(listener);
  24936. }
  24937. /**
  24938. * Remove a listener for a specified event type.
  24939. *
  24940. * @param {string} type the event name
  24941. * @param {Function} listener a function previously registered for this
  24942. * type of event through `on`
  24943. * @return {boolean} if we could turn it off or not
  24944. */;
  24945. _proto.off = function off(type, listener) {
  24946. if (!this.listeners[type]) {
  24947. return false;
  24948. }
  24949. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  24950. // In Video.js we slice listener functions
  24951. // on trigger so that it does not mess up the order
  24952. // while we loop through.
  24953. //
  24954. // Here we slice on off so that the loop in trigger
  24955. // can continue using it's old reference to loop without
  24956. // messing up the order.
  24957. this.listeners[type] = this.listeners[type].slice(0);
  24958. this.listeners[type].splice(index, 1);
  24959. return index > -1;
  24960. }
  24961. /**
  24962. * Trigger an event of the specified type on this stream. Any additional
  24963. * arguments to this function are passed as parameters to event listeners.
  24964. *
  24965. * @param {string} type the event name
  24966. */;
  24967. _proto.trigger = function trigger(type) {
  24968. var callbacks = this.listeners[type];
  24969. if (!callbacks) {
  24970. return;
  24971. } // Slicing the arguments on every invocation of this method
  24972. // can add a significant amount of overhead. Avoid the
  24973. // intermediate object creation for the common case of a
  24974. // single callback argument
  24975. if (arguments.length === 2) {
  24976. var length = callbacks.length;
  24977. for (var i = 0; i < length; ++i) {
  24978. callbacks[i].call(this, arguments[1]);
  24979. }
  24980. } else {
  24981. var args = Array.prototype.slice.call(arguments, 1);
  24982. var _length = callbacks.length;
  24983. for (var _i = 0; _i < _length; ++_i) {
  24984. callbacks[_i].apply(this, args);
  24985. }
  24986. }
  24987. }
  24988. /**
  24989. * Destroys the stream and cleans up.
  24990. */;
  24991. _proto.dispose = function dispose() {
  24992. this.listeners = {};
  24993. }
  24994. /**
  24995. * Forwards all `data` events on this stream to the destination stream. The
  24996. * destination stream should provide a method `push` to receive the data
  24997. * events as they arrive.
  24998. *
  24999. * @param {Stream} destination the stream that will receive all `data` events
  25000. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  25001. */;
  25002. _proto.pipe = function pipe(destination) {
  25003. this.on('data', function (data) {
  25004. destination.push(data);
  25005. });
  25006. };
  25007. return Stream;
  25008. }();
  25009. var atob$1 = function atob(s) {
  25010. return window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');
  25011. };
  25012. function decodeB64ToUint8Array$1(b64Text) {
  25013. var decodedString = atob$1(b64Text);
  25014. var array = new Uint8Array(decodedString.length);
  25015. for (var i = 0; i < decodedString.length; i++) {
  25016. array[i] = decodedString.charCodeAt(i);
  25017. }
  25018. return array;
  25019. }
  25020. /*! @name m3u8-parser @version 6.0.0 @license Apache-2.0 */
  25021. /**
  25022. * @file m3u8/line-stream.js
  25023. */
  25024. /**
  25025. * A stream that buffers string input and generates a `data` event for each
  25026. * line.
  25027. *
  25028. * @class LineStream
  25029. * @extends Stream
  25030. */
  25031. class LineStream extends Stream {
  25032. constructor() {
  25033. super();
  25034. this.buffer = '';
  25035. }
  25036. /**
  25037. * Add new data to be parsed.
  25038. *
  25039. * @param {string} data the text to process
  25040. */
  25041. push(data) {
  25042. let nextNewline;
  25043. this.buffer += data;
  25044. nextNewline = this.buffer.indexOf('\n');
  25045. for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
  25046. this.trigger('data', this.buffer.substring(0, nextNewline));
  25047. this.buffer = this.buffer.substring(nextNewline + 1);
  25048. }
  25049. }
  25050. }
  25051. const TAB = String.fromCharCode(0x09);
  25052. const parseByterange = function (byterangeString) {
  25053. // optionally match and capture 0+ digits before `@`
  25054. // optionally match and capture 0+ digits after `@`
  25055. const match = /([0-9.]*)?@?([0-9.]*)?/.exec(byterangeString || '');
  25056. const result = {};
  25057. if (match[1]) {
  25058. result.length = parseInt(match[1], 10);
  25059. }
  25060. if (match[2]) {
  25061. result.offset = parseInt(match[2], 10);
  25062. }
  25063. return result;
  25064. };
  25065. /**
  25066. * "forgiving" attribute list psuedo-grammar:
  25067. * attributes -> keyvalue (',' keyvalue)*
  25068. * keyvalue -> key '=' value
  25069. * key -> [^=]*
  25070. * value -> '"' [^"]* '"' | [^,]*
  25071. */
  25072. const attributeSeparator = function () {
  25073. const key = '[^=]*';
  25074. const value = '"[^"]*"|[^,]*';
  25075. const keyvalue = '(?:' + key + ')=(?:' + value + ')';
  25076. return new RegExp('(?:^|,)(' + keyvalue + ')');
  25077. };
  25078. /**
  25079. * Parse attributes from a line given the separator
  25080. *
  25081. * @param {string} attributes the attribute line to parse
  25082. */
  25083. const parseAttributes$1 = function (attributes) {
  25084. const result = {};
  25085. if (!attributes) {
  25086. return result;
  25087. } // split the string using attributes as the separator
  25088. const attrs = attributes.split(attributeSeparator());
  25089. let i = attrs.length;
  25090. let attr;
  25091. while (i--) {
  25092. // filter out unmatched portions of the string
  25093. if (attrs[i] === '') {
  25094. continue;
  25095. } // split the key and value
  25096. attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1); // trim whitespace and remove optional quotes around the value
  25097. attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
  25098. attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
  25099. attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
  25100. result[attr[0]] = attr[1];
  25101. }
  25102. return result;
  25103. };
  25104. /**
  25105. * A line-level M3U8 parser event stream. It expects to receive input one
  25106. * line at a time and performs a context-free parse of its contents. A stream
  25107. * interpretation of a manifest can be useful if the manifest is expected to
  25108. * be too large to fit comfortably into memory or the entirety of the input
  25109. * is not immediately available. Otherwise, it's probably much easier to work
  25110. * with a regular `Parser` object.
  25111. *
  25112. * Produces `data` events with an object that captures the parser's
  25113. * interpretation of the input. That object has a property `tag` that is one
  25114. * of `uri`, `comment`, or `tag`. URIs only have a single additional
  25115. * property, `line`, which captures the entirety of the input without
  25116. * interpretation. Comments similarly have a single additional property
  25117. * `text` which is the input without the leading `#`.
  25118. *
  25119. * Tags always have a property `tagType` which is the lower-cased version of
  25120. * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
  25121. * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
  25122. * tags are given the tag type `unknown` and a single additional property
  25123. * `data` with the remainder of the input.
  25124. *
  25125. * @class ParseStream
  25126. * @extends Stream
  25127. */
  25128. class ParseStream extends Stream {
  25129. constructor() {
  25130. super();
  25131. this.customParsers = [];
  25132. this.tagMappers = [];
  25133. }
  25134. /**
  25135. * Parses an additional line of input.
  25136. *
  25137. * @param {string} line a single line of an M3U8 file to parse
  25138. */
  25139. push(line) {
  25140. let match;
  25141. let event; // strip whitespace
  25142. line = line.trim();
  25143. if (line.length === 0) {
  25144. // ignore empty lines
  25145. return;
  25146. } // URIs
  25147. if (line[0] !== '#') {
  25148. this.trigger('data', {
  25149. type: 'uri',
  25150. uri: line
  25151. });
  25152. return;
  25153. } // map tags
  25154. const newLines = this.tagMappers.reduce((acc, mapper) => {
  25155. const mappedLine = mapper(line); // skip if unchanged
  25156. if (mappedLine === line) {
  25157. return acc;
  25158. }
  25159. return acc.concat([mappedLine]);
  25160. }, [line]);
  25161. newLines.forEach(newLine => {
  25162. for (let i = 0; i < this.customParsers.length; i++) {
  25163. if (this.customParsers[i].call(this, newLine)) {
  25164. return;
  25165. }
  25166. } // Comments
  25167. if (newLine.indexOf('#EXT') !== 0) {
  25168. this.trigger('data', {
  25169. type: 'comment',
  25170. text: newLine.slice(1)
  25171. });
  25172. return;
  25173. } // strip off any carriage returns here so the regex matching
  25174. // doesn't have to account for them.
  25175. newLine = newLine.replace('\r', ''); // Tags
  25176. match = /^#EXTM3U/.exec(newLine);
  25177. if (match) {
  25178. this.trigger('data', {
  25179. type: 'tag',
  25180. tagType: 'm3u'
  25181. });
  25182. return;
  25183. }
  25184. match = /^#EXTINF:([0-9\.]*)?,?(.*)?$/.exec(newLine);
  25185. if (match) {
  25186. event = {
  25187. type: 'tag',
  25188. tagType: 'inf'
  25189. };
  25190. if (match[1]) {
  25191. event.duration = parseFloat(match[1]);
  25192. }
  25193. if (match[2]) {
  25194. event.title = match[2];
  25195. }
  25196. this.trigger('data', event);
  25197. return;
  25198. }
  25199. match = /^#EXT-X-TARGETDURATION:([0-9.]*)?/.exec(newLine);
  25200. if (match) {
  25201. event = {
  25202. type: 'tag',
  25203. tagType: 'targetduration'
  25204. };
  25205. if (match[1]) {
  25206. event.duration = parseInt(match[1], 10);
  25207. }
  25208. this.trigger('data', event);
  25209. return;
  25210. }
  25211. match = /^#EXT-X-VERSION:([0-9.]*)?/.exec(newLine);
  25212. if (match) {
  25213. event = {
  25214. type: 'tag',
  25215. tagType: 'version'
  25216. };
  25217. if (match[1]) {
  25218. event.version = parseInt(match[1], 10);
  25219. }
  25220. this.trigger('data', event);
  25221. return;
  25222. }
  25223. match = /^#EXT-X-MEDIA-SEQUENCE:(\-?[0-9.]*)?/.exec(newLine);
  25224. if (match) {
  25225. event = {
  25226. type: 'tag',
  25227. tagType: 'media-sequence'
  25228. };
  25229. if (match[1]) {
  25230. event.number = parseInt(match[1], 10);
  25231. }
  25232. this.trigger('data', event);
  25233. return;
  25234. }
  25235. match = /^#EXT-X-DISCONTINUITY-SEQUENCE:(\-?[0-9.]*)?/.exec(newLine);
  25236. if (match) {
  25237. event = {
  25238. type: 'tag',
  25239. tagType: 'discontinuity-sequence'
  25240. };
  25241. if (match[1]) {
  25242. event.number = parseInt(match[1], 10);
  25243. }
  25244. this.trigger('data', event);
  25245. return;
  25246. }
  25247. match = /^#EXT-X-PLAYLIST-TYPE:(.*)?$/.exec(newLine);
  25248. if (match) {
  25249. event = {
  25250. type: 'tag',
  25251. tagType: 'playlist-type'
  25252. };
  25253. if (match[1]) {
  25254. event.playlistType = match[1];
  25255. }
  25256. this.trigger('data', event);
  25257. return;
  25258. }
  25259. match = /^#EXT-X-BYTERANGE:(.*)?$/.exec(newLine);
  25260. if (match) {
  25261. event = _extends$1(parseByterange(match[1]), {
  25262. type: 'tag',
  25263. tagType: 'byterange'
  25264. });
  25265. this.trigger('data', event);
  25266. return;
  25267. }
  25268. match = /^#EXT-X-ALLOW-CACHE:(YES|NO)?/.exec(newLine);
  25269. if (match) {
  25270. event = {
  25271. type: 'tag',
  25272. tagType: 'allow-cache'
  25273. };
  25274. if (match[1]) {
  25275. event.allowed = !/NO/.test(match[1]);
  25276. }
  25277. this.trigger('data', event);
  25278. return;
  25279. }
  25280. match = /^#EXT-X-MAP:(.*)$/.exec(newLine);
  25281. if (match) {
  25282. event = {
  25283. type: 'tag',
  25284. tagType: 'map'
  25285. };
  25286. if (match[1]) {
  25287. const attributes = parseAttributes$1(match[1]);
  25288. if (attributes.URI) {
  25289. event.uri = attributes.URI;
  25290. }
  25291. if (attributes.BYTERANGE) {
  25292. event.byterange = parseByterange(attributes.BYTERANGE);
  25293. }
  25294. }
  25295. this.trigger('data', event);
  25296. return;
  25297. }
  25298. match = /^#EXT-X-STREAM-INF:(.*)$/.exec(newLine);
  25299. if (match) {
  25300. event = {
  25301. type: 'tag',
  25302. tagType: 'stream-inf'
  25303. };
  25304. if (match[1]) {
  25305. event.attributes = parseAttributes$1(match[1]);
  25306. if (event.attributes.RESOLUTION) {
  25307. const split = event.attributes.RESOLUTION.split('x');
  25308. const resolution = {};
  25309. if (split[0]) {
  25310. resolution.width = parseInt(split[0], 10);
  25311. }
  25312. if (split[1]) {
  25313. resolution.height = parseInt(split[1], 10);
  25314. }
  25315. event.attributes.RESOLUTION = resolution;
  25316. }
  25317. if (event.attributes.BANDWIDTH) {
  25318. event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
  25319. }
  25320. if (event.attributes['FRAME-RATE']) {
  25321. event.attributes['FRAME-RATE'] = parseFloat(event.attributes['FRAME-RATE']);
  25322. }
  25323. if (event.attributes['PROGRAM-ID']) {
  25324. event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
  25325. }
  25326. }
  25327. this.trigger('data', event);
  25328. return;
  25329. }
  25330. match = /^#EXT-X-MEDIA:(.*)$/.exec(newLine);
  25331. if (match) {
  25332. event = {
  25333. type: 'tag',
  25334. tagType: 'media'
  25335. };
  25336. if (match[1]) {
  25337. event.attributes = parseAttributes$1(match[1]);
  25338. }
  25339. this.trigger('data', event);
  25340. return;
  25341. }
  25342. match = /^#EXT-X-ENDLIST/.exec(newLine);
  25343. if (match) {
  25344. this.trigger('data', {
  25345. type: 'tag',
  25346. tagType: 'endlist'
  25347. });
  25348. return;
  25349. }
  25350. match = /^#EXT-X-DISCONTINUITY/.exec(newLine);
  25351. if (match) {
  25352. this.trigger('data', {
  25353. type: 'tag',
  25354. tagType: 'discontinuity'
  25355. });
  25356. return;
  25357. }
  25358. match = /^#EXT-X-PROGRAM-DATE-TIME:(.*)$/.exec(newLine);
  25359. if (match) {
  25360. event = {
  25361. type: 'tag',
  25362. tagType: 'program-date-time'
  25363. };
  25364. if (match[1]) {
  25365. event.dateTimeString = match[1];
  25366. event.dateTimeObject = new Date(match[1]);
  25367. }
  25368. this.trigger('data', event);
  25369. return;
  25370. }
  25371. match = /^#EXT-X-KEY:(.*)$/.exec(newLine);
  25372. if (match) {
  25373. event = {
  25374. type: 'tag',
  25375. tagType: 'key'
  25376. };
  25377. if (match[1]) {
  25378. event.attributes = parseAttributes$1(match[1]); // parse the IV string into a Uint32Array
  25379. if (event.attributes.IV) {
  25380. if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
  25381. event.attributes.IV = event.attributes.IV.substring(2);
  25382. }
  25383. event.attributes.IV = event.attributes.IV.match(/.{8}/g);
  25384. event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
  25385. event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
  25386. event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
  25387. event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
  25388. event.attributes.IV = new Uint32Array(event.attributes.IV);
  25389. }
  25390. }
  25391. this.trigger('data', event);
  25392. return;
  25393. }
  25394. match = /^#EXT-X-START:(.*)$/.exec(newLine);
  25395. if (match) {
  25396. event = {
  25397. type: 'tag',
  25398. tagType: 'start'
  25399. };
  25400. if (match[1]) {
  25401. event.attributes = parseAttributes$1(match[1]);
  25402. event.attributes['TIME-OFFSET'] = parseFloat(event.attributes['TIME-OFFSET']);
  25403. event.attributes.PRECISE = /YES/.test(event.attributes.PRECISE);
  25404. }
  25405. this.trigger('data', event);
  25406. return;
  25407. }
  25408. match = /^#EXT-X-CUE-OUT-CONT:(.*)?$/.exec(newLine);
  25409. if (match) {
  25410. event = {
  25411. type: 'tag',
  25412. tagType: 'cue-out-cont'
  25413. };
  25414. if (match[1]) {
  25415. event.data = match[1];
  25416. } else {
  25417. event.data = '';
  25418. }
  25419. this.trigger('data', event);
  25420. return;
  25421. }
  25422. match = /^#EXT-X-CUE-OUT:(.*)?$/.exec(newLine);
  25423. if (match) {
  25424. event = {
  25425. type: 'tag',
  25426. tagType: 'cue-out'
  25427. };
  25428. if (match[1]) {
  25429. event.data = match[1];
  25430. } else {
  25431. event.data = '';
  25432. }
  25433. this.trigger('data', event);
  25434. return;
  25435. }
  25436. match = /^#EXT-X-CUE-IN:(.*)?$/.exec(newLine);
  25437. if (match) {
  25438. event = {
  25439. type: 'tag',
  25440. tagType: 'cue-in'
  25441. };
  25442. if (match[1]) {
  25443. event.data = match[1];
  25444. } else {
  25445. event.data = '';
  25446. }
  25447. this.trigger('data', event);
  25448. return;
  25449. }
  25450. match = /^#EXT-X-SKIP:(.*)$/.exec(newLine);
  25451. if (match && match[1]) {
  25452. event = {
  25453. type: 'tag',
  25454. tagType: 'skip'
  25455. };
  25456. event.attributes = parseAttributes$1(match[1]);
  25457. if (event.attributes.hasOwnProperty('SKIPPED-SEGMENTS')) {
  25458. event.attributes['SKIPPED-SEGMENTS'] = parseInt(event.attributes['SKIPPED-SEGMENTS'], 10);
  25459. }
  25460. if (event.attributes.hasOwnProperty('RECENTLY-REMOVED-DATERANGES')) {
  25461. event.attributes['RECENTLY-REMOVED-DATERANGES'] = event.attributes['RECENTLY-REMOVED-DATERANGES'].split(TAB);
  25462. }
  25463. this.trigger('data', event);
  25464. return;
  25465. }
  25466. match = /^#EXT-X-PART:(.*)$/.exec(newLine);
  25467. if (match && match[1]) {
  25468. event = {
  25469. type: 'tag',
  25470. tagType: 'part'
  25471. };
  25472. event.attributes = parseAttributes$1(match[1]);
  25473. ['DURATION'].forEach(function (key) {
  25474. if (event.attributes.hasOwnProperty(key)) {
  25475. event.attributes[key] = parseFloat(event.attributes[key]);
  25476. }
  25477. });
  25478. ['INDEPENDENT', 'GAP'].forEach(function (key) {
  25479. if (event.attributes.hasOwnProperty(key)) {
  25480. event.attributes[key] = /YES/.test(event.attributes[key]);
  25481. }
  25482. });
  25483. if (event.attributes.hasOwnProperty('BYTERANGE')) {
  25484. event.attributes.byterange = parseByterange(event.attributes.BYTERANGE);
  25485. }
  25486. this.trigger('data', event);
  25487. return;
  25488. }
  25489. match = /^#EXT-X-SERVER-CONTROL:(.*)$/.exec(newLine);
  25490. if (match && match[1]) {
  25491. event = {
  25492. type: 'tag',
  25493. tagType: 'server-control'
  25494. };
  25495. event.attributes = parseAttributes$1(match[1]);
  25496. ['CAN-SKIP-UNTIL', 'PART-HOLD-BACK', 'HOLD-BACK'].forEach(function (key) {
  25497. if (event.attributes.hasOwnProperty(key)) {
  25498. event.attributes[key] = parseFloat(event.attributes[key]);
  25499. }
  25500. });
  25501. ['CAN-SKIP-DATERANGES', 'CAN-BLOCK-RELOAD'].forEach(function (key) {
  25502. if (event.attributes.hasOwnProperty(key)) {
  25503. event.attributes[key] = /YES/.test(event.attributes[key]);
  25504. }
  25505. });
  25506. this.trigger('data', event);
  25507. return;
  25508. }
  25509. match = /^#EXT-X-PART-INF:(.*)$/.exec(newLine);
  25510. if (match && match[1]) {
  25511. event = {
  25512. type: 'tag',
  25513. tagType: 'part-inf'
  25514. };
  25515. event.attributes = parseAttributes$1(match[1]);
  25516. ['PART-TARGET'].forEach(function (key) {
  25517. if (event.attributes.hasOwnProperty(key)) {
  25518. event.attributes[key] = parseFloat(event.attributes[key]);
  25519. }
  25520. });
  25521. this.trigger('data', event);
  25522. return;
  25523. }
  25524. match = /^#EXT-X-PRELOAD-HINT:(.*)$/.exec(newLine);
  25525. if (match && match[1]) {
  25526. event = {
  25527. type: 'tag',
  25528. tagType: 'preload-hint'
  25529. };
  25530. event.attributes = parseAttributes$1(match[1]);
  25531. ['BYTERANGE-START', 'BYTERANGE-LENGTH'].forEach(function (key) {
  25532. if (event.attributes.hasOwnProperty(key)) {
  25533. event.attributes[key] = parseInt(event.attributes[key], 10);
  25534. const subkey = key === 'BYTERANGE-LENGTH' ? 'length' : 'offset';
  25535. event.attributes.byterange = event.attributes.byterange || {};
  25536. event.attributes.byterange[subkey] = event.attributes[key]; // only keep the parsed byterange object.
  25537. delete event.attributes[key];
  25538. }
  25539. });
  25540. this.trigger('data', event);
  25541. return;
  25542. }
  25543. match = /^#EXT-X-RENDITION-REPORT:(.*)$/.exec(newLine);
  25544. if (match && match[1]) {
  25545. event = {
  25546. type: 'tag',
  25547. tagType: 'rendition-report'
  25548. };
  25549. event.attributes = parseAttributes$1(match[1]);
  25550. ['LAST-MSN', 'LAST-PART'].forEach(function (key) {
  25551. if (event.attributes.hasOwnProperty(key)) {
  25552. event.attributes[key] = parseInt(event.attributes[key], 10);
  25553. }
  25554. });
  25555. this.trigger('data', event);
  25556. return;
  25557. } // unknown tag type
  25558. this.trigger('data', {
  25559. type: 'tag',
  25560. data: newLine.slice(4)
  25561. });
  25562. });
  25563. }
  25564. /**
  25565. * Add a parser for custom headers
  25566. *
  25567. * @param {Object} options a map of options for the added parser
  25568. * @param {RegExp} options.expression a regular expression to match the custom header
  25569. * @param {string} options.customType the custom type to register to the output
  25570. * @param {Function} [options.dataParser] function to parse the line into an object
  25571. * @param {boolean} [options.segment] should tag data be attached to the segment object
  25572. */
  25573. addParser({
  25574. expression,
  25575. customType,
  25576. dataParser,
  25577. segment
  25578. }) {
  25579. if (typeof dataParser !== 'function') {
  25580. dataParser = line => line;
  25581. }
  25582. this.customParsers.push(line => {
  25583. const match = expression.exec(line);
  25584. if (match) {
  25585. this.trigger('data', {
  25586. type: 'custom',
  25587. data: dataParser(line),
  25588. customType,
  25589. segment
  25590. });
  25591. return true;
  25592. }
  25593. });
  25594. }
  25595. /**
  25596. * Add a custom header mapper
  25597. *
  25598. * @param {Object} options
  25599. * @param {RegExp} options.expression a regular expression to match the custom header
  25600. * @param {Function} options.map function to translate tag into a different tag
  25601. */
  25602. addTagMapper({
  25603. expression,
  25604. map
  25605. }) {
  25606. const mapFn = line => {
  25607. if (expression.test(line)) {
  25608. return map(line);
  25609. }
  25610. return line;
  25611. };
  25612. this.tagMappers.push(mapFn);
  25613. }
  25614. }
  25615. const camelCase = str => str.toLowerCase().replace(/-(\w)/g, a => a[1].toUpperCase());
  25616. const camelCaseKeys = function (attributes) {
  25617. const result = {};
  25618. Object.keys(attributes).forEach(function (key) {
  25619. result[camelCase(key)] = attributes[key];
  25620. });
  25621. return result;
  25622. }; // set SERVER-CONTROL hold back based upon targetDuration and partTargetDuration
  25623. // we need this helper because defaults are based upon targetDuration and
  25624. // partTargetDuration being set, but they may not be if SERVER-CONTROL appears before
  25625. // target durations are set.
  25626. const setHoldBack = function (manifest) {
  25627. const {
  25628. serverControl,
  25629. targetDuration,
  25630. partTargetDuration
  25631. } = manifest;
  25632. if (!serverControl) {
  25633. return;
  25634. }
  25635. const tag = '#EXT-X-SERVER-CONTROL';
  25636. const hb = 'holdBack';
  25637. const phb = 'partHoldBack';
  25638. const minTargetDuration = targetDuration && targetDuration * 3;
  25639. const minPartDuration = partTargetDuration && partTargetDuration * 2;
  25640. if (targetDuration && !serverControl.hasOwnProperty(hb)) {
  25641. serverControl[hb] = minTargetDuration;
  25642. this.trigger('info', {
  25643. message: `${tag} defaulting HOLD-BACK to targetDuration * 3 (${minTargetDuration}).`
  25644. });
  25645. }
  25646. if (minTargetDuration && serverControl[hb] < minTargetDuration) {
  25647. this.trigger('warn', {
  25648. message: `${tag} clamping HOLD-BACK (${serverControl[hb]}) to targetDuration * 3 (${minTargetDuration})`
  25649. });
  25650. serverControl[hb] = minTargetDuration;
  25651. } // default no part hold back to part target duration * 3
  25652. if (partTargetDuration && !serverControl.hasOwnProperty(phb)) {
  25653. serverControl[phb] = partTargetDuration * 3;
  25654. this.trigger('info', {
  25655. message: `${tag} defaulting PART-HOLD-BACK to partTargetDuration * 3 (${serverControl[phb]}).`
  25656. });
  25657. } // if part hold back is too small default it to part target duration * 2
  25658. if (partTargetDuration && serverControl[phb] < minPartDuration) {
  25659. this.trigger('warn', {
  25660. message: `${tag} clamping PART-HOLD-BACK (${serverControl[phb]}) to partTargetDuration * 2 (${minPartDuration}).`
  25661. });
  25662. serverControl[phb] = minPartDuration;
  25663. }
  25664. };
  25665. /**
  25666. * A parser for M3U8 files. The current interpretation of the input is
  25667. * exposed as a property `manifest` on parser objects. It's just two lines to
  25668. * create and parse a manifest once you have the contents available as a string:
  25669. *
  25670. * ```js
  25671. * var parser = new m3u8.Parser();
  25672. * parser.push(xhr.responseText);
  25673. * ```
  25674. *
  25675. * New input can later be applied to update the manifest object by calling
  25676. * `push` again.
  25677. *
  25678. * The parser attempts to create a usable manifest object even if the
  25679. * underlying input is somewhat nonsensical. It emits `info` and `warning`
  25680. * events during the parse if it encounters input that seems invalid or
  25681. * requires some property of the manifest object to be defaulted.
  25682. *
  25683. * @class Parser
  25684. * @extends Stream
  25685. */
  25686. class Parser extends Stream {
  25687. constructor() {
  25688. super();
  25689. this.lineStream = new LineStream();
  25690. this.parseStream = new ParseStream();
  25691. this.lineStream.pipe(this.parseStream);
  25692. /* eslint-disable consistent-this */
  25693. const self = this;
  25694. /* eslint-enable consistent-this */
  25695. const uris = [];
  25696. let currentUri = {}; // if specified, the active EXT-X-MAP definition
  25697. let currentMap; // if specified, the active decryption key
  25698. let key;
  25699. let hasParts = false;
  25700. const noop = function () {};
  25701. const defaultMediaGroups = {
  25702. 'AUDIO': {},
  25703. 'VIDEO': {},
  25704. 'CLOSED-CAPTIONS': {},
  25705. 'SUBTITLES': {}
  25706. }; // This is the Widevine UUID from DASH IF IOP. The same exact string is
  25707. // used in MPDs with Widevine encrypted streams.
  25708. const widevineUuid = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed'; // group segments into numbered timelines delineated by discontinuities
  25709. let currentTimeline = 0; // the manifest is empty until the parse stream begins delivering data
  25710. this.manifest = {
  25711. allowCache: true,
  25712. discontinuityStarts: [],
  25713. segments: []
  25714. }; // keep track of the last seen segment's byte range end, as segments are not required
  25715. // to provide the offset, in which case it defaults to the next byte after the
  25716. // previous segment
  25717. let lastByterangeEnd = 0; // keep track of the last seen part's byte range end.
  25718. let lastPartByterangeEnd = 0;
  25719. this.on('end', () => {
  25720. // only add preloadSegment if we don't yet have a uri for it.
  25721. // and we actually have parts/preloadHints
  25722. if (currentUri.uri || !currentUri.parts && !currentUri.preloadHints) {
  25723. return;
  25724. }
  25725. if (!currentUri.map && currentMap) {
  25726. currentUri.map = currentMap;
  25727. }
  25728. if (!currentUri.key && key) {
  25729. currentUri.key = key;
  25730. }
  25731. if (!currentUri.timeline && typeof currentTimeline === 'number') {
  25732. currentUri.timeline = currentTimeline;
  25733. }
  25734. this.manifest.preloadSegment = currentUri;
  25735. }); // update the manifest with the m3u8 entry from the parse stream
  25736. this.parseStream.on('data', function (entry) {
  25737. let mediaGroup;
  25738. let rendition;
  25739. ({
  25740. tag() {
  25741. // switch based on the tag type
  25742. (({
  25743. version() {
  25744. if (entry.version) {
  25745. this.manifest.version = entry.version;
  25746. }
  25747. },
  25748. 'allow-cache'() {
  25749. this.manifest.allowCache = entry.allowed;
  25750. if (!('allowed' in entry)) {
  25751. this.trigger('info', {
  25752. message: 'defaulting allowCache to YES'
  25753. });
  25754. this.manifest.allowCache = true;
  25755. }
  25756. },
  25757. byterange() {
  25758. const byterange = {};
  25759. if ('length' in entry) {
  25760. currentUri.byterange = byterange;
  25761. byterange.length = entry.length;
  25762. if (!('offset' in entry)) {
  25763. /*
  25764. * From the latest spec (as of this writing):
  25765. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.2
  25766. *
  25767. * Same text since EXT-X-BYTERANGE's introduction in draft 7:
  25768. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.1)
  25769. *
  25770. * "If o [offset] is not present, the sub-range begins at the next byte
  25771. * following the sub-range of the previous media segment."
  25772. */
  25773. entry.offset = lastByterangeEnd;
  25774. }
  25775. }
  25776. if ('offset' in entry) {
  25777. currentUri.byterange = byterange;
  25778. byterange.offset = entry.offset;
  25779. }
  25780. lastByterangeEnd = byterange.offset + byterange.length;
  25781. },
  25782. endlist() {
  25783. this.manifest.endList = true;
  25784. },
  25785. inf() {
  25786. if (!('mediaSequence' in this.manifest)) {
  25787. this.manifest.mediaSequence = 0;
  25788. this.trigger('info', {
  25789. message: 'defaulting media sequence to zero'
  25790. });
  25791. }
  25792. if (!('discontinuitySequence' in this.manifest)) {
  25793. this.manifest.discontinuitySequence = 0;
  25794. this.trigger('info', {
  25795. message: 'defaulting discontinuity sequence to zero'
  25796. });
  25797. }
  25798. if (entry.duration > 0) {
  25799. currentUri.duration = entry.duration;
  25800. }
  25801. if (entry.duration === 0) {
  25802. currentUri.duration = 0.01;
  25803. this.trigger('info', {
  25804. message: 'updating zero segment duration to a small value'
  25805. });
  25806. }
  25807. this.manifest.segments = uris;
  25808. },
  25809. key() {
  25810. if (!entry.attributes) {
  25811. this.trigger('warn', {
  25812. message: 'ignoring key declaration without attribute list'
  25813. });
  25814. return;
  25815. } // clear the active encryption key
  25816. if (entry.attributes.METHOD === 'NONE') {
  25817. key = null;
  25818. return;
  25819. }
  25820. if (!entry.attributes.URI) {
  25821. this.trigger('warn', {
  25822. message: 'ignoring key declaration without URI'
  25823. });
  25824. return;
  25825. }
  25826. if (entry.attributes.KEYFORMAT === 'com.apple.streamingkeydelivery') {
  25827. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  25828. this.manifest.contentProtection['com.apple.fps.1_0'] = {
  25829. attributes: entry.attributes
  25830. };
  25831. return;
  25832. }
  25833. if (entry.attributes.KEYFORMAT === 'com.microsoft.playready') {
  25834. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  25835. this.manifest.contentProtection['com.microsoft.playready'] = {
  25836. uri: entry.attributes.URI
  25837. };
  25838. return;
  25839. } // check if the content is encrypted for Widevine
  25840. // Widevine/HLS spec: https://storage.googleapis.com/wvdocs/Widevine_DRM_HLS.pdf
  25841. if (entry.attributes.KEYFORMAT === widevineUuid) {
  25842. const VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR', 'SAMPLE-AES-CENC'];
  25843. if (VALID_METHODS.indexOf(entry.attributes.METHOD) === -1) {
  25844. this.trigger('warn', {
  25845. message: 'invalid key method provided for Widevine'
  25846. });
  25847. return;
  25848. }
  25849. if (entry.attributes.METHOD === 'SAMPLE-AES-CENC') {
  25850. this.trigger('warn', {
  25851. message: 'SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead'
  25852. });
  25853. }
  25854. if (entry.attributes.URI.substring(0, 23) !== 'data:text/plain;base64,') {
  25855. this.trigger('warn', {
  25856. message: 'invalid key URI provided for Widevine'
  25857. });
  25858. return;
  25859. }
  25860. if (!(entry.attributes.KEYID && entry.attributes.KEYID.substring(0, 2) === '0x')) {
  25861. this.trigger('warn', {
  25862. message: 'invalid key ID provided for Widevine'
  25863. });
  25864. return;
  25865. } // if Widevine key attributes are valid, store them as `contentProtection`
  25866. // on the manifest to emulate Widevine tag structure in a DASH mpd
  25867. this.manifest.contentProtection = this.manifest.contentProtection || {};
  25868. this.manifest.contentProtection['com.widevine.alpha'] = {
  25869. attributes: {
  25870. schemeIdUri: entry.attributes.KEYFORMAT,
  25871. // remove '0x' from the key id string
  25872. keyId: entry.attributes.KEYID.substring(2)
  25873. },
  25874. // decode the base64-encoded PSSH box
  25875. pssh: decodeB64ToUint8Array$1(entry.attributes.URI.split(',')[1])
  25876. };
  25877. return;
  25878. }
  25879. if (!entry.attributes.METHOD) {
  25880. this.trigger('warn', {
  25881. message: 'defaulting key method to AES-128'
  25882. });
  25883. } // setup an encryption key for upcoming segments
  25884. key = {
  25885. method: entry.attributes.METHOD || 'AES-128',
  25886. uri: entry.attributes.URI
  25887. };
  25888. if (typeof entry.attributes.IV !== 'undefined') {
  25889. key.iv = entry.attributes.IV;
  25890. }
  25891. },
  25892. 'media-sequence'() {
  25893. if (!isFinite(entry.number)) {
  25894. this.trigger('warn', {
  25895. message: 'ignoring invalid media sequence: ' + entry.number
  25896. });
  25897. return;
  25898. }
  25899. this.manifest.mediaSequence = entry.number;
  25900. },
  25901. 'discontinuity-sequence'() {
  25902. if (!isFinite(entry.number)) {
  25903. this.trigger('warn', {
  25904. message: 'ignoring invalid discontinuity sequence: ' + entry.number
  25905. });
  25906. return;
  25907. }
  25908. this.manifest.discontinuitySequence = entry.number;
  25909. currentTimeline = entry.number;
  25910. },
  25911. 'playlist-type'() {
  25912. if (!/VOD|EVENT/.test(entry.playlistType)) {
  25913. this.trigger('warn', {
  25914. message: 'ignoring unknown playlist type: ' + entry.playlist
  25915. });
  25916. return;
  25917. }
  25918. this.manifest.playlistType = entry.playlistType;
  25919. },
  25920. map() {
  25921. currentMap = {};
  25922. if (entry.uri) {
  25923. currentMap.uri = entry.uri;
  25924. }
  25925. if (entry.byterange) {
  25926. currentMap.byterange = entry.byterange;
  25927. }
  25928. if (key) {
  25929. currentMap.key = key;
  25930. }
  25931. },
  25932. 'stream-inf'() {
  25933. this.manifest.playlists = uris;
  25934. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  25935. if (!entry.attributes) {
  25936. this.trigger('warn', {
  25937. message: 'ignoring empty stream-inf attributes'
  25938. });
  25939. return;
  25940. }
  25941. if (!currentUri.attributes) {
  25942. currentUri.attributes = {};
  25943. }
  25944. _extends$1(currentUri.attributes, entry.attributes);
  25945. },
  25946. media() {
  25947. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  25948. if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
  25949. this.trigger('warn', {
  25950. message: 'ignoring incomplete or missing media group'
  25951. });
  25952. return;
  25953. } // find the media group, creating defaults as necessary
  25954. const mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
  25955. mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
  25956. mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']]; // collect the rendition metadata
  25957. rendition = {
  25958. default: /yes/i.test(entry.attributes.DEFAULT)
  25959. };
  25960. if (rendition.default) {
  25961. rendition.autoselect = true;
  25962. } else {
  25963. rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
  25964. }
  25965. if (entry.attributes.LANGUAGE) {
  25966. rendition.language = entry.attributes.LANGUAGE;
  25967. }
  25968. if (entry.attributes.URI) {
  25969. rendition.uri = entry.attributes.URI;
  25970. }
  25971. if (entry.attributes['INSTREAM-ID']) {
  25972. rendition.instreamId = entry.attributes['INSTREAM-ID'];
  25973. }
  25974. if (entry.attributes.CHARACTERISTICS) {
  25975. rendition.characteristics = entry.attributes.CHARACTERISTICS;
  25976. }
  25977. if (entry.attributes.FORCED) {
  25978. rendition.forced = /yes/i.test(entry.attributes.FORCED);
  25979. } // insert the new rendition
  25980. mediaGroup[entry.attributes.NAME] = rendition;
  25981. },
  25982. discontinuity() {
  25983. currentTimeline += 1;
  25984. currentUri.discontinuity = true;
  25985. this.manifest.discontinuityStarts.push(uris.length);
  25986. },
  25987. 'program-date-time'() {
  25988. if (typeof this.manifest.dateTimeString === 'undefined') {
  25989. // PROGRAM-DATE-TIME is a media-segment tag, but for backwards
  25990. // compatibility, we add the first occurence of the PROGRAM-DATE-TIME tag
  25991. // to the manifest object
  25992. // TODO: Consider removing this in future major version
  25993. this.manifest.dateTimeString = entry.dateTimeString;
  25994. this.manifest.dateTimeObject = entry.dateTimeObject;
  25995. }
  25996. currentUri.dateTimeString = entry.dateTimeString;
  25997. currentUri.dateTimeObject = entry.dateTimeObject;
  25998. },
  25999. targetduration() {
  26000. if (!isFinite(entry.duration) || entry.duration < 0) {
  26001. this.trigger('warn', {
  26002. message: 'ignoring invalid target duration: ' + entry.duration
  26003. });
  26004. return;
  26005. }
  26006. this.manifest.targetDuration = entry.duration;
  26007. setHoldBack.call(this, this.manifest);
  26008. },
  26009. start() {
  26010. if (!entry.attributes || isNaN(entry.attributes['TIME-OFFSET'])) {
  26011. this.trigger('warn', {
  26012. message: 'ignoring start declaration without appropriate attribute list'
  26013. });
  26014. return;
  26015. }
  26016. this.manifest.start = {
  26017. timeOffset: entry.attributes['TIME-OFFSET'],
  26018. precise: entry.attributes.PRECISE
  26019. };
  26020. },
  26021. 'cue-out'() {
  26022. currentUri.cueOut = entry.data;
  26023. },
  26024. 'cue-out-cont'() {
  26025. currentUri.cueOutCont = entry.data;
  26026. },
  26027. 'cue-in'() {
  26028. currentUri.cueIn = entry.data;
  26029. },
  26030. 'skip'() {
  26031. this.manifest.skip = camelCaseKeys(entry.attributes);
  26032. this.warnOnMissingAttributes_('#EXT-X-SKIP', entry.attributes, ['SKIPPED-SEGMENTS']);
  26033. },
  26034. 'part'() {
  26035. hasParts = true; // parts are always specifed before a segment
  26036. const segmentIndex = this.manifest.segments.length;
  26037. const part = camelCaseKeys(entry.attributes);
  26038. currentUri.parts = currentUri.parts || [];
  26039. currentUri.parts.push(part);
  26040. if (part.byterange) {
  26041. if (!part.byterange.hasOwnProperty('offset')) {
  26042. part.byterange.offset = lastPartByterangeEnd;
  26043. }
  26044. lastPartByterangeEnd = part.byterange.offset + part.byterange.length;
  26045. }
  26046. const partIndex = currentUri.parts.length - 1;
  26047. this.warnOnMissingAttributes_(`#EXT-X-PART #${partIndex} for segment #${segmentIndex}`, entry.attributes, ['URI', 'DURATION']);
  26048. if (this.manifest.renditionReports) {
  26049. this.manifest.renditionReports.forEach((r, i) => {
  26050. if (!r.hasOwnProperty('lastPart')) {
  26051. this.trigger('warn', {
  26052. message: `#EXT-X-RENDITION-REPORT #${i} lacks required attribute(s): LAST-PART`
  26053. });
  26054. }
  26055. });
  26056. }
  26057. },
  26058. 'server-control'() {
  26059. const attrs = this.manifest.serverControl = camelCaseKeys(entry.attributes);
  26060. if (!attrs.hasOwnProperty('canBlockReload')) {
  26061. attrs.canBlockReload = false;
  26062. this.trigger('info', {
  26063. message: '#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false'
  26064. });
  26065. }
  26066. setHoldBack.call(this, this.manifest);
  26067. if (attrs.canSkipDateranges && !attrs.hasOwnProperty('canSkipUntil')) {
  26068. this.trigger('warn', {
  26069. message: '#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set'
  26070. });
  26071. }
  26072. },
  26073. 'preload-hint'() {
  26074. // parts are always specifed before a segment
  26075. const segmentIndex = this.manifest.segments.length;
  26076. const hint = camelCaseKeys(entry.attributes);
  26077. const isPart = hint.type && hint.type === 'PART';
  26078. currentUri.preloadHints = currentUri.preloadHints || [];
  26079. currentUri.preloadHints.push(hint);
  26080. if (hint.byterange) {
  26081. if (!hint.byterange.hasOwnProperty('offset')) {
  26082. // use last part byterange end or zero if not a part.
  26083. hint.byterange.offset = isPart ? lastPartByterangeEnd : 0;
  26084. if (isPart) {
  26085. lastPartByterangeEnd = hint.byterange.offset + hint.byterange.length;
  26086. }
  26087. }
  26088. }
  26089. const index = currentUri.preloadHints.length - 1;
  26090. this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex}`, entry.attributes, ['TYPE', 'URI']);
  26091. if (!hint.type) {
  26092. return;
  26093. } // search through all preload hints except for the current one for
  26094. // a duplicate type.
  26095. for (let i = 0; i < currentUri.preloadHints.length - 1; i++) {
  26096. const otherHint = currentUri.preloadHints[i];
  26097. if (!otherHint.type) {
  26098. continue;
  26099. }
  26100. if (otherHint.type === hint.type) {
  26101. this.trigger('warn', {
  26102. message: `#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex} has the same TYPE ${hint.type} as preload hint #${i}`
  26103. });
  26104. }
  26105. }
  26106. },
  26107. 'rendition-report'() {
  26108. const report = camelCaseKeys(entry.attributes);
  26109. this.manifest.renditionReports = this.manifest.renditionReports || [];
  26110. this.manifest.renditionReports.push(report);
  26111. const index = this.manifest.renditionReports.length - 1;
  26112. const required = ['LAST-MSN', 'URI'];
  26113. if (hasParts) {
  26114. required.push('LAST-PART');
  26115. }
  26116. this.warnOnMissingAttributes_(`#EXT-X-RENDITION-REPORT #${index}`, entry.attributes, required);
  26117. },
  26118. 'part-inf'() {
  26119. this.manifest.partInf = camelCaseKeys(entry.attributes);
  26120. this.warnOnMissingAttributes_('#EXT-X-PART-INF', entry.attributes, ['PART-TARGET']);
  26121. if (this.manifest.partInf.partTarget) {
  26122. this.manifest.partTargetDuration = this.manifest.partInf.partTarget;
  26123. }
  26124. setHoldBack.call(this, this.manifest);
  26125. }
  26126. })[entry.tagType] || noop).call(self);
  26127. },
  26128. uri() {
  26129. currentUri.uri = entry.uri;
  26130. uris.push(currentUri); // if no explicit duration was declared, use the target duration
  26131. if (this.manifest.targetDuration && !('duration' in currentUri)) {
  26132. this.trigger('warn', {
  26133. message: 'defaulting segment duration to the target duration'
  26134. });
  26135. currentUri.duration = this.manifest.targetDuration;
  26136. } // annotate with encryption information, if necessary
  26137. if (key) {
  26138. currentUri.key = key;
  26139. }
  26140. currentUri.timeline = currentTimeline; // annotate with initialization segment information, if necessary
  26141. if (currentMap) {
  26142. currentUri.map = currentMap;
  26143. } // reset the last byterange end as it needs to be 0 between parts
  26144. lastPartByterangeEnd = 0; // prepare for the next URI
  26145. currentUri = {};
  26146. },
  26147. comment() {// comments are not important for playback
  26148. },
  26149. custom() {
  26150. // if this is segment-level data attach the output to the segment
  26151. if (entry.segment) {
  26152. currentUri.custom = currentUri.custom || {};
  26153. currentUri.custom[entry.customType] = entry.data; // if this is manifest-level data attach to the top level manifest object
  26154. } else {
  26155. this.manifest.custom = this.manifest.custom || {};
  26156. this.manifest.custom[entry.customType] = entry.data;
  26157. }
  26158. }
  26159. })[entry.type].call(self);
  26160. });
  26161. }
  26162. warnOnMissingAttributes_(identifier, attributes, required) {
  26163. const missing = [];
  26164. required.forEach(function (key) {
  26165. if (!attributes.hasOwnProperty(key)) {
  26166. missing.push(key);
  26167. }
  26168. });
  26169. if (missing.length) {
  26170. this.trigger('warn', {
  26171. message: `${identifier} lacks required attribute(s): ${missing.join(', ')}`
  26172. });
  26173. }
  26174. }
  26175. /**
  26176. * Parse the input string and update the manifest object.
  26177. *
  26178. * @param {string} chunk a potentially incomplete portion of the manifest
  26179. */
  26180. push(chunk) {
  26181. this.lineStream.push(chunk);
  26182. }
  26183. /**
  26184. * Flush any remaining input. This can be handy if the last line of an M3U8
  26185. * manifest did not contain a trailing newline but the file has been
  26186. * completely received.
  26187. */
  26188. end() {
  26189. // flush any buffered input
  26190. this.lineStream.push('\n');
  26191. this.trigger('end');
  26192. }
  26193. /**
  26194. * Add an additional parser for non-standard tags
  26195. *
  26196. * @param {Object} options a map of options for the added parser
  26197. * @param {RegExp} options.expression a regular expression to match the custom header
  26198. * @param {string} options.type the type to register to the output
  26199. * @param {Function} [options.dataParser] function to parse the line into an object
  26200. * @param {boolean} [options.segment] should tag data be attached to the segment object
  26201. */
  26202. addParser(options) {
  26203. this.parseStream.addParser(options);
  26204. }
  26205. /**
  26206. * Add a custom header mapper
  26207. *
  26208. * @param {Object} options
  26209. * @param {RegExp} options.expression a regular expression to match the custom header
  26210. * @param {Function} options.map function to translate tag into a different tag
  26211. */
  26212. addTagMapper(options) {
  26213. this.parseStream.addTagMapper(options);
  26214. }
  26215. }
  26216. var regexs = {
  26217. // to determine mime types
  26218. mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
  26219. webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
  26220. ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
  26221. // to determine if a codec is audio or video
  26222. video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
  26223. audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
  26224. text: /^(stpp.ttml.im1t)/,
  26225. // mux.js support regex
  26226. muxerVideo: /^(avc0?1)/,
  26227. muxerAudio: /^(mp4a)/,
  26228. // match nothing as muxer does not support text right now.
  26229. // there cannot never be a character before the start of a string
  26230. // so this matches nothing.
  26231. muxerText: /a^/
  26232. };
  26233. var mediaTypes = ['video', 'audio', 'text'];
  26234. var upperMediaTypes = ['Video', 'Audio', 'Text'];
  26235. /**
  26236. * Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard
  26237. * `avc1.<hhhhhh>`
  26238. *
  26239. * @param {string} codec
  26240. * Codec string to translate
  26241. * @return {string}
  26242. * The translated codec string
  26243. */
  26244. var translateLegacyCodec = function translateLegacyCodec(codec) {
  26245. if (!codec) {
  26246. return codec;
  26247. }
  26248. return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
  26249. var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
  26250. var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
  26251. return 'avc1.' + profileHex + '00' + avcLevelHex;
  26252. });
  26253. };
  26254. /**
  26255. * @typedef {Object} ParsedCodecInfo
  26256. * @property {number} codecCount
  26257. * Number of codecs parsed
  26258. * @property {string} [videoCodec]
  26259. * Parsed video codec (if found)
  26260. * @property {string} [videoObjectTypeIndicator]
  26261. * Video object type indicator (if found)
  26262. * @property {string|null} audioProfile
  26263. * Audio profile
  26264. */
  26265. /**
  26266. * Parses a codec string to retrieve the number of codecs specified, the video codec and
  26267. * object type indicator, and the audio profile.
  26268. *
  26269. * @param {string} [codecString]
  26270. * The codec string to parse
  26271. * @return {ParsedCodecInfo}
  26272. * Parsed codec info
  26273. */
  26274. var parseCodecs = function parseCodecs(codecString) {
  26275. if (codecString === void 0) {
  26276. codecString = '';
  26277. }
  26278. var codecs = codecString.split(',');
  26279. var result = [];
  26280. codecs.forEach(function (codec) {
  26281. codec = codec.trim();
  26282. var codecType;
  26283. mediaTypes.forEach(function (name) {
  26284. var match = regexs[name].exec(codec.toLowerCase());
  26285. if (!match || match.length <= 1) {
  26286. return;
  26287. }
  26288. codecType = name; // maintain codec case
  26289. var type = codec.substring(0, match[1].length);
  26290. var details = codec.replace(type, '');
  26291. result.push({
  26292. type: type,
  26293. details: details,
  26294. mediaType: name
  26295. });
  26296. });
  26297. if (!codecType) {
  26298. result.push({
  26299. type: codec,
  26300. details: '',
  26301. mediaType: 'unknown'
  26302. });
  26303. }
  26304. });
  26305. return result;
  26306. };
  26307. /**
  26308. * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
  26309. * a default alternate audio playlist for the provided audio group.
  26310. *
  26311. * @param {Object} master
  26312. * The master playlist
  26313. * @param {string} audioGroupId
  26314. * ID of the audio group for which to find the default codec info
  26315. * @return {ParsedCodecInfo}
  26316. * Parsed codec info
  26317. */
  26318. var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {
  26319. if (!master.mediaGroups.AUDIO || !audioGroupId) {
  26320. return null;
  26321. }
  26322. var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
  26323. if (!audioGroup) {
  26324. return null;
  26325. }
  26326. for (var name in audioGroup) {
  26327. var audioType = audioGroup[name];
  26328. if (audioType.default && audioType.playlists) {
  26329. // codec should be the same for all playlists within the audio type
  26330. return parseCodecs(audioType.playlists[0].attributes.CODECS);
  26331. }
  26332. }
  26333. return null;
  26334. };
  26335. var isAudioCodec = function isAudioCodec(codec) {
  26336. if (codec === void 0) {
  26337. codec = '';
  26338. }
  26339. return regexs.audio.test(codec.trim().toLowerCase());
  26340. };
  26341. var isTextCodec = function isTextCodec(codec) {
  26342. if (codec === void 0) {
  26343. codec = '';
  26344. }
  26345. return regexs.text.test(codec.trim().toLowerCase());
  26346. };
  26347. var getMimeForCodec = function getMimeForCodec(codecString) {
  26348. if (!codecString || typeof codecString !== 'string') {
  26349. return;
  26350. }
  26351. var codecs = codecString.toLowerCase().split(',').map(function (c) {
  26352. return translateLegacyCodec(c.trim());
  26353. }); // default to video type
  26354. var type = 'video'; // only change to audio type if the only codec we have is
  26355. // audio
  26356. if (codecs.length === 1 && isAudioCodec(codecs[0])) {
  26357. type = 'audio';
  26358. } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
  26359. // text uses application/<container> for now
  26360. type = 'application';
  26361. } // default the container to mp4
  26362. var container = 'mp4'; // every codec must be able to go into the container
  26363. // for that container to be the correct one
  26364. if (codecs.every(function (c) {
  26365. return regexs.mp4.test(c);
  26366. })) {
  26367. container = 'mp4';
  26368. } else if (codecs.every(function (c) {
  26369. return regexs.webm.test(c);
  26370. })) {
  26371. container = 'webm';
  26372. } else if (codecs.every(function (c) {
  26373. return regexs.ogg.test(c);
  26374. })) {
  26375. container = 'ogg';
  26376. }
  26377. return type + "/" + container + ";codecs=\"" + codecString + "\"";
  26378. };
  26379. var browserSupportsCodec = function browserSupportsCodec(codecString) {
  26380. if (codecString === void 0) {
  26381. codecString = '';
  26382. }
  26383. return window.MediaSource && window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
  26384. };
  26385. var muxerSupportsCodec = function muxerSupportsCodec(codecString) {
  26386. if (codecString === void 0) {
  26387. codecString = '';
  26388. }
  26389. return codecString.toLowerCase().split(',').every(function (codec) {
  26390. codec = codec.trim(); // any match is supported.
  26391. for (var i = 0; i < upperMediaTypes.length; i++) {
  26392. var type = upperMediaTypes[i];
  26393. if (regexs["muxer" + type].test(codec)) {
  26394. return true;
  26395. }
  26396. }
  26397. return false;
  26398. });
  26399. };
  26400. var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
  26401. var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
  26402. var MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
  26403. var DASH_REGEX = /^application\/dash\+xml/i;
  26404. /**
  26405. * Returns a string that describes the type of source based on a video source object's
  26406. * media type.
  26407. *
  26408. * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}
  26409. *
  26410. * @param {string} type
  26411. * Video source object media type
  26412. * @return {('hls'|'dash'|'vhs-json'|null)}
  26413. * VHS source type string
  26414. */
  26415. var simpleTypeFromSourceType = function simpleTypeFromSourceType(type) {
  26416. if (MPEGURL_REGEX.test(type)) {
  26417. return 'hls';
  26418. }
  26419. if (DASH_REGEX.test(type)) {
  26420. return 'dash';
  26421. } // Denotes the special case of a manifest object passed to http-streaming instead of a
  26422. // source URL.
  26423. //
  26424. // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.
  26425. //
  26426. // In this case, vnd stands for vendor, video.js for the organization, VHS for this
  26427. // project, and the +json suffix identifies the structure of the media type.
  26428. if (type === 'application/vnd.videojs.vhs+json') {
  26429. return 'vhs-json';
  26430. }
  26431. return null;
  26432. };
  26433. // const log2 = Math.log2 ? Math.log2 : (x) => (Math.log(x) / Math.log(2));
  26434. // we used to do this with log2 but BigInt does not support builtin math
  26435. // Math.ceil(log2(x));
  26436. var countBits = function countBits(x) {
  26437. return x.toString(2).length;
  26438. }; // count the number of whole bytes it would take to represent a number
  26439. var countBytes = function countBytes(x) {
  26440. return Math.ceil(countBits(x) / 8);
  26441. };
  26442. var isArrayBufferView = function isArrayBufferView(obj) {
  26443. if (ArrayBuffer.isView === 'function') {
  26444. return ArrayBuffer.isView(obj);
  26445. }
  26446. return obj && obj.buffer instanceof ArrayBuffer;
  26447. };
  26448. var isTypedArray = function isTypedArray(obj) {
  26449. return isArrayBufferView(obj);
  26450. };
  26451. var toUint8 = function toUint8(bytes) {
  26452. if (bytes instanceof Uint8Array) {
  26453. return bytes;
  26454. }
  26455. if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
  26456. // any non-number or NaN leads to empty uint8array
  26457. // eslint-disable-next-line
  26458. if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
  26459. bytes = 0;
  26460. } else {
  26461. bytes = [bytes];
  26462. }
  26463. }
  26464. return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
  26465. };
  26466. var BigInt = window.BigInt || Number;
  26467. var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  26468. (function () {
  26469. var a = new Uint16Array([0xFFCC]);
  26470. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  26471. if (b[0] === 0xFF) {
  26472. return 'big';
  26473. }
  26474. if (b[0] === 0xCC) {
  26475. return 'little';
  26476. }
  26477. return 'unknown';
  26478. })();
  26479. var bytesToNumber = function bytesToNumber(bytes, _temp) {
  26480. var _ref = _temp === void 0 ? {} : _temp,
  26481. _ref$signed = _ref.signed,
  26482. signed = _ref$signed === void 0 ? false : _ref$signed,
  26483. _ref$le = _ref.le,
  26484. le = _ref$le === void 0 ? false : _ref$le;
  26485. bytes = toUint8(bytes);
  26486. var fn = le ? 'reduce' : 'reduceRight';
  26487. var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
  26488. var number = obj.call(bytes, function (total, byte, i) {
  26489. var exponent = le ? i : Math.abs(i + 1 - bytes.length);
  26490. return total + BigInt(byte) * BYTE_TABLE[exponent];
  26491. }, BigInt(0));
  26492. if (signed) {
  26493. var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
  26494. number = BigInt(number);
  26495. if (number > max) {
  26496. number -= max;
  26497. number -= max;
  26498. number -= BigInt(2);
  26499. }
  26500. }
  26501. return Number(number);
  26502. };
  26503. var numberToBytes = function numberToBytes(number, _temp2) {
  26504. var _ref2 = _temp2 === void 0 ? {} : _temp2,
  26505. _ref2$le = _ref2.le,
  26506. le = _ref2$le === void 0 ? false : _ref2$le;
  26507. // eslint-disable-next-line
  26508. if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
  26509. number = 0;
  26510. }
  26511. number = BigInt(number);
  26512. var byteCount = countBytes(number);
  26513. var bytes = new Uint8Array(new ArrayBuffer(byteCount));
  26514. for (var i = 0; i < byteCount; i++) {
  26515. var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
  26516. bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
  26517. if (number < 0) {
  26518. bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
  26519. bytes[byteIndex] -= i === 0 ? 1 : 2;
  26520. }
  26521. }
  26522. return bytes;
  26523. };
  26524. var stringToBytes = function stringToBytes(string, stringIsBytes) {
  26525. if (typeof string !== 'string' && string && typeof string.toString === 'function') {
  26526. string = string.toString();
  26527. }
  26528. if (typeof string !== 'string') {
  26529. return new Uint8Array();
  26530. } // If the string already is bytes, we don't have to do this
  26531. // otherwise we do this so that we split multi length characters
  26532. // into individual bytes
  26533. if (!stringIsBytes) {
  26534. string = unescape(encodeURIComponent(string));
  26535. }
  26536. var view = new Uint8Array(string.length);
  26537. for (var i = 0; i < string.length; i++) {
  26538. view[i] = string.charCodeAt(i);
  26539. }
  26540. return view;
  26541. };
  26542. var concatTypedArrays = function concatTypedArrays() {
  26543. for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
  26544. buffers[_key] = arguments[_key];
  26545. }
  26546. buffers = buffers.filter(function (b) {
  26547. return b && (b.byteLength || b.length) && typeof b !== 'string';
  26548. });
  26549. if (buffers.length <= 1) {
  26550. // for 0 length we will return empty uint8
  26551. // for 1 length we return the first uint8
  26552. return toUint8(buffers[0]);
  26553. }
  26554. var totalLen = buffers.reduce(function (total, buf, i) {
  26555. return total + (buf.byteLength || buf.length);
  26556. }, 0);
  26557. var tempBuffer = new Uint8Array(totalLen);
  26558. var offset = 0;
  26559. buffers.forEach(function (buf) {
  26560. buf = toUint8(buf);
  26561. tempBuffer.set(buf, offset);
  26562. offset += buf.byteLength;
  26563. });
  26564. return tempBuffer;
  26565. };
  26566. /**
  26567. * Check if the bytes "b" are contained within bytes "a".
  26568. *
  26569. * @param {Uint8Array|Array} a
  26570. * Bytes to check in
  26571. *
  26572. * @param {Uint8Array|Array} b
  26573. * Bytes to check for
  26574. *
  26575. * @param {Object} options
  26576. * options
  26577. *
  26578. * @param {Array|Uint8Array} [offset=0]
  26579. * offset to use when looking at bytes in a
  26580. *
  26581. * @param {Array|Uint8Array} [mask=[]]
  26582. * mask to use on bytes before comparison.
  26583. *
  26584. * @return {boolean}
  26585. * If all bytes in b are inside of a, taking into account
  26586. * bit masks.
  26587. */
  26588. var bytesMatch = function bytesMatch(a, b, _temp3) {
  26589. var _ref3 = _temp3 === void 0 ? {} : _temp3,
  26590. _ref3$offset = _ref3.offset,
  26591. offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
  26592. _ref3$mask = _ref3.mask,
  26593. mask = _ref3$mask === void 0 ? [] : _ref3$mask;
  26594. a = toUint8(a);
  26595. b = toUint8(b); // ie 11 does not support uint8 every
  26596. var fn = b.every ? b.every : Array.prototype.every;
  26597. return b.length && a.length - offset >= b.length &&
  26598. // ie 11 doesn't support every on uin8
  26599. fn.call(b, function (bByte, i) {
  26600. var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
  26601. return bByte === aByte;
  26602. });
  26603. };
  26604. var DEFAULT_LOCATION = 'http://example.com';
  26605. var resolveUrl$1 = function resolveUrl(baseUrl, relativeUrl) {
  26606. // return early if we don't need to resolve
  26607. if (/^[a-z]+:/i.test(relativeUrl)) {
  26608. return relativeUrl;
  26609. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  26610. if (/^data:/.test(baseUrl)) {
  26611. baseUrl = window.location && window.location.href || '';
  26612. } // IE11 supports URL but not the URL constructor
  26613. // feature detect the behavior we want
  26614. var nativeURL = typeof window.URL === 'function';
  26615. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  26616. // and if baseUrl isn't an absolute url
  26617. var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  26618. if (nativeURL) {
  26619. baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION);
  26620. } else if (!/\/\//i.test(baseUrl)) {
  26621. baseUrl = urlToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
  26622. }
  26623. if (nativeURL) {
  26624. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  26625. // and if we're location-less, remove the location
  26626. // otherwise, return the url unmodified
  26627. if (removeLocation) {
  26628. return newUrl.href.slice(DEFAULT_LOCATION.length);
  26629. } else if (protocolLess) {
  26630. return newUrl.href.slice(newUrl.protocol.length);
  26631. }
  26632. return newUrl.href;
  26633. }
  26634. return urlToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
  26635. };
  26636. /**
  26637. * Loops through all supported media groups in master and calls the provided
  26638. * callback for each group
  26639. *
  26640. * @param {Object} master
  26641. * The parsed master manifest object
  26642. * @param {string[]} groups
  26643. * The media groups to call the callback for
  26644. * @param {Function} callback
  26645. * Callback to call for each media group
  26646. */
  26647. var forEachMediaGroup$1 = function forEachMediaGroup(master, groups, callback) {
  26648. groups.forEach(function (mediaType) {
  26649. for (var groupKey in master.mediaGroups[mediaType]) {
  26650. for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
  26651. var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
  26652. callback(mediaProperties, mediaType, groupKey, labelKey);
  26653. }
  26654. }
  26655. });
  26656. };
  26657. var atob = function atob(s) {
  26658. return window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');
  26659. };
  26660. function decodeB64ToUint8Array(b64Text) {
  26661. var decodedString = atob(b64Text);
  26662. var array = new Uint8Array(decodedString.length);
  26663. for (var i = 0; i < decodedString.length; i++) {
  26664. array[i] = decodedString.charCodeAt(i);
  26665. }
  26666. return array;
  26667. }
  26668. /**
  26669. * Ponyfill for `Array.prototype.find` which is only available in ES6 runtimes.
  26670. *
  26671. * Works with anything that has a `length` property and index access properties, including NodeList.
  26672. *
  26673. * @template {unknown} T
  26674. * @param {Array<T> | ({length:number, [number]: T})} list
  26675. * @param {function (item: T, index: number, list:Array<T> | ({length:number, [number]: T})):boolean} predicate
  26676. * @param {Partial<Pick<ArrayConstructor['prototype'], 'find'>>?} ac `Array.prototype` by default,
  26677. * allows injecting a custom implementation in tests
  26678. * @returns {T | undefined}
  26679. *
  26680. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
  26681. * @see https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.find
  26682. */
  26683. function find$1(list, predicate, ac) {
  26684. if (ac === undefined) {
  26685. ac = Array.prototype;
  26686. }
  26687. if (list && typeof ac.find === 'function') {
  26688. return ac.find.call(list, predicate);
  26689. }
  26690. for (var i = 0; i < list.length; i++) {
  26691. if (Object.prototype.hasOwnProperty.call(list, i)) {
  26692. var item = list[i];
  26693. if (predicate.call(undefined, item, i, list)) {
  26694. return item;
  26695. }
  26696. }
  26697. }
  26698. }
  26699. /**
  26700. * "Shallow freezes" an object to render it immutable.
  26701. * Uses `Object.freeze` if available,
  26702. * otherwise the immutability is only in the type.
  26703. *
  26704. * Is used to create "enum like" objects.
  26705. *
  26706. * @template T
  26707. * @param {T} object the object to freeze
  26708. * @param {Pick<ObjectConstructor, 'freeze'> = Object} oc `Object` by default,
  26709. * allows to inject custom object constructor for tests
  26710. * @returns {Readonly<T>}
  26711. *
  26712. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
  26713. */
  26714. function freeze(object, oc) {
  26715. if (oc === undefined) {
  26716. oc = Object;
  26717. }
  26718. return oc && typeof oc.freeze === 'function' ? oc.freeze(object) : object;
  26719. }
  26720. /**
  26721. * Since we can not rely on `Object.assign` we provide a simplified version
  26722. * that is sufficient for our needs.
  26723. *
  26724. * @param {Object} target
  26725. * @param {Object | null | undefined} source
  26726. *
  26727. * @returns {Object} target
  26728. * @throws TypeError if target is not an object
  26729. *
  26730. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  26731. * @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign
  26732. */
  26733. function assign(target, source) {
  26734. if (target === null || typeof target !== 'object') {
  26735. throw new TypeError('target is not an object');
  26736. }
  26737. for (var key in source) {
  26738. if (Object.prototype.hasOwnProperty.call(source, key)) {
  26739. target[key] = source[key];
  26740. }
  26741. }
  26742. return target;
  26743. }
  26744. /**
  26745. * All mime types that are allowed as input to `DOMParser.parseFromString`
  26746. *
  26747. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 MDN
  26748. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype WHATWG HTML Spec
  26749. * @see DOMParser.prototype.parseFromString
  26750. */
  26751. var MIME_TYPE = freeze({
  26752. /**
  26753. * `text/html`, the only mime type that triggers treating an XML document as HTML.
  26754. *
  26755. * @see DOMParser.SupportedType.isHTML
  26756. * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
  26757. * @see https://en.wikipedia.org/wiki/HTML Wikipedia
  26758. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
  26759. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring WHATWG HTML Spec
  26760. */
  26761. HTML: 'text/html',
  26762. /**
  26763. * Helper method to check a mime type if it indicates an HTML document
  26764. *
  26765. * @param {string} [value]
  26766. * @returns {boolean}
  26767. *
  26768. * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
  26769. * @see https://en.wikipedia.org/wiki/HTML Wikipedia
  26770. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
  26771. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */
  26772. isHTML: function (value) {
  26773. return value === MIME_TYPE.HTML;
  26774. },
  26775. /**
  26776. * `application/xml`, the standard mime type for XML documents.
  26777. *
  26778. * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType registration
  26779. * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303
  26780. * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
  26781. */
  26782. XML_APPLICATION: 'application/xml',
  26783. /**
  26784. * `text/html`, an alias for `application/xml`.
  26785. *
  26786. * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303
  26787. * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration
  26788. * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
  26789. */
  26790. XML_TEXT: 'text/xml',
  26791. /**
  26792. * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace,
  26793. * but is parsed as an XML document.
  26794. *
  26795. * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType registration
  26796. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec
  26797. * @see https://en.wikipedia.org/wiki/XHTML Wikipedia
  26798. */
  26799. XML_XHTML_APPLICATION: 'application/xhtml+xml',
  26800. /**
  26801. * `image/svg+xml`,
  26802. *
  26803. * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration
  26804. * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1
  26805. * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia
  26806. */
  26807. XML_SVG_IMAGE: 'image/svg+xml'
  26808. });
  26809. /**
  26810. * Namespaces that are used in this code base.
  26811. *
  26812. * @see http://www.w3.org/TR/REC-xml-names
  26813. */
  26814. var NAMESPACE$3 = freeze({
  26815. /**
  26816. * The XHTML namespace.
  26817. *
  26818. * @see http://www.w3.org/1999/xhtml
  26819. */
  26820. HTML: 'http://www.w3.org/1999/xhtml',
  26821. /**
  26822. * Checks if `uri` equals `NAMESPACE.HTML`.
  26823. *
  26824. * @param {string} [uri]
  26825. *
  26826. * @see NAMESPACE.HTML
  26827. */
  26828. isHTML: function (uri) {
  26829. return uri === NAMESPACE$3.HTML;
  26830. },
  26831. /**
  26832. * The SVG namespace.
  26833. *
  26834. * @see http://www.w3.org/2000/svg
  26835. */
  26836. SVG: 'http://www.w3.org/2000/svg',
  26837. /**
  26838. * The `xml:` namespace.
  26839. *
  26840. * @see http://www.w3.org/XML/1998/namespace
  26841. */
  26842. XML: 'http://www.w3.org/XML/1998/namespace',
  26843. /**
  26844. * The `xmlns:` namespace
  26845. *
  26846. * @see https://www.w3.org/2000/xmlns/
  26847. */
  26848. XMLNS: 'http://www.w3.org/2000/xmlns/'
  26849. });
  26850. var assign_1 = assign;
  26851. var find_1 = find$1;
  26852. var freeze_1 = freeze;
  26853. var MIME_TYPE_1 = MIME_TYPE;
  26854. var NAMESPACE_1 = NAMESPACE$3;
  26855. var conventions = {
  26856. assign: assign_1,
  26857. find: find_1,
  26858. freeze: freeze_1,
  26859. MIME_TYPE: MIME_TYPE_1,
  26860. NAMESPACE: NAMESPACE_1
  26861. };
  26862. var find = conventions.find;
  26863. var NAMESPACE$2 = conventions.NAMESPACE;
  26864. /**
  26865. * A prerequisite for `[].filter`, to drop elements that are empty
  26866. * @param {string} input
  26867. * @returns {boolean}
  26868. */
  26869. function notEmptyString(input) {
  26870. return input !== '';
  26871. }
  26872. /**
  26873. * @see https://infra.spec.whatwg.org/#split-on-ascii-whitespace
  26874. * @see https://infra.spec.whatwg.org/#ascii-whitespace
  26875. *
  26876. * @param {string} input
  26877. * @returns {string[]} (can be empty)
  26878. */
  26879. function splitOnASCIIWhitespace(input) {
  26880. // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE
  26881. return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : [];
  26882. }
  26883. /**
  26884. * Adds element as a key to current if it is not already present.
  26885. *
  26886. * @param {Record<string, boolean | undefined>} current
  26887. * @param {string} element
  26888. * @returns {Record<string, boolean | undefined>}
  26889. */
  26890. function orderedSetReducer(current, element) {
  26891. if (!current.hasOwnProperty(element)) {
  26892. current[element] = true;
  26893. }
  26894. return current;
  26895. }
  26896. /**
  26897. * @see https://infra.spec.whatwg.org/#ordered-set
  26898. * @param {string} input
  26899. * @returns {string[]}
  26900. */
  26901. function toOrderedSet(input) {
  26902. if (!input) return [];
  26903. var list = splitOnASCIIWhitespace(input);
  26904. return Object.keys(list.reduce(orderedSetReducer, {}));
  26905. }
  26906. /**
  26907. * Uses `list.indexOf` to implement something like `Array.prototype.includes`,
  26908. * which we can not rely on being available.
  26909. *
  26910. * @param {any[]} list
  26911. * @returns {function(any): boolean}
  26912. */
  26913. function arrayIncludes(list) {
  26914. return function (element) {
  26915. return list && list.indexOf(element) !== -1;
  26916. };
  26917. }
  26918. function copy(src, dest) {
  26919. for (var p in src) {
  26920. if (Object.prototype.hasOwnProperty.call(src, p)) {
  26921. dest[p] = src[p];
  26922. }
  26923. }
  26924. }
  26925. /**
  26926. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  26927. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  26928. */
  26929. function _extends(Class, Super) {
  26930. var pt = Class.prototype;
  26931. if (!(pt instanceof Super)) {
  26932. function t() {}
  26933. t.prototype = Super.prototype;
  26934. t = new t();
  26935. copy(pt, t);
  26936. Class.prototype = pt = t;
  26937. }
  26938. if (pt.constructor != Class) {
  26939. if (typeof Class != 'function') {
  26940. console.error("unknown Class:" + Class);
  26941. }
  26942. pt.constructor = Class;
  26943. }
  26944. }
  26945. // Node Types
  26946. var NodeType = {};
  26947. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  26948. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  26949. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  26950. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  26951. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  26952. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  26953. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  26954. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  26955. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  26956. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  26957. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  26958. var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
  26959. // ExceptionCode
  26960. var ExceptionCode = {};
  26961. var ExceptionMessage = {};
  26962. ExceptionCode.INDEX_SIZE_ERR = (ExceptionMessage[1] = "Index size error", 1);
  26963. ExceptionCode.DOMSTRING_SIZE_ERR = (ExceptionMessage[2] = "DOMString size error", 2);
  26964. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = (ExceptionMessage[3] = "Hierarchy request error", 3);
  26965. ExceptionCode.WRONG_DOCUMENT_ERR = (ExceptionMessage[4] = "Wrong document", 4);
  26966. ExceptionCode.INVALID_CHARACTER_ERR = (ExceptionMessage[5] = "Invalid character", 5);
  26967. ExceptionCode.NO_DATA_ALLOWED_ERR = (ExceptionMessage[6] = "No data allowed", 6);
  26968. ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = (ExceptionMessage[7] = "No modification allowed", 7);
  26969. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = (ExceptionMessage[8] = "Not found", 8);
  26970. ExceptionCode.NOT_SUPPORTED_ERR = (ExceptionMessage[9] = "Not supported", 9);
  26971. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = (ExceptionMessage[10] = "Attribute in use", 10);
  26972. //level2
  26973. ExceptionCode.INVALID_STATE_ERR = (ExceptionMessage[11] = "Invalid state", 11);
  26974. ExceptionCode.SYNTAX_ERR = (ExceptionMessage[12] = "Syntax error", 12);
  26975. ExceptionCode.INVALID_MODIFICATION_ERR = (ExceptionMessage[13] = "Invalid modification", 13);
  26976. ExceptionCode.NAMESPACE_ERR = (ExceptionMessage[14] = "Invalid namespace", 14);
  26977. ExceptionCode.INVALID_ACCESS_ERR = (ExceptionMessage[15] = "Invalid access", 15);
  26978. /**
  26979. * DOM Level 2
  26980. * Object DOMException
  26981. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  26982. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  26983. */
  26984. function DOMException(code, message) {
  26985. if (message instanceof Error) {
  26986. var error = message;
  26987. } else {
  26988. error = this;
  26989. Error.call(this, ExceptionMessage[code]);
  26990. this.message = ExceptionMessage[code];
  26991. if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  26992. }
  26993. error.code = code;
  26994. if (message) this.message = this.message + ": " + message;
  26995. return error;
  26996. }
  26997. DOMException.prototype = Error.prototype;
  26998. copy(ExceptionCode, DOMException);
  26999. /**
  27000. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  27001. * 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.
  27002. * The items in the NodeList are accessible via an integral index, starting from 0.
  27003. */
  27004. function NodeList() {}
  27005. NodeList.prototype = {
  27006. /**
  27007. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  27008. * @standard level1
  27009. */
  27010. length: 0,
  27011. /**
  27012. * 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.
  27013. * @standard level1
  27014. * @param index unsigned long
  27015. * Index into the collection.
  27016. * @return Node
  27017. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  27018. */
  27019. item: function (index) {
  27020. return this[index] || null;
  27021. },
  27022. toString: function (isHTML, nodeFilter) {
  27023. for (var buf = [], i = 0; i < this.length; i++) {
  27024. serializeToString(this[i], buf, isHTML, nodeFilter);
  27025. }
  27026. return buf.join('');
  27027. },
  27028. /**
  27029. * @private
  27030. * @param {function (Node):boolean} predicate
  27031. * @returns {Node[]}
  27032. */
  27033. filter: function (predicate) {
  27034. return Array.prototype.filter.call(this, predicate);
  27035. },
  27036. /**
  27037. * @private
  27038. * @param {Node} item
  27039. * @returns {number}
  27040. */
  27041. indexOf: function (item) {
  27042. return Array.prototype.indexOf.call(this, item);
  27043. }
  27044. };
  27045. function LiveNodeList(node, refresh) {
  27046. this._node = node;
  27047. this._refresh = refresh;
  27048. _updateLiveList(this);
  27049. }
  27050. function _updateLiveList(list) {
  27051. var inc = list._node._inc || list._node.ownerDocument._inc;
  27052. if (list._inc != inc) {
  27053. var ls = list._refresh(list._node);
  27054. //console.log(ls.length)
  27055. __set__(list, 'length', ls.length);
  27056. copy(ls, list);
  27057. list._inc = inc;
  27058. }
  27059. }
  27060. LiveNodeList.prototype.item = function (i) {
  27061. _updateLiveList(this);
  27062. return this[i];
  27063. };
  27064. _extends(LiveNodeList, NodeList);
  27065. /**
  27066. * Objects implementing the NamedNodeMap interface are used
  27067. * to represent collections of nodes that can be accessed by name.
  27068. * Note that NamedNodeMap does not inherit from NodeList;
  27069. * NamedNodeMaps are not maintained in any particular order.
  27070. * Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index,
  27071. * but this is simply to allow convenient enumeration of the contents of a NamedNodeMap,
  27072. * and does not imply that the DOM specifies an order to these Nodes.
  27073. * NamedNodeMap objects in the DOM are live.
  27074. * used for attributes or DocumentType entities
  27075. */
  27076. function NamedNodeMap() {}
  27077. function _findNodeIndex(list, node) {
  27078. var i = list.length;
  27079. while (i--) {
  27080. if (list[i] === node) {
  27081. return i;
  27082. }
  27083. }
  27084. }
  27085. function _addNamedNode(el, list, newAttr, oldAttr) {
  27086. if (oldAttr) {
  27087. list[_findNodeIndex(list, oldAttr)] = newAttr;
  27088. } else {
  27089. list[list.length++] = newAttr;
  27090. }
  27091. if (el) {
  27092. newAttr.ownerElement = el;
  27093. var doc = el.ownerDocument;
  27094. if (doc) {
  27095. oldAttr && _onRemoveAttribute(doc, el, oldAttr);
  27096. _onAddAttribute(doc, el, newAttr);
  27097. }
  27098. }
  27099. }
  27100. function _removeNamedNode(el, list, attr) {
  27101. //console.log('remove attr:'+attr)
  27102. var i = _findNodeIndex(list, attr);
  27103. if (i >= 0) {
  27104. var lastIndex = list.length - 1;
  27105. while (i < lastIndex) {
  27106. list[i] = list[++i];
  27107. }
  27108. list.length = lastIndex;
  27109. if (el) {
  27110. var doc = el.ownerDocument;
  27111. if (doc) {
  27112. _onRemoveAttribute(doc, el, attr);
  27113. attr.ownerElement = null;
  27114. }
  27115. }
  27116. } else {
  27117. throw new DOMException(NOT_FOUND_ERR, new Error(el.tagName + '@' + attr));
  27118. }
  27119. }
  27120. NamedNodeMap.prototype = {
  27121. length: 0,
  27122. item: NodeList.prototype.item,
  27123. getNamedItem: function (key) {
  27124. // if(key.indexOf(':')>0 || key == 'xmlns'){
  27125. // return null;
  27126. // }
  27127. //console.log()
  27128. var i = this.length;
  27129. while (i--) {
  27130. var attr = this[i];
  27131. //console.log(attr.nodeName,key)
  27132. if (attr.nodeName == key) {
  27133. return attr;
  27134. }
  27135. }
  27136. },
  27137. setNamedItem: function (attr) {
  27138. var el = attr.ownerElement;
  27139. if (el && el != this._ownerElement) {
  27140. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  27141. }
  27142. var oldAttr = this.getNamedItem(attr.nodeName);
  27143. _addNamedNode(this._ownerElement, this, attr, oldAttr);
  27144. return oldAttr;
  27145. },
  27146. /* returns Node */
  27147. setNamedItemNS: function (attr) {
  27148. // raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  27149. var el = attr.ownerElement,
  27150. oldAttr;
  27151. if (el && el != this._ownerElement) {
  27152. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  27153. }
  27154. oldAttr = this.getNamedItemNS(attr.namespaceURI, attr.localName);
  27155. _addNamedNode(this._ownerElement, this, attr, oldAttr);
  27156. return oldAttr;
  27157. },
  27158. /* returns Node */
  27159. removeNamedItem: function (key) {
  27160. var attr = this.getNamedItem(key);
  27161. _removeNamedNode(this._ownerElement, this, attr);
  27162. return attr;
  27163. },
  27164. // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  27165. //for level2
  27166. removeNamedItemNS: function (namespaceURI, localName) {
  27167. var attr = this.getNamedItemNS(namespaceURI, localName);
  27168. _removeNamedNode(this._ownerElement, this, attr);
  27169. return attr;
  27170. },
  27171. getNamedItemNS: function (namespaceURI, localName) {
  27172. var i = this.length;
  27173. while (i--) {
  27174. var node = this[i];
  27175. if (node.localName == localName && node.namespaceURI == namespaceURI) {
  27176. return node;
  27177. }
  27178. }
  27179. return null;
  27180. }
  27181. };
  27182. /**
  27183. * The DOMImplementation interface represents an object providing methods
  27184. * which are not dependent on any particular document.
  27185. * Such an object is returned by the `Document.implementation` property.
  27186. *
  27187. * __The individual methods describe the differences compared to the specs.__
  27188. *
  27189. * @constructor
  27190. *
  27191. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation MDN
  27192. * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 DOM Level 1 Core (Initial)
  27193. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-102161490 DOM Level 2 Core
  27194. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core
  27195. * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard
  27196. */
  27197. function DOMImplementation$1() {}
  27198. DOMImplementation$1.prototype = {
  27199. /**
  27200. * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given feature is supported.
  27201. * The different implementations fairly diverged in what kind of features were reported.
  27202. * The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use.
  27203. *
  27204. * @deprecated It is deprecated and modern browsers return true in all cases.
  27205. *
  27206. * @param {string} feature
  27207. * @param {string} [version]
  27208. * @returns {boolean} always true
  27209. *
  27210. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN
  27211. * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core
  27212. * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard
  27213. */
  27214. hasFeature: function (feature, version) {
  27215. return true;
  27216. },
  27217. /**
  27218. * Creates an XML Document object of the specified type with its document element.
  27219. *
  27220. * __It behaves slightly different from the description in the living standard__:
  27221. * - There is no interface/class `XMLDocument`, it returns a `Document` instance.
  27222. * - `contentType`, `encoding`, `mode`, `origin`, `url` fields are currently not declared.
  27223. * - this implementation is not validating names or qualified names
  27224. * (when parsing XML strings, the SAX parser takes care of that)
  27225. *
  27226. * @param {string|null} namespaceURI
  27227. * @param {string} qualifiedName
  27228. * @param {DocumentType=null} doctype
  27229. * @returns {Document}
  27230. *
  27231. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN
  27232. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM Level 2 Core (initial)
  27233. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core
  27234. *
  27235. * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
  27236. * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
  27237. * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
  27238. */
  27239. createDocument: function (namespaceURI, qualifiedName, doctype) {
  27240. var doc = new Document();
  27241. doc.implementation = this;
  27242. doc.childNodes = new NodeList();
  27243. doc.doctype = doctype || null;
  27244. if (doctype) {
  27245. doc.appendChild(doctype);
  27246. }
  27247. if (qualifiedName) {
  27248. var root = doc.createElementNS(namespaceURI, qualifiedName);
  27249. doc.appendChild(root);
  27250. }
  27251. return doc;
  27252. },
  27253. /**
  27254. * Returns a doctype, with the given `qualifiedName`, `publicId`, and `systemId`.
  27255. *
  27256. * __This behavior is slightly different from the in the specs__:
  27257. * - this implementation is not validating names or qualified names
  27258. * (when parsing XML strings, the SAX parser takes care of that)
  27259. *
  27260. * @param {string} qualifiedName
  27261. * @param {string} [publicId]
  27262. * @param {string} [systemId]
  27263. * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` upon document creation
  27264. * or can be put into the document via methods like `Node.insertBefore()` or `Node.replaceChild()`
  27265. *
  27266. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType MDN
  27267. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM Level 2 Core
  27268. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living Standard
  27269. *
  27270. * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
  27271. * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
  27272. * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
  27273. */
  27274. createDocumentType: function (qualifiedName, publicId, systemId) {
  27275. var node = new DocumentType();
  27276. node.name = qualifiedName;
  27277. node.nodeName = qualifiedName;
  27278. node.publicId = publicId || '';
  27279. node.systemId = systemId || '';
  27280. return node;
  27281. }
  27282. };
  27283. /**
  27284. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  27285. */
  27286. function Node() {}
  27287. Node.prototype = {
  27288. firstChild: null,
  27289. lastChild: null,
  27290. previousSibling: null,
  27291. nextSibling: null,
  27292. attributes: null,
  27293. parentNode: null,
  27294. childNodes: null,
  27295. ownerDocument: null,
  27296. nodeValue: null,
  27297. namespaceURI: null,
  27298. prefix: null,
  27299. localName: null,
  27300. // Modified in DOM Level 2:
  27301. insertBefore: function (newChild, refChild) {
  27302. //raises
  27303. return _insertBefore(this, newChild, refChild);
  27304. },
  27305. replaceChild: function (newChild, oldChild) {
  27306. //raises
  27307. _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);
  27308. if (oldChild) {
  27309. this.removeChild(oldChild);
  27310. }
  27311. },
  27312. removeChild: function (oldChild) {
  27313. return _removeChild(this, oldChild);
  27314. },
  27315. appendChild: function (newChild) {
  27316. return this.insertBefore(newChild, null);
  27317. },
  27318. hasChildNodes: function () {
  27319. return this.firstChild != null;
  27320. },
  27321. cloneNode: function (deep) {
  27322. return cloneNode(this.ownerDocument || this, this, deep);
  27323. },
  27324. // Modified in DOM Level 2:
  27325. normalize: function () {
  27326. var child = this.firstChild;
  27327. while (child) {
  27328. var next = child.nextSibling;
  27329. if (next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE) {
  27330. this.removeChild(next);
  27331. child.appendData(next.data);
  27332. } else {
  27333. child.normalize();
  27334. child = next;
  27335. }
  27336. }
  27337. },
  27338. // Introduced in DOM Level 2:
  27339. isSupported: function (feature, version) {
  27340. return this.ownerDocument.implementation.hasFeature(feature, version);
  27341. },
  27342. // Introduced in DOM Level 2:
  27343. hasAttributes: function () {
  27344. return this.attributes.length > 0;
  27345. },
  27346. /**
  27347. * Look up the prefix associated to the given namespace URI, starting from this node.
  27348. * **The default namespace declarations are ignored by this method.**
  27349. * See Namespace Prefix Lookup for details on the algorithm used by this method.
  27350. *
  27351. * _Note: The implementation seems to be incomplete when compared to the algorithm described in the specs._
  27352. *
  27353. * @param {string | null} namespaceURI
  27354. * @returns {string | null}
  27355. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix
  27356. * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo
  27357. * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix
  27358. * @see https://github.com/xmldom/xmldom/issues/322
  27359. */
  27360. lookupPrefix: function (namespaceURI) {
  27361. var el = this;
  27362. while (el) {
  27363. var map = el._nsMap;
  27364. //console.dir(map)
  27365. if (map) {
  27366. for (var n in map) {
  27367. if (Object.prototype.hasOwnProperty.call(map, n) && map[n] === namespaceURI) {
  27368. return n;
  27369. }
  27370. }
  27371. }
  27372. el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
  27373. }
  27374. return null;
  27375. },
  27376. // Introduced in DOM Level 3:
  27377. lookupNamespaceURI: function (prefix) {
  27378. var el = this;
  27379. while (el) {
  27380. var map = el._nsMap;
  27381. //console.dir(map)
  27382. if (map) {
  27383. if (Object.prototype.hasOwnProperty.call(map, prefix)) {
  27384. return map[prefix];
  27385. }
  27386. }
  27387. el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
  27388. }
  27389. return null;
  27390. },
  27391. // Introduced in DOM Level 3:
  27392. isDefaultNamespace: function (namespaceURI) {
  27393. var prefix = this.lookupPrefix(namespaceURI);
  27394. return prefix == null;
  27395. }
  27396. };
  27397. function _xmlEncoder(c) {
  27398. return c == '<' && '&lt;' || c == '>' && '&gt;' || c == '&' && '&amp;' || c == '"' && '&quot;' || '&#' + c.charCodeAt() + ';';
  27399. }
  27400. copy(NodeType, Node);
  27401. copy(NodeType, Node.prototype);
  27402. /**
  27403. * @param callback return true for continue,false for break
  27404. * @return boolean true: break visit;
  27405. */
  27406. function _visitNode(node, callback) {
  27407. if (callback(node)) {
  27408. return true;
  27409. }
  27410. if (node = node.firstChild) {
  27411. do {
  27412. if (_visitNode(node, callback)) {
  27413. return true;
  27414. }
  27415. } while (node = node.nextSibling);
  27416. }
  27417. }
  27418. function Document() {
  27419. this.ownerDocument = this;
  27420. }
  27421. function _onAddAttribute(doc, el, newAttr) {
  27422. doc && doc._inc++;
  27423. var ns = newAttr.namespaceURI;
  27424. if (ns === NAMESPACE$2.XMLNS) {
  27425. //update namespace
  27426. el._nsMap[newAttr.prefix ? newAttr.localName : ''] = newAttr.value;
  27427. }
  27428. }
  27429. function _onRemoveAttribute(doc, el, newAttr, remove) {
  27430. doc && doc._inc++;
  27431. var ns = newAttr.namespaceURI;
  27432. if (ns === NAMESPACE$2.XMLNS) {
  27433. //update namespace
  27434. delete el._nsMap[newAttr.prefix ? newAttr.localName : ''];
  27435. }
  27436. }
  27437. /**
  27438. * Updates `el.childNodes`, updating the indexed items and it's `length`.
  27439. * Passing `newChild` means it will be appended.
  27440. * Otherwise it's assumed that an item has been removed,
  27441. * and `el.firstNode` and it's `.nextSibling` are used
  27442. * to walk the current list of child nodes.
  27443. *
  27444. * @param {Document} doc
  27445. * @param {Node} el
  27446. * @param {Node} [newChild]
  27447. * @private
  27448. */
  27449. function _onUpdateChild(doc, el, newChild) {
  27450. if (doc && doc._inc) {
  27451. doc._inc++;
  27452. //update childNodes
  27453. var cs = el.childNodes;
  27454. if (newChild) {
  27455. cs[cs.length++] = newChild;
  27456. } else {
  27457. var child = el.firstChild;
  27458. var i = 0;
  27459. while (child) {
  27460. cs[i++] = child;
  27461. child = child.nextSibling;
  27462. }
  27463. cs.length = i;
  27464. delete cs[cs.length];
  27465. }
  27466. }
  27467. }
  27468. /**
  27469. * Removes the connections between `parentNode` and `child`
  27470. * and any existing `child.previousSibling` or `child.nextSibling`.
  27471. *
  27472. * @see https://github.com/xmldom/xmldom/issues/135
  27473. * @see https://github.com/xmldom/xmldom/issues/145
  27474. *
  27475. * @param {Node} parentNode
  27476. * @param {Node} child
  27477. * @returns {Node} the child that was removed.
  27478. * @private
  27479. */
  27480. function _removeChild(parentNode, child) {
  27481. var previous = child.previousSibling;
  27482. var next = child.nextSibling;
  27483. if (previous) {
  27484. previous.nextSibling = next;
  27485. } else {
  27486. parentNode.firstChild = next;
  27487. }
  27488. if (next) {
  27489. next.previousSibling = previous;
  27490. } else {
  27491. parentNode.lastChild = previous;
  27492. }
  27493. child.parentNode = null;
  27494. child.previousSibling = null;
  27495. child.nextSibling = null;
  27496. _onUpdateChild(parentNode.ownerDocument, parentNode);
  27497. return child;
  27498. }
  27499. /**
  27500. * Returns `true` if `node` can be a parent for insertion.
  27501. * @param {Node} node
  27502. * @returns {boolean}
  27503. */
  27504. function hasValidParentNodeType(node) {
  27505. return node && (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE);
  27506. }
  27507. /**
  27508. * Returns `true` if `node` can be inserted according to it's `nodeType`.
  27509. * @param {Node} node
  27510. * @returns {boolean}
  27511. */
  27512. function hasInsertableNodeType(node) {
  27513. 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);
  27514. }
  27515. /**
  27516. * Returns true if `node` is a DOCTYPE node
  27517. * @param {Node} node
  27518. * @returns {boolean}
  27519. */
  27520. function isDocTypeNode(node) {
  27521. return node && node.nodeType === Node.DOCUMENT_TYPE_NODE;
  27522. }
  27523. /**
  27524. * Returns true if the node is an element
  27525. * @param {Node} node
  27526. * @returns {boolean}
  27527. */
  27528. function isElementNode(node) {
  27529. return node && node.nodeType === Node.ELEMENT_NODE;
  27530. }
  27531. /**
  27532. * Returns true if `node` is a text node
  27533. * @param {Node} node
  27534. * @returns {boolean}
  27535. */
  27536. function isTextNode(node) {
  27537. return node && node.nodeType === Node.TEXT_NODE;
  27538. }
  27539. /**
  27540. * Check if en element node can be inserted before `child`, or at the end if child is falsy,
  27541. * according to the presence and position of a doctype node on the same level.
  27542. *
  27543. * @param {Document} doc The document node
  27544. * @param {Node} child the node that would become the nextSibling if the element would be inserted
  27545. * @returns {boolean} `true` if an element can be inserted before child
  27546. * @private
  27547. * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  27548. */
  27549. function isElementInsertionPossible(doc, child) {
  27550. var parentChildNodes = doc.childNodes || [];
  27551. if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) {
  27552. return false;
  27553. }
  27554. var docTypeNode = find(parentChildNodes, isDocTypeNode);
  27555. return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));
  27556. }
  27557. /**
  27558. * Check if en element node can be inserted before `child`, or at the end if child is falsy,
  27559. * according to the presence and position of a doctype node on the same level.
  27560. *
  27561. * @param {Node} doc The document node
  27562. * @param {Node} child the node that would become the nextSibling if the element would be inserted
  27563. * @returns {boolean} `true` if an element can be inserted before child
  27564. * @private
  27565. * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  27566. */
  27567. function isElementReplacementPossible(doc, child) {
  27568. var parentChildNodes = doc.childNodes || [];
  27569. function hasElementChildThatIsNotChild(node) {
  27570. return isElementNode(node) && node !== child;
  27571. }
  27572. if (find(parentChildNodes, hasElementChildThatIsNotChild)) {
  27573. return false;
  27574. }
  27575. var docTypeNode = find(parentChildNodes, isDocTypeNode);
  27576. return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));
  27577. }
  27578. /**
  27579. * @private
  27580. * Steps 1-5 of the checks before inserting and before replacing a child are the same.
  27581. *
  27582. * @param {Node} parent the parent node to insert `node` into
  27583. * @param {Node} node the node to insert
  27584. * @param {Node=} child the node that should become the `nextSibling` of `node`
  27585. * @returns {Node}
  27586. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  27587. * @throws DOMException if `child` is provided but is not a child of `parent`.
  27588. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  27589. * @see https://dom.spec.whatwg.org/#concept-node-replace
  27590. */
  27591. function assertPreInsertionValidity1to5(parent, node, child) {
  27592. // 1. If `parent` is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException.
  27593. if (!hasValidParentNodeType(parent)) {
  27594. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Unexpected parent node type ' + parent.nodeType);
  27595. }
  27596. // 2. If `node` is a host-including inclusive ancestor of `parent`, then throw a "HierarchyRequestError" DOMException.
  27597. // not implemented!
  27598. // 3. If `child` is non-null and its parent is not `parent`, then throw a "NotFoundError" DOMException.
  27599. if (child && child.parentNode !== parent) {
  27600. throw new DOMException(NOT_FOUND_ERR, 'child not in parent');
  27601. }
  27602. if (
  27603. // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
  27604. !hasInsertableNodeType(node) ||
  27605. // 5. If either `node` is a Text node and `parent` is a document,
  27606. // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0
  27607. // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE)
  27608. // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException.
  27609. isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE) {
  27610. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Unexpected node type ' + node.nodeType + ' for parent node type ' + parent.nodeType);
  27611. }
  27612. }
  27613. /**
  27614. * @private
  27615. * Step 6 of the checks before inserting and before replacing a child are different.
  27616. *
  27617. * @param {Document} parent the parent node to insert `node` into
  27618. * @param {Node} node the node to insert
  27619. * @param {Node | undefined} child the node that should become the `nextSibling` of `node`
  27620. * @returns {Node}
  27621. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  27622. * @throws DOMException if `child` is provided but is not a child of `parent`.
  27623. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  27624. * @see https://dom.spec.whatwg.org/#concept-node-replace
  27625. */
  27626. function assertPreInsertionValidityInDocument(parent, node, child) {
  27627. var parentChildNodes = parent.childNodes || [];
  27628. var nodeChildNodes = node.childNodes || [];
  27629. // DocumentFragment
  27630. if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
  27631. var nodeChildElements = nodeChildNodes.filter(isElementNode);
  27632. // If node has more than one element child or has a Text node child.
  27633. if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) {
  27634. throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment');
  27635. }
  27636. // Otherwise, if `node` has one element child and either `parent` has an element child,
  27637. // `child` is a doctype, or `child` is non-null and a doctype is following `child`.
  27638. if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) {
  27639. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype');
  27640. }
  27641. }
  27642. // Element
  27643. if (isElementNode(node)) {
  27644. // `parent` has an element child, `child` is a doctype,
  27645. // or `child` is non-null and a doctype is following `child`.
  27646. if (!isElementInsertionPossible(parent, child)) {
  27647. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype');
  27648. }
  27649. }
  27650. // DocumentType
  27651. if (isDocTypeNode(node)) {
  27652. // `parent` has a doctype child,
  27653. if (find(parentChildNodes, isDocTypeNode)) {
  27654. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed');
  27655. }
  27656. var parentElementChild = find(parentChildNodes, isElementNode);
  27657. // `child` is non-null and an element is preceding `child`,
  27658. if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {
  27659. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element');
  27660. }
  27661. // or `child` is null and `parent` has an element child.
  27662. if (!child && parentElementChild) {
  27663. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can not be appended since element is present');
  27664. }
  27665. }
  27666. }
  27667. /**
  27668. * @private
  27669. * Step 6 of the checks before inserting and before replacing a child are different.
  27670. *
  27671. * @param {Document} parent the parent node to insert `node` into
  27672. * @param {Node} node the node to insert
  27673. * @param {Node | undefined} child the node that should become the `nextSibling` of `node`
  27674. * @returns {Node}
  27675. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  27676. * @throws DOMException if `child` is provided but is not a child of `parent`.
  27677. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  27678. * @see https://dom.spec.whatwg.org/#concept-node-replace
  27679. */
  27680. function assertPreReplacementValidityInDocument(parent, node, child) {
  27681. var parentChildNodes = parent.childNodes || [];
  27682. var nodeChildNodes = node.childNodes || [];
  27683. // DocumentFragment
  27684. if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
  27685. var nodeChildElements = nodeChildNodes.filter(isElementNode);
  27686. // If `node` has more than one element child or has a Text node child.
  27687. if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) {
  27688. throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment');
  27689. }
  27690. // Otherwise, if `node` has one element child and either `parent` has an element child that is not `child` or a doctype is following `child`.
  27691. if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) {
  27692. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype');
  27693. }
  27694. }
  27695. // Element
  27696. if (isElementNode(node)) {
  27697. // `parent` has an element child that is not `child` or a doctype is following `child`.
  27698. if (!isElementReplacementPossible(parent, child)) {
  27699. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype');
  27700. }
  27701. }
  27702. // DocumentType
  27703. if (isDocTypeNode(node)) {
  27704. function hasDoctypeChildThatIsNotChild(node) {
  27705. return isDocTypeNode(node) && node !== child;
  27706. }
  27707. // `parent` has a doctype child that is not `child`,
  27708. if (find(parentChildNodes, hasDoctypeChildThatIsNotChild)) {
  27709. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed');
  27710. }
  27711. var parentElementChild = find(parentChildNodes, isElementNode);
  27712. // or an element is preceding `child`.
  27713. if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {
  27714. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element');
  27715. }
  27716. }
  27717. }
  27718. /**
  27719. * @private
  27720. * @param {Node} parent the parent node to insert `node` into
  27721. * @param {Node} node the node to insert
  27722. * @param {Node=} child the node that should become the `nextSibling` of `node`
  27723. * @returns {Node}
  27724. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  27725. * @throws DOMException if `child` is provided but is not a child of `parent`.
  27726. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  27727. */
  27728. function _insertBefore(parent, node, child, _inDocumentAssertion) {
  27729. // To ensure pre-insertion validity of a node into a parent before a child, run these steps:
  27730. assertPreInsertionValidity1to5(parent, node, child);
  27731. // If parent is a document, and any of the statements below, switched on the interface node implements,
  27732. // are true, then throw a "HierarchyRequestError" DOMException.
  27733. if (parent.nodeType === Node.DOCUMENT_NODE) {
  27734. (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child);
  27735. }
  27736. var cp = node.parentNode;
  27737. if (cp) {
  27738. cp.removeChild(node); //remove and update
  27739. }
  27740. if (node.nodeType === DOCUMENT_FRAGMENT_NODE) {
  27741. var newFirst = node.firstChild;
  27742. if (newFirst == null) {
  27743. return node;
  27744. }
  27745. var newLast = node.lastChild;
  27746. } else {
  27747. newFirst = newLast = node;
  27748. }
  27749. var pre = child ? child.previousSibling : parent.lastChild;
  27750. newFirst.previousSibling = pre;
  27751. newLast.nextSibling = child;
  27752. if (pre) {
  27753. pre.nextSibling = newFirst;
  27754. } else {
  27755. parent.firstChild = newFirst;
  27756. }
  27757. if (child == null) {
  27758. parent.lastChild = newLast;
  27759. } else {
  27760. child.previousSibling = newLast;
  27761. }
  27762. do {
  27763. newFirst.parentNode = parent;
  27764. } while (newFirst !== newLast && (newFirst = newFirst.nextSibling));
  27765. _onUpdateChild(parent.ownerDocument || parent, parent);
  27766. //console.log(parent.lastChild.nextSibling == null)
  27767. if (node.nodeType == DOCUMENT_FRAGMENT_NODE) {
  27768. node.firstChild = node.lastChild = null;
  27769. }
  27770. return node;
  27771. }
  27772. /**
  27773. * Appends `newChild` to `parentNode`.
  27774. * If `newChild` is already connected to a `parentNode` it is first removed from it.
  27775. *
  27776. * @see https://github.com/xmldom/xmldom/issues/135
  27777. * @see https://github.com/xmldom/xmldom/issues/145
  27778. * @param {Node} parentNode
  27779. * @param {Node} newChild
  27780. * @returns {Node}
  27781. * @private
  27782. */
  27783. function _appendSingleChild(parentNode, newChild) {
  27784. if (newChild.parentNode) {
  27785. newChild.parentNode.removeChild(newChild);
  27786. }
  27787. newChild.parentNode = parentNode;
  27788. newChild.previousSibling = parentNode.lastChild;
  27789. newChild.nextSibling = null;
  27790. if (newChild.previousSibling) {
  27791. newChild.previousSibling.nextSibling = newChild;
  27792. } else {
  27793. parentNode.firstChild = newChild;
  27794. }
  27795. parentNode.lastChild = newChild;
  27796. _onUpdateChild(parentNode.ownerDocument, parentNode, newChild);
  27797. return newChild;
  27798. }
  27799. Document.prototype = {
  27800. //implementation : null,
  27801. nodeName: '#document',
  27802. nodeType: DOCUMENT_NODE,
  27803. /**
  27804. * The DocumentType node of the document.
  27805. *
  27806. * @readonly
  27807. * @type DocumentType
  27808. */
  27809. doctype: null,
  27810. documentElement: null,
  27811. _inc: 1,
  27812. insertBefore: function (newChild, refChild) {
  27813. //raises
  27814. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  27815. var child = newChild.firstChild;
  27816. while (child) {
  27817. var next = child.nextSibling;
  27818. this.insertBefore(child, refChild);
  27819. child = next;
  27820. }
  27821. return newChild;
  27822. }
  27823. _insertBefore(this, newChild, refChild);
  27824. newChild.ownerDocument = this;
  27825. if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) {
  27826. this.documentElement = newChild;
  27827. }
  27828. return newChild;
  27829. },
  27830. removeChild: function (oldChild) {
  27831. if (this.documentElement == oldChild) {
  27832. this.documentElement = null;
  27833. }
  27834. return _removeChild(this, oldChild);
  27835. },
  27836. replaceChild: function (newChild, oldChild) {
  27837. //raises
  27838. _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);
  27839. newChild.ownerDocument = this;
  27840. if (oldChild) {
  27841. this.removeChild(oldChild);
  27842. }
  27843. if (isElementNode(newChild)) {
  27844. this.documentElement = newChild;
  27845. }
  27846. },
  27847. // Introduced in DOM Level 2:
  27848. importNode: function (importedNode, deep) {
  27849. return importNode(this, importedNode, deep);
  27850. },
  27851. // Introduced in DOM Level 2:
  27852. getElementById: function (id) {
  27853. var rtv = null;
  27854. _visitNode(this.documentElement, function (node) {
  27855. if (node.nodeType == ELEMENT_NODE) {
  27856. if (node.getAttribute('id') == id) {
  27857. rtv = node;
  27858. return true;
  27859. }
  27860. }
  27861. });
  27862. return rtv;
  27863. },
  27864. /**
  27865. * The `getElementsByClassName` method of `Document` interface returns an array-like object
  27866. * of all child elements which have **all** of the given class name(s).
  27867. *
  27868. * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters.
  27869. *
  27870. *
  27871. * Warning: This is a live LiveNodeList.
  27872. * Changes in the DOM will reflect in the array as the changes occur.
  27873. * If an element selected by this array no longer qualifies for the selector,
  27874. * it will automatically be removed. Be aware of this for iteration purposes.
  27875. *
  27876. * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace
  27877. *
  27878. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
  27879. * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname
  27880. */
  27881. getElementsByClassName: function (classNames) {
  27882. var classNamesSet = toOrderedSet(classNames);
  27883. return new LiveNodeList(this, function (base) {
  27884. var ls = [];
  27885. if (classNamesSet.length > 0) {
  27886. _visitNode(base.documentElement, function (node) {
  27887. if (node !== base && node.nodeType === ELEMENT_NODE) {
  27888. var nodeClassNames = node.getAttribute('class');
  27889. // can be null if the attribute does not exist
  27890. if (nodeClassNames) {
  27891. // before splitting and iterating just compare them for the most common case
  27892. var matches = classNames === nodeClassNames;
  27893. if (!matches) {
  27894. var nodeClassNamesSet = toOrderedSet(nodeClassNames);
  27895. matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet));
  27896. }
  27897. if (matches) {
  27898. ls.push(node);
  27899. }
  27900. }
  27901. }
  27902. });
  27903. }
  27904. return ls;
  27905. });
  27906. },
  27907. //document factory method:
  27908. createElement: function (tagName) {
  27909. var node = new Element();
  27910. node.ownerDocument = this;
  27911. node.nodeName = tagName;
  27912. node.tagName = tagName;
  27913. node.localName = tagName;
  27914. node.childNodes = new NodeList();
  27915. var attrs = node.attributes = new NamedNodeMap();
  27916. attrs._ownerElement = node;
  27917. return node;
  27918. },
  27919. createDocumentFragment: function () {
  27920. var node = new DocumentFragment();
  27921. node.ownerDocument = this;
  27922. node.childNodes = new NodeList();
  27923. return node;
  27924. },
  27925. createTextNode: function (data) {
  27926. var node = new Text();
  27927. node.ownerDocument = this;
  27928. node.appendData(data);
  27929. return node;
  27930. },
  27931. createComment: function (data) {
  27932. var node = new Comment();
  27933. node.ownerDocument = this;
  27934. node.appendData(data);
  27935. return node;
  27936. },
  27937. createCDATASection: function (data) {
  27938. var node = new CDATASection();
  27939. node.ownerDocument = this;
  27940. node.appendData(data);
  27941. return node;
  27942. },
  27943. createProcessingInstruction: function (target, data) {
  27944. var node = new ProcessingInstruction();
  27945. node.ownerDocument = this;
  27946. node.tagName = node.target = target;
  27947. node.nodeValue = node.data = data;
  27948. return node;
  27949. },
  27950. createAttribute: function (name) {
  27951. var node = new Attr();
  27952. node.ownerDocument = this;
  27953. node.name = name;
  27954. node.nodeName = name;
  27955. node.localName = name;
  27956. node.specified = true;
  27957. return node;
  27958. },
  27959. createEntityReference: function (name) {
  27960. var node = new EntityReference();
  27961. node.ownerDocument = this;
  27962. node.nodeName = name;
  27963. return node;
  27964. },
  27965. // Introduced in DOM Level 2:
  27966. createElementNS: function (namespaceURI, qualifiedName) {
  27967. var node = new Element();
  27968. var pl = qualifiedName.split(':');
  27969. var attrs = node.attributes = new NamedNodeMap();
  27970. node.childNodes = new NodeList();
  27971. node.ownerDocument = this;
  27972. node.nodeName = qualifiedName;
  27973. node.tagName = qualifiedName;
  27974. node.namespaceURI = namespaceURI;
  27975. if (pl.length == 2) {
  27976. node.prefix = pl[0];
  27977. node.localName = pl[1];
  27978. } else {
  27979. //el.prefix = null;
  27980. node.localName = qualifiedName;
  27981. }
  27982. attrs._ownerElement = node;
  27983. return node;
  27984. },
  27985. // Introduced in DOM Level 2:
  27986. createAttributeNS: function (namespaceURI, qualifiedName) {
  27987. var node = new Attr();
  27988. var pl = qualifiedName.split(':');
  27989. node.ownerDocument = this;
  27990. node.nodeName = qualifiedName;
  27991. node.name = qualifiedName;
  27992. node.namespaceURI = namespaceURI;
  27993. node.specified = true;
  27994. if (pl.length == 2) {
  27995. node.prefix = pl[0];
  27996. node.localName = pl[1];
  27997. } else {
  27998. //el.prefix = null;
  27999. node.localName = qualifiedName;
  28000. }
  28001. return node;
  28002. }
  28003. };
  28004. _extends(Document, Node);
  28005. function Element() {
  28006. this._nsMap = {};
  28007. }
  28008. Element.prototype = {
  28009. nodeType: ELEMENT_NODE,
  28010. hasAttribute: function (name) {
  28011. return this.getAttributeNode(name) != null;
  28012. },
  28013. getAttribute: function (name) {
  28014. var attr = this.getAttributeNode(name);
  28015. return attr && attr.value || '';
  28016. },
  28017. getAttributeNode: function (name) {
  28018. return this.attributes.getNamedItem(name);
  28019. },
  28020. setAttribute: function (name, value) {
  28021. var attr = this.ownerDocument.createAttribute(name);
  28022. attr.value = attr.nodeValue = "" + value;
  28023. this.setAttributeNode(attr);
  28024. },
  28025. removeAttribute: function (name) {
  28026. var attr = this.getAttributeNode(name);
  28027. attr && this.removeAttributeNode(attr);
  28028. },
  28029. //four real opeartion method
  28030. appendChild: function (newChild) {
  28031. if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
  28032. return this.insertBefore(newChild, null);
  28033. } else {
  28034. return _appendSingleChild(this, newChild);
  28035. }
  28036. },
  28037. setAttributeNode: function (newAttr) {
  28038. return this.attributes.setNamedItem(newAttr);
  28039. },
  28040. setAttributeNodeNS: function (newAttr) {
  28041. return this.attributes.setNamedItemNS(newAttr);
  28042. },
  28043. removeAttributeNode: function (oldAttr) {
  28044. //console.log(this == oldAttr.ownerElement)
  28045. return this.attributes.removeNamedItem(oldAttr.nodeName);
  28046. },
  28047. //get real attribute name,and remove it by removeAttributeNode
  28048. removeAttributeNS: function (namespaceURI, localName) {
  28049. var old = this.getAttributeNodeNS(namespaceURI, localName);
  28050. old && this.removeAttributeNode(old);
  28051. },
  28052. hasAttributeNS: function (namespaceURI, localName) {
  28053. return this.getAttributeNodeNS(namespaceURI, localName) != null;
  28054. },
  28055. getAttributeNS: function (namespaceURI, localName) {
  28056. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  28057. return attr && attr.value || '';
  28058. },
  28059. setAttributeNS: function (namespaceURI, qualifiedName, value) {
  28060. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  28061. attr.value = attr.nodeValue = "" + value;
  28062. this.setAttributeNode(attr);
  28063. },
  28064. getAttributeNodeNS: function (namespaceURI, localName) {
  28065. return this.attributes.getNamedItemNS(namespaceURI, localName);
  28066. },
  28067. getElementsByTagName: function (tagName) {
  28068. return new LiveNodeList(this, function (base) {
  28069. var ls = [];
  28070. _visitNode(base, function (node) {
  28071. if (node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)) {
  28072. ls.push(node);
  28073. }
  28074. });
  28075. return ls;
  28076. });
  28077. },
  28078. getElementsByTagNameNS: function (namespaceURI, localName) {
  28079. return new LiveNodeList(this, function (base) {
  28080. var ls = [];
  28081. _visitNode(base, function (node) {
  28082. if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)) {
  28083. ls.push(node);
  28084. }
  28085. });
  28086. return ls;
  28087. });
  28088. }
  28089. };
  28090. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  28091. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  28092. _extends(Element, Node);
  28093. function Attr() {}
  28094. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  28095. _extends(Attr, Node);
  28096. function CharacterData() {}
  28097. CharacterData.prototype = {
  28098. data: '',
  28099. substringData: function (offset, count) {
  28100. return this.data.substring(offset, offset + count);
  28101. },
  28102. appendData: function (text) {
  28103. text = this.data + text;
  28104. this.nodeValue = this.data = text;
  28105. this.length = text.length;
  28106. },
  28107. insertData: function (offset, text) {
  28108. this.replaceData(offset, 0, text);
  28109. },
  28110. appendChild: function (newChild) {
  28111. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]);
  28112. },
  28113. deleteData: function (offset, count) {
  28114. this.replaceData(offset, count, "");
  28115. },
  28116. replaceData: function (offset, count, text) {
  28117. var start = this.data.substring(0, offset);
  28118. var end = this.data.substring(offset + count);
  28119. text = start + text + end;
  28120. this.nodeValue = this.data = text;
  28121. this.length = text.length;
  28122. }
  28123. };
  28124. _extends(CharacterData, Node);
  28125. function Text() {}
  28126. Text.prototype = {
  28127. nodeName: "#text",
  28128. nodeType: TEXT_NODE,
  28129. splitText: function (offset) {
  28130. var text = this.data;
  28131. var newText = text.substring(offset);
  28132. text = text.substring(0, offset);
  28133. this.data = this.nodeValue = text;
  28134. this.length = text.length;
  28135. var newNode = this.ownerDocument.createTextNode(newText);
  28136. if (this.parentNode) {
  28137. this.parentNode.insertBefore(newNode, this.nextSibling);
  28138. }
  28139. return newNode;
  28140. }
  28141. };
  28142. _extends(Text, CharacterData);
  28143. function Comment() {}
  28144. Comment.prototype = {
  28145. nodeName: "#comment",
  28146. nodeType: COMMENT_NODE
  28147. };
  28148. _extends(Comment, CharacterData);
  28149. function CDATASection() {}
  28150. CDATASection.prototype = {
  28151. nodeName: "#cdata-section",
  28152. nodeType: CDATA_SECTION_NODE
  28153. };
  28154. _extends(CDATASection, CharacterData);
  28155. function DocumentType() {}
  28156. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  28157. _extends(DocumentType, Node);
  28158. function Notation() {}
  28159. Notation.prototype.nodeType = NOTATION_NODE;
  28160. _extends(Notation, Node);
  28161. function Entity() {}
  28162. Entity.prototype.nodeType = ENTITY_NODE;
  28163. _extends(Entity, Node);
  28164. function EntityReference() {}
  28165. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  28166. _extends(EntityReference, Node);
  28167. function DocumentFragment() {}
  28168. DocumentFragment.prototype.nodeName = "#document-fragment";
  28169. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  28170. _extends(DocumentFragment, Node);
  28171. function ProcessingInstruction() {}
  28172. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  28173. _extends(ProcessingInstruction, Node);
  28174. function XMLSerializer() {}
  28175. XMLSerializer.prototype.serializeToString = function (node, isHtml, nodeFilter) {
  28176. return nodeSerializeToString.call(node, isHtml, nodeFilter);
  28177. };
  28178. Node.prototype.toString = nodeSerializeToString;
  28179. function nodeSerializeToString(isHtml, nodeFilter) {
  28180. var buf = [];
  28181. var refNode = this.nodeType == 9 && this.documentElement || this;
  28182. var prefix = refNode.prefix;
  28183. var uri = refNode.namespaceURI;
  28184. if (uri && prefix == null) {
  28185. //console.log(prefix)
  28186. var prefix = refNode.lookupPrefix(uri);
  28187. if (prefix == null) {
  28188. //isHTML = true;
  28189. var visibleNamespaces = [{
  28190. namespace: uri,
  28191. prefix: null
  28192. }
  28193. //{namespace:uri,prefix:''}
  28194. ];
  28195. }
  28196. }
  28197. serializeToString(this, buf, isHtml, nodeFilter, visibleNamespaces);
  28198. //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  28199. return buf.join('');
  28200. }
  28201. function needNamespaceDefine(node, isHTML, visibleNamespaces) {
  28202. var prefix = node.prefix || '';
  28203. var uri = node.namespaceURI;
  28204. // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) ,
  28205. // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl :
  28206. // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty.
  28207. // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using)
  28208. // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared :
  28209. // > [...] Furthermore, the attribute value [...] must not be an empty string.
  28210. // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document.
  28211. if (!uri) {
  28212. return false;
  28213. }
  28214. if (prefix === "xml" && uri === NAMESPACE$2.XML || uri === NAMESPACE$2.XMLNS) {
  28215. return false;
  28216. }
  28217. var i = visibleNamespaces.length;
  28218. while (i--) {
  28219. var ns = visibleNamespaces[i];
  28220. // get namespace prefix
  28221. if (ns.prefix === prefix) {
  28222. return ns.namespace !== uri;
  28223. }
  28224. }
  28225. return true;
  28226. }
  28227. /**
  28228. * Well-formed constraint: No < in Attribute Values
  28229. * > The replacement text of any entity referred to directly or indirectly
  28230. * > in an attribute value must not contain a <.
  28231. * @see https://www.w3.org/TR/xml11/#CleanAttrVals
  28232. * @see https://www.w3.org/TR/xml11/#NT-AttValue
  28233. *
  28234. * Literal whitespace other than space that appear in attribute values
  28235. * are serialized as their entity references, so they will be preserved.
  28236. * (In contrast to whitespace literals in the input which are normalized to spaces)
  28237. * @see https://www.w3.org/TR/xml11/#AVNormalize
  28238. * @see https://w3c.github.io/DOM-Parsing/#serializing-an-element-s-attributes
  28239. */
  28240. function addSerializedAttribute(buf, qualifiedName, value) {
  28241. buf.push(' ', qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"');
  28242. }
  28243. function serializeToString(node, buf, isHTML, nodeFilter, visibleNamespaces) {
  28244. if (!visibleNamespaces) {
  28245. visibleNamespaces = [];
  28246. }
  28247. if (nodeFilter) {
  28248. node = nodeFilter(node);
  28249. if (node) {
  28250. if (typeof node == 'string') {
  28251. buf.push(node);
  28252. return;
  28253. }
  28254. } else {
  28255. return;
  28256. }
  28257. //buf.sort.apply(attrs, attributeSorter);
  28258. }
  28259. switch (node.nodeType) {
  28260. case ELEMENT_NODE:
  28261. var attrs = node.attributes;
  28262. var len = attrs.length;
  28263. var child = node.firstChild;
  28264. var nodeName = node.tagName;
  28265. isHTML = NAMESPACE$2.isHTML(node.namespaceURI) || isHTML;
  28266. var prefixedNodeName = nodeName;
  28267. if (!isHTML && !node.prefix && node.namespaceURI) {
  28268. var defaultNS;
  28269. // lookup current default ns from `xmlns` attribute
  28270. for (var ai = 0; ai < attrs.length; ai++) {
  28271. if (attrs.item(ai).name === 'xmlns') {
  28272. defaultNS = attrs.item(ai).value;
  28273. break;
  28274. }
  28275. }
  28276. if (!defaultNS) {
  28277. // lookup current default ns in visibleNamespaces
  28278. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  28279. var namespace = visibleNamespaces[nsi];
  28280. if (namespace.prefix === '' && namespace.namespace === node.namespaceURI) {
  28281. defaultNS = namespace.namespace;
  28282. break;
  28283. }
  28284. }
  28285. }
  28286. if (defaultNS !== node.namespaceURI) {
  28287. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  28288. var namespace = visibleNamespaces[nsi];
  28289. if (namespace.namespace === node.namespaceURI) {
  28290. if (namespace.prefix) {
  28291. prefixedNodeName = namespace.prefix + ':' + nodeName;
  28292. }
  28293. break;
  28294. }
  28295. }
  28296. }
  28297. }
  28298. buf.push('<', prefixedNodeName);
  28299. for (var i = 0; i < len; i++) {
  28300. // add namespaces for attributes
  28301. var attr = attrs.item(i);
  28302. if (attr.prefix == 'xmlns') {
  28303. visibleNamespaces.push({
  28304. prefix: attr.localName,
  28305. namespace: attr.value
  28306. });
  28307. } else if (attr.nodeName == 'xmlns') {
  28308. visibleNamespaces.push({
  28309. prefix: '',
  28310. namespace: attr.value
  28311. });
  28312. }
  28313. }
  28314. for (var i = 0; i < len; i++) {
  28315. var attr = attrs.item(i);
  28316. if (needNamespaceDefine(attr, isHTML, visibleNamespaces)) {
  28317. var prefix = attr.prefix || '';
  28318. var uri = attr.namespaceURI;
  28319. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  28320. visibleNamespaces.push({
  28321. prefix: prefix,
  28322. namespace: uri
  28323. });
  28324. }
  28325. serializeToString(attr, buf, isHTML, nodeFilter, visibleNamespaces);
  28326. }
  28327. // add namespace for current node
  28328. if (nodeName === prefixedNodeName && needNamespaceDefine(node, isHTML, visibleNamespaces)) {
  28329. var prefix = node.prefix || '';
  28330. var uri = node.namespaceURI;
  28331. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  28332. visibleNamespaces.push({
  28333. prefix: prefix,
  28334. namespace: uri
  28335. });
  28336. }
  28337. if (child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)) {
  28338. buf.push('>');
  28339. //if is cdata child node
  28340. if (isHTML && /^script$/i.test(nodeName)) {
  28341. while (child) {
  28342. if (child.data) {
  28343. buf.push(child.data);
  28344. } else {
  28345. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  28346. }
  28347. child = child.nextSibling;
  28348. }
  28349. } else {
  28350. while (child) {
  28351. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  28352. child = child.nextSibling;
  28353. }
  28354. }
  28355. buf.push('</', prefixedNodeName, '>');
  28356. } else {
  28357. buf.push('/>');
  28358. }
  28359. // remove added visible namespaces
  28360. //visibleNamespaces.length = startVisibleNamespaces;
  28361. return;
  28362. case DOCUMENT_NODE:
  28363. case DOCUMENT_FRAGMENT_NODE:
  28364. var child = node.firstChild;
  28365. while (child) {
  28366. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  28367. child = child.nextSibling;
  28368. }
  28369. return;
  28370. case ATTRIBUTE_NODE:
  28371. return addSerializedAttribute(buf, node.name, node.value);
  28372. case TEXT_NODE:
  28373. /**
  28374. * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
  28375. * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
  28376. * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
  28377. * `&amp;` and `&lt;` respectively.
  28378. * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
  28379. * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
  28380. * when that string is not marking the end of a CDATA section.
  28381. *
  28382. * In the content of elements, character data is any string of characters
  28383. * which does not contain the start-delimiter of any markup
  28384. * and does not include the CDATA-section-close delimiter, `]]>`.
  28385. *
  28386. * @see https://www.w3.org/TR/xml/#NT-CharData
  28387. * @see https://w3c.github.io/DOM-Parsing/#xml-serializing-a-text-node
  28388. */
  28389. return buf.push(node.data.replace(/[<&>]/g, _xmlEncoder));
  28390. case CDATA_SECTION_NODE:
  28391. return buf.push('<![CDATA[', node.data, ']]>');
  28392. case COMMENT_NODE:
  28393. return buf.push("<!--", node.data, "-->");
  28394. case DOCUMENT_TYPE_NODE:
  28395. var pubid = node.publicId;
  28396. var sysid = node.systemId;
  28397. buf.push('<!DOCTYPE ', node.name);
  28398. if (pubid) {
  28399. buf.push(' PUBLIC ', pubid);
  28400. if (sysid && sysid != '.') {
  28401. buf.push(' ', sysid);
  28402. }
  28403. buf.push('>');
  28404. } else if (sysid && sysid != '.') {
  28405. buf.push(' SYSTEM ', sysid, '>');
  28406. } else {
  28407. var sub = node.internalSubset;
  28408. if (sub) {
  28409. buf.push(" [", sub, "]");
  28410. }
  28411. buf.push(">");
  28412. }
  28413. return;
  28414. case PROCESSING_INSTRUCTION_NODE:
  28415. return buf.push("<?", node.target, " ", node.data, "?>");
  28416. case ENTITY_REFERENCE_NODE:
  28417. return buf.push('&', node.nodeName, ';');
  28418. //case ENTITY_NODE:
  28419. //case NOTATION_NODE:
  28420. default:
  28421. buf.push('??', node.nodeName);
  28422. }
  28423. }
  28424. function importNode(doc, node, deep) {
  28425. var node2;
  28426. switch (node.nodeType) {
  28427. case ELEMENT_NODE:
  28428. node2 = node.cloneNode(false);
  28429. node2.ownerDocument = doc;
  28430. //var attrs = node2.attributes;
  28431. //var len = attrs.length;
  28432. //for(var i=0;i<len;i++){
  28433. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  28434. //}
  28435. case DOCUMENT_FRAGMENT_NODE:
  28436. break;
  28437. case ATTRIBUTE_NODE:
  28438. deep = true;
  28439. break;
  28440. //case ENTITY_REFERENCE_NODE:
  28441. //case PROCESSING_INSTRUCTION_NODE:
  28442. ////case TEXT_NODE:
  28443. //case CDATA_SECTION_NODE:
  28444. //case COMMENT_NODE:
  28445. // deep = false;
  28446. // break;
  28447. //case DOCUMENT_NODE:
  28448. //case DOCUMENT_TYPE_NODE:
  28449. //cannot be imported.
  28450. //case ENTITY_NODE:
  28451. //case NOTATION_NODE:
  28452. //can not hit in level3
  28453. //default:throw e;
  28454. }
  28455. if (!node2) {
  28456. node2 = node.cloneNode(false); //false
  28457. }
  28458. node2.ownerDocument = doc;
  28459. node2.parentNode = null;
  28460. if (deep) {
  28461. var child = node.firstChild;
  28462. while (child) {
  28463. node2.appendChild(importNode(doc, child, deep));
  28464. child = child.nextSibling;
  28465. }
  28466. }
  28467. return node2;
  28468. }
  28469. //
  28470. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  28471. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  28472. function cloneNode(doc, node, deep) {
  28473. var node2 = new node.constructor();
  28474. for (var n in node) {
  28475. if (Object.prototype.hasOwnProperty.call(node, n)) {
  28476. var v = node[n];
  28477. if (typeof v != "object") {
  28478. if (v != node2[n]) {
  28479. node2[n] = v;
  28480. }
  28481. }
  28482. }
  28483. }
  28484. if (node.childNodes) {
  28485. node2.childNodes = new NodeList();
  28486. }
  28487. node2.ownerDocument = doc;
  28488. switch (node2.nodeType) {
  28489. case ELEMENT_NODE:
  28490. var attrs = node.attributes;
  28491. var attrs2 = node2.attributes = new NamedNodeMap();
  28492. var len = attrs.length;
  28493. attrs2._ownerElement = node2;
  28494. for (var i = 0; i < len; i++) {
  28495. node2.setAttributeNode(cloneNode(doc, attrs.item(i), true));
  28496. }
  28497. break;
  28498. case ATTRIBUTE_NODE:
  28499. deep = true;
  28500. }
  28501. if (deep) {
  28502. var child = node.firstChild;
  28503. while (child) {
  28504. node2.appendChild(cloneNode(doc, child, deep));
  28505. child = child.nextSibling;
  28506. }
  28507. }
  28508. return node2;
  28509. }
  28510. function __set__(object, key, value) {
  28511. object[key] = value;
  28512. }
  28513. //do dynamic
  28514. try {
  28515. if (Object.defineProperty) {
  28516. Object.defineProperty(LiveNodeList.prototype, 'length', {
  28517. get: function () {
  28518. _updateLiveList(this);
  28519. return this.$$length;
  28520. }
  28521. });
  28522. Object.defineProperty(Node.prototype, 'textContent', {
  28523. get: function () {
  28524. return getTextContent(this);
  28525. },
  28526. set: function (data) {
  28527. switch (this.nodeType) {
  28528. case ELEMENT_NODE:
  28529. case DOCUMENT_FRAGMENT_NODE:
  28530. while (this.firstChild) {
  28531. this.removeChild(this.firstChild);
  28532. }
  28533. if (data || String(data)) {
  28534. this.appendChild(this.ownerDocument.createTextNode(data));
  28535. }
  28536. break;
  28537. default:
  28538. this.data = data;
  28539. this.value = data;
  28540. this.nodeValue = data;
  28541. }
  28542. }
  28543. });
  28544. function getTextContent(node) {
  28545. switch (node.nodeType) {
  28546. case ELEMENT_NODE:
  28547. case DOCUMENT_FRAGMENT_NODE:
  28548. var buf = [];
  28549. node = node.firstChild;
  28550. while (node) {
  28551. if (node.nodeType !== 7 && node.nodeType !== 8) {
  28552. buf.push(getTextContent(node));
  28553. }
  28554. node = node.nextSibling;
  28555. }
  28556. return buf.join('');
  28557. default:
  28558. return node.nodeValue;
  28559. }
  28560. }
  28561. __set__ = function (object, key, value) {
  28562. //console.log(value)
  28563. object['$$' + key] = value;
  28564. };
  28565. }
  28566. } catch (e) {//ie8
  28567. }
  28568. //if(typeof require == 'function'){
  28569. var DocumentType_1 = DocumentType;
  28570. var DOMException_1 = DOMException;
  28571. var DOMImplementation_1 = DOMImplementation$1;
  28572. var Element_1 = Element;
  28573. var Node_1 = Node;
  28574. var NodeList_1 = NodeList;
  28575. var XMLSerializer_1 = XMLSerializer;
  28576. //}
  28577. var dom = {
  28578. DocumentType: DocumentType_1,
  28579. DOMException: DOMException_1,
  28580. DOMImplementation: DOMImplementation_1,
  28581. Element: Element_1,
  28582. Node: Node_1,
  28583. NodeList: NodeList_1,
  28584. XMLSerializer: XMLSerializer_1
  28585. };
  28586. var entities = createCommonjsModule(function (module, exports) {
  28587. var freeze = conventions.freeze;
  28588. /**
  28589. * The entities that are predefined in every XML document.
  28590. *
  28591. * @see https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-predefined-ent W3C XML 1.1
  28592. * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent W3C XML 1.0
  28593. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML Wikipedia
  28594. */
  28595. exports.XML_ENTITIES = freeze({
  28596. amp: '&',
  28597. apos: "'",
  28598. gt: '>',
  28599. lt: '<',
  28600. quot: '"'
  28601. });
  28602. /**
  28603. * A map of currently 241 entities that are detected in an HTML document.
  28604. * They contain all entries from `XML_ENTITIES`.
  28605. *
  28606. * @see XML_ENTITIES
  28607. * @see DOMParser.parseFromString
  28608. * @see DOMImplementation.prototype.createHTMLDocument
  28609. * @see https://html.spec.whatwg.org/#named-character-references WHATWG HTML(5) Spec
  28610. * @see https://www.w3.org/TR/xml-entity-names/ W3C XML Entity Names
  28611. * @see https://www.w3.org/TR/html4/sgml/entities.html W3C HTML4/SGML
  28612. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML Wikipedia (HTML)
  28613. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Entities_representing_special_characters_in_XHTML Wikpedia (XHTML)
  28614. */
  28615. exports.HTML_ENTITIES = freeze({
  28616. lt: '<',
  28617. gt: '>',
  28618. amp: '&',
  28619. quot: '"',
  28620. apos: "'",
  28621. Agrave: "À",
  28622. Aacute: "Á",
  28623. Acirc: "Â",
  28624. Atilde: "Ã",
  28625. Auml: "Ä",
  28626. Aring: "Å",
  28627. AElig: "Æ",
  28628. Ccedil: "Ç",
  28629. Egrave: "È",
  28630. Eacute: "É",
  28631. Ecirc: "Ê",
  28632. Euml: "Ë",
  28633. Igrave: "Ì",
  28634. Iacute: "Í",
  28635. Icirc: "Î",
  28636. Iuml: "Ï",
  28637. ETH: "Ð",
  28638. Ntilde: "Ñ",
  28639. Ograve: "Ò",
  28640. Oacute: "Ó",
  28641. Ocirc: "Ô",
  28642. Otilde: "Õ",
  28643. Ouml: "Ö",
  28644. Oslash: "Ø",
  28645. Ugrave: "Ù",
  28646. Uacute: "Ú",
  28647. Ucirc: "Û",
  28648. Uuml: "Ü",
  28649. Yacute: "Ý",
  28650. THORN: "Þ",
  28651. szlig: "ß",
  28652. agrave: "à",
  28653. aacute: "á",
  28654. acirc: "â",
  28655. atilde: "ã",
  28656. auml: "ä",
  28657. aring: "å",
  28658. aelig: "æ",
  28659. ccedil: "ç",
  28660. egrave: "è",
  28661. eacute: "é",
  28662. ecirc: "ê",
  28663. euml: "ë",
  28664. igrave: "ì",
  28665. iacute: "í",
  28666. icirc: "î",
  28667. iuml: "ï",
  28668. eth: "ð",
  28669. ntilde: "ñ",
  28670. ograve: "ò",
  28671. oacute: "ó",
  28672. ocirc: "ô",
  28673. otilde: "õ",
  28674. ouml: "ö",
  28675. oslash: "ø",
  28676. ugrave: "ù",
  28677. uacute: "ú",
  28678. ucirc: "û",
  28679. uuml: "ü",
  28680. yacute: "ý",
  28681. thorn: "þ",
  28682. yuml: "ÿ",
  28683. nbsp: "\u00a0",
  28684. iexcl: "¡",
  28685. cent: "¢",
  28686. pound: "£",
  28687. curren: "¤",
  28688. yen: "¥",
  28689. brvbar: "¦",
  28690. sect: "§",
  28691. uml: "¨",
  28692. copy: "©",
  28693. ordf: "ª",
  28694. laquo: "«",
  28695. not: "¬",
  28696. shy: "­­",
  28697. reg: "®",
  28698. macr: "¯",
  28699. deg: "°",
  28700. plusmn: "±",
  28701. sup2: "²",
  28702. sup3: "³",
  28703. acute: "´",
  28704. micro: "µ",
  28705. para: "¶",
  28706. middot: "·",
  28707. cedil: "¸",
  28708. sup1: "¹",
  28709. ordm: "º",
  28710. raquo: "»",
  28711. frac14: "¼",
  28712. frac12: "½",
  28713. frac34: "¾",
  28714. iquest: "¿",
  28715. times: "×",
  28716. divide: "÷",
  28717. forall: "∀",
  28718. part: "∂",
  28719. exist: "∃",
  28720. empty: "∅",
  28721. nabla: "∇",
  28722. isin: "∈",
  28723. notin: "∉",
  28724. ni: "∋",
  28725. prod: "∏",
  28726. sum: "∑",
  28727. minus: "−",
  28728. lowast: "∗",
  28729. radic: "√",
  28730. prop: "∝",
  28731. infin: "∞",
  28732. ang: "∠",
  28733. and: "∧",
  28734. or: "∨",
  28735. cap: "∩",
  28736. cup: "∪",
  28737. 'int': "∫",
  28738. there4: "∴",
  28739. sim: "∼",
  28740. cong: "≅",
  28741. asymp: "≈",
  28742. ne: "≠",
  28743. equiv: "≡",
  28744. le: "≤",
  28745. ge: "≥",
  28746. sub: "⊂",
  28747. sup: "⊃",
  28748. nsub: "⊄",
  28749. sube: "⊆",
  28750. supe: "⊇",
  28751. oplus: "⊕",
  28752. otimes: "⊗",
  28753. perp: "⊥",
  28754. sdot: "⋅",
  28755. Alpha: "Α",
  28756. Beta: "Β",
  28757. Gamma: "Γ",
  28758. Delta: "Δ",
  28759. Epsilon: "Ε",
  28760. Zeta: "Ζ",
  28761. Eta: "Η",
  28762. Theta: "Θ",
  28763. Iota: "Ι",
  28764. Kappa: "Κ",
  28765. Lambda: "Λ",
  28766. Mu: "Μ",
  28767. Nu: "Ν",
  28768. Xi: "Ξ",
  28769. Omicron: "Ο",
  28770. Pi: "Π",
  28771. Rho: "Ρ",
  28772. Sigma: "Σ",
  28773. Tau: "Τ",
  28774. Upsilon: "Υ",
  28775. Phi: "Φ",
  28776. Chi: "Χ",
  28777. Psi: "Ψ",
  28778. Omega: "Ω",
  28779. alpha: "α",
  28780. beta: "β",
  28781. gamma: "γ",
  28782. delta: "δ",
  28783. epsilon: "ε",
  28784. zeta: "ζ",
  28785. eta: "η",
  28786. theta: "θ",
  28787. iota: "ι",
  28788. kappa: "κ",
  28789. lambda: "λ",
  28790. mu: "μ",
  28791. nu: "ν",
  28792. xi: "ξ",
  28793. omicron: "ο",
  28794. pi: "π",
  28795. rho: "ρ",
  28796. sigmaf: "ς",
  28797. sigma: "σ",
  28798. tau: "τ",
  28799. upsilon: "υ",
  28800. phi: "φ",
  28801. chi: "χ",
  28802. psi: "ψ",
  28803. omega: "ω",
  28804. thetasym: "ϑ",
  28805. upsih: "ϒ",
  28806. piv: "ϖ",
  28807. OElig: "Œ",
  28808. oelig: "œ",
  28809. Scaron: "Š",
  28810. scaron: "š",
  28811. Yuml: "Ÿ",
  28812. fnof: "ƒ",
  28813. circ: "ˆ",
  28814. tilde: "˜",
  28815. ensp: " ",
  28816. emsp: " ",
  28817. thinsp: " ",
  28818. zwnj: "‌",
  28819. zwj: "‍",
  28820. lrm: "‎",
  28821. rlm: "‏",
  28822. ndash: "–",
  28823. mdash: "—",
  28824. lsquo: "‘",
  28825. rsquo: "’",
  28826. sbquo: "‚",
  28827. ldquo: "“",
  28828. rdquo: "”",
  28829. bdquo: "„",
  28830. dagger: "†",
  28831. Dagger: "‡",
  28832. bull: "•",
  28833. hellip: "…",
  28834. permil: "‰",
  28835. prime: "′",
  28836. Prime: "″",
  28837. lsaquo: "‹",
  28838. rsaquo: "›",
  28839. oline: "‾",
  28840. euro: "€",
  28841. trade: "™",
  28842. larr: "←",
  28843. uarr: "↑",
  28844. rarr: "→",
  28845. darr: "↓",
  28846. harr: "↔",
  28847. crarr: "↵",
  28848. lceil: "⌈",
  28849. rceil: "⌉",
  28850. lfloor: "⌊",
  28851. rfloor: "⌋",
  28852. loz: "◊",
  28853. spades: "♠",
  28854. clubs: "♣",
  28855. hearts: "♥",
  28856. diams: "♦"
  28857. });
  28858. /**
  28859. * @deprecated use `HTML_ENTITIES` instead
  28860. * @see HTML_ENTITIES
  28861. */
  28862. exports.entityMap = exports.HTML_ENTITIES;
  28863. });
  28864. entities.XML_ENTITIES;
  28865. entities.HTML_ENTITIES;
  28866. entities.entityMap;
  28867. var NAMESPACE$1 = conventions.NAMESPACE;
  28868. //[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]
  28869. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  28870. //[5] Name ::= NameStartChar (NameChar)*
  28871. 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
  28872. var nameChar = new RegExp("[\\-\\.0-9" + nameStartChar.source.slice(1, -1) + "\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
  28873. var tagNamePattern = new RegExp('^' + nameStartChar.source + nameChar.source + '*(?:\:' + nameStartChar.source + nameChar.source + '*)?$');
  28874. //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  28875. //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(',')
  28876. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  28877. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  28878. var S_TAG = 0; //tag name offerring
  28879. var S_ATTR = 1; //attr name offerring
  28880. var S_ATTR_SPACE = 2; //attr name end and space offer
  28881. var S_EQ = 3; //=space?
  28882. var S_ATTR_NOQUOT_VALUE = 4; //attr value(no quot value only)
  28883. var S_ATTR_END = 5; //attr value end and no space(quot end)
  28884. var S_TAG_SPACE = 6; //(attr value end || tag end ) && (space offer)
  28885. var S_TAG_CLOSE = 7; //closed el<el />
  28886. /**
  28887. * Creates an error that will not be caught by XMLReader aka the SAX parser.
  28888. *
  28889. * @param {string} message
  28890. * @param {any?} locator Optional, can provide details about the location in the source
  28891. * @constructor
  28892. */
  28893. function ParseError$1(message, locator) {
  28894. this.message = message;
  28895. this.locator = locator;
  28896. if (Error.captureStackTrace) Error.captureStackTrace(this, ParseError$1);
  28897. }
  28898. ParseError$1.prototype = new Error();
  28899. ParseError$1.prototype.name = ParseError$1.name;
  28900. function XMLReader$1() {}
  28901. XMLReader$1.prototype = {
  28902. parse: function (source, defaultNSMap, entityMap) {
  28903. var domBuilder = this.domBuilder;
  28904. domBuilder.startDocument();
  28905. _copy(defaultNSMap, defaultNSMap = {});
  28906. parse$1(source, defaultNSMap, entityMap, domBuilder, this.errorHandler);
  28907. domBuilder.endDocument();
  28908. }
  28909. };
  28910. function parse$1(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
  28911. function fixedFromCharCode(code) {
  28912. // String.prototype.fromCharCode does not supports
  28913. // > 2 bytes unicode chars directly
  28914. if (code > 0xffff) {
  28915. code -= 0x10000;
  28916. var surrogate1 = 0xd800 + (code >> 10),
  28917. surrogate2 = 0xdc00 + (code & 0x3ff);
  28918. return String.fromCharCode(surrogate1, surrogate2);
  28919. } else {
  28920. return String.fromCharCode(code);
  28921. }
  28922. }
  28923. function entityReplacer(a) {
  28924. var k = a.slice(1, -1);
  28925. if (Object.hasOwnProperty.call(entityMap, k)) {
  28926. return entityMap[k];
  28927. } else if (k.charAt(0) === '#') {
  28928. return fixedFromCharCode(parseInt(k.substr(1).replace('x', '0x')));
  28929. } else {
  28930. errorHandler.error('entity not found:' + a);
  28931. return a;
  28932. }
  28933. }
  28934. function appendText(end) {
  28935. //has some bugs
  28936. if (end > start) {
  28937. var xt = source.substring(start, end).replace(/&#?\w+;/g, entityReplacer);
  28938. locator && position(start);
  28939. domBuilder.characters(xt, 0, end - start);
  28940. start = end;
  28941. }
  28942. }
  28943. function position(p, m) {
  28944. while (p >= lineEnd && (m = linePattern.exec(source))) {
  28945. lineStart = m.index;
  28946. lineEnd = lineStart + m[0].length;
  28947. locator.lineNumber++;
  28948. //console.log('line++:',locator,startPos,endPos)
  28949. }
  28950. locator.columnNumber = p - lineStart + 1;
  28951. }
  28952. var lineStart = 0;
  28953. var lineEnd = 0;
  28954. var linePattern = /.*(?:\r\n?|\n)|.*$/g;
  28955. var locator = domBuilder.locator;
  28956. var parseStack = [{
  28957. currentNSMap: defaultNSMapCopy
  28958. }];
  28959. var closeMap = {};
  28960. var start = 0;
  28961. while (true) {
  28962. try {
  28963. var tagStart = source.indexOf('<', start);
  28964. if (tagStart < 0) {
  28965. if (!source.substr(start).match(/^\s*$/)) {
  28966. var doc = domBuilder.doc;
  28967. var text = doc.createTextNode(source.substr(start));
  28968. doc.appendChild(text);
  28969. domBuilder.currentElement = text;
  28970. }
  28971. return;
  28972. }
  28973. if (tagStart > start) {
  28974. appendText(tagStart);
  28975. }
  28976. switch (source.charAt(tagStart + 1)) {
  28977. case '/':
  28978. var end = source.indexOf('>', tagStart + 3);
  28979. var tagName = source.substring(tagStart + 2, end).replace(/[ \t\n\r]+$/g, '');
  28980. var config = parseStack.pop();
  28981. if (end < 0) {
  28982. tagName = source.substring(tagStart + 2).replace(/[\s<].*/, '');
  28983. errorHandler.error("end tag name: " + tagName + ' is not complete:' + config.tagName);
  28984. end = tagStart + 1 + tagName.length;
  28985. } else if (tagName.match(/\s</)) {
  28986. tagName = tagName.replace(/[\s<].*/, '');
  28987. errorHandler.error("end tag name: " + tagName + ' maybe not complete');
  28988. end = tagStart + 1 + tagName.length;
  28989. }
  28990. var localNSMap = config.localNSMap;
  28991. var endMatch = config.tagName == tagName;
  28992. var endIgnoreCaseMach = endMatch || config.tagName && config.tagName.toLowerCase() == tagName.toLowerCase();
  28993. if (endIgnoreCaseMach) {
  28994. domBuilder.endElement(config.uri, config.localName, tagName);
  28995. if (localNSMap) {
  28996. for (var prefix in localNSMap) {
  28997. if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) {
  28998. domBuilder.endPrefixMapping(prefix);
  28999. }
  29000. }
  29001. }
  29002. if (!endMatch) {
  29003. errorHandler.fatalError("end tag name: " + tagName + ' is not match the current start tagName:' + config.tagName); // No known test case
  29004. }
  29005. } else {
  29006. parseStack.push(config);
  29007. }
  29008. end++;
  29009. break;
  29010. // end elment
  29011. case '?':
  29012. // <?...?>
  29013. locator && position(tagStart);
  29014. end = parseInstruction(source, tagStart, domBuilder);
  29015. break;
  29016. case '!':
  29017. // <!doctype,<![CDATA,<!--
  29018. locator && position(tagStart);
  29019. end = parseDCC(source, tagStart, domBuilder, errorHandler);
  29020. break;
  29021. default:
  29022. locator && position(tagStart);
  29023. var el = new ElementAttributes();
  29024. var currentNSMap = parseStack[parseStack.length - 1].currentNSMap;
  29025. //elStartEnd
  29026. var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler);
  29027. var len = el.length;
  29028. if (!el.closed && fixSelfClosed(source, end, el.tagName, closeMap)) {
  29029. el.closed = true;
  29030. if (!entityMap.nbsp) {
  29031. errorHandler.warning('unclosed xml attribute');
  29032. }
  29033. }
  29034. if (locator && len) {
  29035. var locator2 = copyLocator(locator, {});
  29036. //try{//attribute position fixed
  29037. for (var i = 0; i < len; i++) {
  29038. var a = el[i];
  29039. position(a.offset);
  29040. a.locator = copyLocator(locator, {});
  29041. }
  29042. domBuilder.locator = locator2;
  29043. if (appendElement$1(el, domBuilder, currentNSMap)) {
  29044. parseStack.push(el);
  29045. }
  29046. domBuilder.locator = locator;
  29047. } else {
  29048. if (appendElement$1(el, domBuilder, currentNSMap)) {
  29049. parseStack.push(el);
  29050. }
  29051. }
  29052. if (NAMESPACE$1.isHTML(el.uri) && !el.closed) {
  29053. end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder);
  29054. } else {
  29055. end++;
  29056. }
  29057. }
  29058. } catch (e) {
  29059. if (e instanceof ParseError$1) {
  29060. throw e;
  29061. }
  29062. errorHandler.error('element parse error: ' + e);
  29063. end = -1;
  29064. }
  29065. if (end > start) {
  29066. start = end;
  29067. } else {
  29068. //TODO: 这里有可能sax回退,有位置错误风险
  29069. appendText(Math.max(tagStart, start) + 1);
  29070. }
  29071. }
  29072. }
  29073. function copyLocator(f, t) {
  29074. t.lineNumber = f.lineNumber;
  29075. t.columnNumber = f.columnNumber;
  29076. return t;
  29077. }
  29078. /**
  29079. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  29080. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  29081. */
  29082. function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler) {
  29083. /**
  29084. * @param {string} qname
  29085. * @param {string} value
  29086. * @param {number} startIndex
  29087. */
  29088. function addAttribute(qname, value, startIndex) {
  29089. if (el.attributeNames.hasOwnProperty(qname)) {
  29090. errorHandler.fatalError('Attribute ' + qname + ' redefined');
  29091. }
  29092. el.addValue(qname,
  29093. // @see https://www.w3.org/TR/xml/#AVNormalize
  29094. // since the xmldom sax parser does not "interpret" DTD the following is not implemented:
  29095. // - recursive replacement of (DTD) entity references
  29096. // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA
  29097. value.replace(/[\t\n\r]/g, ' ').replace(/&#?\w+;/g, entityReplacer), startIndex);
  29098. }
  29099. var attrName;
  29100. var value;
  29101. var p = ++start;
  29102. var s = S_TAG; //status
  29103. while (true) {
  29104. var c = source.charAt(p);
  29105. switch (c) {
  29106. case '=':
  29107. if (s === S_ATTR) {
  29108. //attrName
  29109. attrName = source.slice(start, p);
  29110. s = S_EQ;
  29111. } else if (s === S_ATTR_SPACE) {
  29112. s = S_EQ;
  29113. } else {
  29114. //fatalError: equal must after attrName or space after attrName
  29115. throw new Error('attribute equal must after attrName'); // No known test case
  29116. }
  29117. break;
  29118. case '\'':
  29119. case '"':
  29120. if (s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
  29121. ) {
  29122. //equal
  29123. if (s === S_ATTR) {
  29124. errorHandler.warning('attribute value must after "="');
  29125. attrName = source.slice(start, p);
  29126. }
  29127. start = p + 1;
  29128. p = source.indexOf(c, start);
  29129. if (p > 0) {
  29130. value = source.slice(start, p);
  29131. addAttribute(attrName, value, start - 1);
  29132. s = S_ATTR_END;
  29133. } else {
  29134. //fatalError: no end quot match
  29135. throw new Error('attribute value no end \'' + c + '\' match');
  29136. }
  29137. } else if (s == S_ATTR_NOQUOT_VALUE) {
  29138. value = source.slice(start, p);
  29139. addAttribute(attrName, value, start);
  29140. errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ')!!');
  29141. start = p + 1;
  29142. s = S_ATTR_END;
  29143. } else {
  29144. //fatalError: no equal before
  29145. throw new Error('attribute value must after "="'); // No known test case
  29146. }
  29147. break;
  29148. case '/':
  29149. switch (s) {
  29150. case S_TAG:
  29151. el.setTagName(source.slice(start, p));
  29152. case S_ATTR_END:
  29153. case S_TAG_SPACE:
  29154. case S_TAG_CLOSE:
  29155. s = S_TAG_CLOSE;
  29156. el.closed = true;
  29157. case S_ATTR_NOQUOT_VALUE:
  29158. case S_ATTR:
  29159. case S_ATTR_SPACE:
  29160. break;
  29161. //case S_EQ:
  29162. default:
  29163. throw new Error("attribute invalid close char('/')");
  29164. // No known test case
  29165. }
  29166. break;
  29167. case '':
  29168. //end document
  29169. errorHandler.error('unexpected end of input');
  29170. if (s == S_TAG) {
  29171. el.setTagName(source.slice(start, p));
  29172. }
  29173. return p;
  29174. case '>':
  29175. switch (s) {
  29176. case S_TAG:
  29177. el.setTagName(source.slice(start, p));
  29178. case S_ATTR_END:
  29179. case S_TAG_SPACE:
  29180. case S_TAG_CLOSE:
  29181. break;
  29182. //normal
  29183. case S_ATTR_NOQUOT_VALUE: //Compatible state
  29184. case S_ATTR:
  29185. value = source.slice(start, p);
  29186. if (value.slice(-1) === '/') {
  29187. el.closed = true;
  29188. value = value.slice(0, -1);
  29189. }
  29190. case S_ATTR_SPACE:
  29191. if (s === S_ATTR_SPACE) {
  29192. value = attrName;
  29193. }
  29194. if (s == S_ATTR_NOQUOT_VALUE) {
  29195. errorHandler.warning('attribute "' + value + '" missed quot(")!');
  29196. addAttribute(attrName, value, start);
  29197. } else {
  29198. if (!NAMESPACE$1.isHTML(currentNSMap['']) || !value.match(/^(?:disabled|checked|selected)$/i)) {
  29199. errorHandler.warning('attribute "' + value + '" missed value!! "' + value + '" instead!!');
  29200. }
  29201. addAttribute(value, value, start);
  29202. }
  29203. break;
  29204. case S_EQ:
  29205. throw new Error('attribute value missed!!');
  29206. }
  29207. // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  29208. return p;
  29209. /*xml space '\x20' | #x9 | #xD | #xA; */
  29210. case '\u0080':
  29211. c = ' ';
  29212. default:
  29213. if (c <= ' ') {
  29214. //space
  29215. switch (s) {
  29216. case S_TAG:
  29217. el.setTagName(source.slice(start, p)); //tagName
  29218. s = S_TAG_SPACE;
  29219. break;
  29220. case S_ATTR:
  29221. attrName = source.slice(start, p);
  29222. s = S_ATTR_SPACE;
  29223. break;
  29224. case S_ATTR_NOQUOT_VALUE:
  29225. var value = source.slice(start, p);
  29226. errorHandler.warning('attribute "' + value + '" missed quot(")!!');
  29227. addAttribute(attrName, value, start);
  29228. case S_ATTR_END:
  29229. s = S_TAG_SPACE;
  29230. break;
  29231. //case S_TAG_SPACE:
  29232. //case S_EQ:
  29233. //case S_ATTR_SPACE:
  29234. // void();break;
  29235. //case S_TAG_CLOSE:
  29236. //ignore warning
  29237. }
  29238. } else {
  29239. //not space
  29240. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  29241. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  29242. switch (s) {
  29243. //case S_TAG:void();break;
  29244. //case S_ATTR:void();break;
  29245. //case S_ATTR_NOQUOT_VALUE:void();break;
  29246. case S_ATTR_SPACE:
  29247. el.tagName;
  29248. if (!NAMESPACE$1.isHTML(currentNSMap['']) || !attrName.match(/^(?:disabled|checked|selected)$/i)) {
  29249. errorHandler.warning('attribute "' + attrName + '" missed value!! "' + attrName + '" instead2!!');
  29250. }
  29251. addAttribute(attrName, attrName, start);
  29252. start = p;
  29253. s = S_ATTR;
  29254. break;
  29255. case S_ATTR_END:
  29256. errorHandler.warning('attribute space is required"' + attrName + '"!!');
  29257. case S_TAG_SPACE:
  29258. s = S_ATTR;
  29259. start = p;
  29260. break;
  29261. case S_EQ:
  29262. s = S_ATTR_NOQUOT_VALUE;
  29263. start = p;
  29264. break;
  29265. case S_TAG_CLOSE:
  29266. throw new Error("elements closed character '/' and '>' must be connected to");
  29267. }
  29268. }
  29269. } //end outer switch
  29270. //console.log('p++',p)
  29271. p++;
  29272. }
  29273. }
  29274. /**
  29275. * @return true if has new namespace define
  29276. */
  29277. function appendElement$1(el, domBuilder, currentNSMap) {
  29278. var tagName = el.tagName;
  29279. var localNSMap = null;
  29280. //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  29281. var i = el.length;
  29282. while (i--) {
  29283. var a = el[i];
  29284. var qName = a.qName;
  29285. var value = a.value;
  29286. var nsp = qName.indexOf(':');
  29287. if (nsp > 0) {
  29288. var prefix = a.prefix = qName.slice(0, nsp);
  29289. var localName = qName.slice(nsp + 1);
  29290. var nsPrefix = prefix === 'xmlns' && localName;
  29291. } else {
  29292. localName = qName;
  29293. prefix = null;
  29294. nsPrefix = qName === 'xmlns' && '';
  29295. }
  29296. //can not set prefix,because prefix !== ''
  29297. a.localName = localName;
  29298. //prefix == null for no ns prefix attribute
  29299. if (nsPrefix !== false) {
  29300. //hack!!
  29301. if (localNSMap == null) {
  29302. localNSMap = {};
  29303. //console.log(currentNSMap,0)
  29304. _copy(currentNSMap, currentNSMap = {});
  29305. //console.log(currentNSMap,1)
  29306. }
  29307. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  29308. a.uri = NAMESPACE$1.XMLNS;
  29309. domBuilder.startPrefixMapping(nsPrefix, value);
  29310. }
  29311. }
  29312. var i = el.length;
  29313. while (i--) {
  29314. a = el[i];
  29315. var prefix = a.prefix;
  29316. if (prefix) {
  29317. //no prefix attribute has no namespace
  29318. if (prefix === 'xml') {
  29319. a.uri = NAMESPACE$1.XML;
  29320. }
  29321. if (prefix !== 'xmlns') {
  29322. a.uri = currentNSMap[prefix || ''];
  29323. //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  29324. }
  29325. }
  29326. }
  29327. var nsp = tagName.indexOf(':');
  29328. if (nsp > 0) {
  29329. prefix = el.prefix = tagName.slice(0, nsp);
  29330. localName = el.localName = tagName.slice(nsp + 1);
  29331. } else {
  29332. prefix = null; //important!!
  29333. localName = el.localName = tagName;
  29334. }
  29335. //no prefix element has default namespace
  29336. var ns = el.uri = currentNSMap[prefix || ''];
  29337. domBuilder.startElement(ns, localName, tagName, el);
  29338. //endPrefixMapping and startPrefixMapping have not any help for dom builder
  29339. //localNSMap = null
  29340. if (el.closed) {
  29341. domBuilder.endElement(ns, localName, tagName);
  29342. if (localNSMap) {
  29343. for (prefix in localNSMap) {
  29344. if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) {
  29345. domBuilder.endPrefixMapping(prefix);
  29346. }
  29347. }
  29348. }
  29349. } else {
  29350. el.currentNSMap = currentNSMap;
  29351. el.localNSMap = localNSMap;
  29352. //parseStack.push(el);
  29353. return true;
  29354. }
  29355. }
  29356. function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) {
  29357. if (/^(?:script|textarea)$/i.test(tagName)) {
  29358. var elEndStart = source.indexOf('</' + tagName + '>', elStartEnd);
  29359. var text = source.substring(elStartEnd + 1, elEndStart);
  29360. if (/[&<]/.test(text)) {
  29361. if (/^script$/i.test(tagName)) {
  29362. //if(!/\]\]>/.test(text)){
  29363. //lexHandler.startCDATA();
  29364. domBuilder.characters(text, 0, text.length);
  29365. //lexHandler.endCDATA();
  29366. return elEndStart;
  29367. //}
  29368. } //}else{//text area
  29369. text = text.replace(/&#?\w+;/g, entityReplacer);
  29370. domBuilder.characters(text, 0, text.length);
  29371. return elEndStart;
  29372. //}
  29373. }
  29374. }
  29375. return elStartEnd + 1;
  29376. }
  29377. function fixSelfClosed(source, elStartEnd, tagName, closeMap) {
  29378. //if(tagName in closeMap){
  29379. var pos = closeMap[tagName];
  29380. if (pos == null) {
  29381. //console.log(tagName)
  29382. pos = source.lastIndexOf('</' + tagName + '>');
  29383. if (pos < elStartEnd) {
  29384. //忘记闭合
  29385. pos = source.lastIndexOf('</' + tagName);
  29386. }
  29387. closeMap[tagName] = pos;
  29388. }
  29389. return pos < elStartEnd;
  29390. //}
  29391. }
  29392. function _copy(source, target) {
  29393. for (var n in source) {
  29394. if (Object.prototype.hasOwnProperty.call(source, n)) {
  29395. target[n] = source[n];
  29396. }
  29397. }
  29398. }
  29399. function parseDCC(source, start, domBuilder, errorHandler) {
  29400. //sure start with '<!'
  29401. var next = source.charAt(start + 2);
  29402. switch (next) {
  29403. case '-':
  29404. if (source.charAt(start + 3) === '-') {
  29405. var end = source.indexOf('-->', start + 4);
  29406. //append comment source.substring(4,end)//<!--
  29407. if (end > start) {
  29408. domBuilder.comment(source, start + 4, end - start - 4);
  29409. return end + 3;
  29410. } else {
  29411. errorHandler.error("Unclosed comment");
  29412. return -1;
  29413. }
  29414. } else {
  29415. //error
  29416. return -1;
  29417. }
  29418. default:
  29419. if (source.substr(start + 3, 6) == 'CDATA[') {
  29420. var end = source.indexOf(']]>', start + 9);
  29421. domBuilder.startCDATA();
  29422. domBuilder.characters(source, start + 9, end - start - 9);
  29423. domBuilder.endCDATA();
  29424. return end + 3;
  29425. }
  29426. //<!DOCTYPE
  29427. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  29428. var matchs = split(source, start);
  29429. var len = matchs.length;
  29430. if (len > 1 && /!doctype/i.test(matchs[0][0])) {
  29431. var name = matchs[1][0];
  29432. var pubid = false;
  29433. var sysid = false;
  29434. if (len > 3) {
  29435. if (/^public$/i.test(matchs[2][0])) {
  29436. pubid = matchs[3][0];
  29437. sysid = len > 4 && matchs[4][0];
  29438. } else if (/^system$/i.test(matchs[2][0])) {
  29439. sysid = matchs[3][0];
  29440. }
  29441. }
  29442. var lastMatch = matchs[len - 1];
  29443. domBuilder.startDTD(name, pubid, sysid);
  29444. domBuilder.endDTD();
  29445. return lastMatch.index + lastMatch[0].length;
  29446. }
  29447. }
  29448. return -1;
  29449. }
  29450. function parseInstruction(source, start, domBuilder) {
  29451. var end = source.indexOf('?>', start);
  29452. if (end) {
  29453. var match = source.substring(start, end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  29454. if (match) {
  29455. match[0].length;
  29456. domBuilder.processingInstruction(match[1], match[2]);
  29457. return end + 2;
  29458. } else {
  29459. //error
  29460. return -1;
  29461. }
  29462. }
  29463. return -1;
  29464. }
  29465. function ElementAttributes() {
  29466. this.attributeNames = {};
  29467. }
  29468. ElementAttributes.prototype = {
  29469. setTagName: function (tagName) {
  29470. if (!tagNamePattern.test(tagName)) {
  29471. throw new Error('invalid tagName:' + tagName);
  29472. }
  29473. this.tagName = tagName;
  29474. },
  29475. addValue: function (qName, value, offset) {
  29476. if (!tagNamePattern.test(qName)) {
  29477. throw new Error('invalid attribute:' + qName);
  29478. }
  29479. this.attributeNames[qName] = this.length;
  29480. this[this.length++] = {
  29481. qName: qName,
  29482. value: value,
  29483. offset: offset
  29484. };
  29485. },
  29486. length: 0,
  29487. getLocalName: function (i) {
  29488. return this[i].localName;
  29489. },
  29490. getLocator: function (i) {
  29491. return this[i].locator;
  29492. },
  29493. getQName: function (i) {
  29494. return this[i].qName;
  29495. },
  29496. getURI: function (i) {
  29497. return this[i].uri;
  29498. },
  29499. getValue: function (i) {
  29500. return this[i].value;
  29501. }
  29502. // ,getIndex:function(uri, localName)){
  29503. // if(localName){
  29504. //
  29505. // }else{
  29506. // var qName = uri
  29507. // }
  29508. // },
  29509. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  29510. // getType:function(uri,localName){}
  29511. // getType:function(i){},
  29512. };
  29513. function split(source, start) {
  29514. var match;
  29515. var buf = [];
  29516. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  29517. reg.lastIndex = start;
  29518. reg.exec(source); //skip <
  29519. while (match = reg.exec(source)) {
  29520. buf.push(match);
  29521. if (match[1]) return buf;
  29522. }
  29523. }
  29524. var XMLReader_1 = XMLReader$1;
  29525. var ParseError_1 = ParseError$1;
  29526. var sax = {
  29527. XMLReader: XMLReader_1,
  29528. ParseError: ParseError_1
  29529. };
  29530. var DOMImplementation = dom.DOMImplementation;
  29531. var NAMESPACE = conventions.NAMESPACE;
  29532. var ParseError = sax.ParseError;
  29533. var XMLReader = sax.XMLReader;
  29534. /**
  29535. * Normalizes line ending according to https://www.w3.org/TR/xml11/#sec-line-ends:
  29536. *
  29537. * > XML parsed entities are often stored in computer files which,
  29538. * > for editing convenience, are organized into lines.
  29539. * > These lines are typically separated by some combination
  29540. * > of the characters CARRIAGE RETURN (#xD) and LINE FEED (#xA).
  29541. * >
  29542. * > To simplify the tasks of applications, the XML processor must behave
  29543. * > as if it normalized all line breaks in external parsed entities (including the document entity)
  29544. * > on input, before parsing, by translating all of the following to a single #xA character:
  29545. * >
  29546. * > 1. the two-character sequence #xD #xA
  29547. * > 2. the two-character sequence #xD #x85
  29548. * > 3. the single character #x85
  29549. * > 4. the single character #x2028
  29550. * > 5. any #xD character that is not immediately followed by #xA or #x85.
  29551. *
  29552. * @param {string} input
  29553. * @returns {string}
  29554. */
  29555. function normalizeLineEndings(input) {
  29556. return input.replace(/\r[\n\u0085]/g, '\n').replace(/[\r\u0085\u2028]/g, '\n');
  29557. }
  29558. /**
  29559. * @typedef Locator
  29560. * @property {number} [columnNumber]
  29561. * @property {number} [lineNumber]
  29562. */
  29563. /**
  29564. * @typedef DOMParserOptions
  29565. * @property {DOMHandler} [domBuilder]
  29566. * @property {Function} [errorHandler]
  29567. * @property {(string) => string} [normalizeLineEndings] used to replace line endings before parsing
  29568. * defaults to `normalizeLineEndings`
  29569. * @property {Locator} [locator]
  29570. * @property {Record<string, string>} [xmlns]
  29571. *
  29572. * @see normalizeLineEndings
  29573. */
  29574. /**
  29575. * The DOMParser interface provides the ability to parse XML or HTML source code
  29576. * from a string into a DOM `Document`.
  29577. *
  29578. * _xmldom is different from the spec in that it allows an `options` parameter,
  29579. * to override the default behavior._
  29580. *
  29581. * @param {DOMParserOptions} [options]
  29582. * @constructor
  29583. *
  29584. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
  29585. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization
  29586. */
  29587. function DOMParser$1(options) {
  29588. this.options = options || {
  29589. locator: {}
  29590. };
  29591. }
  29592. DOMParser$1.prototype.parseFromString = function (source, mimeType) {
  29593. var options = this.options;
  29594. var sax = new XMLReader();
  29595. var domBuilder = options.domBuilder || new DOMHandler(); //contentHandler and LexicalHandler
  29596. var errorHandler = options.errorHandler;
  29597. var locator = options.locator;
  29598. var defaultNSMap = options.xmlns || {};
  29599. var isHTML = /\/x?html?$/.test(mimeType); //mimeType.toLowerCase().indexOf('html') > -1;
  29600. var entityMap = isHTML ? entities.HTML_ENTITIES : entities.XML_ENTITIES;
  29601. if (locator) {
  29602. domBuilder.setDocumentLocator(locator);
  29603. }
  29604. sax.errorHandler = buildErrorHandler(errorHandler, domBuilder, locator);
  29605. sax.domBuilder = options.domBuilder || domBuilder;
  29606. if (isHTML) {
  29607. defaultNSMap[''] = NAMESPACE.HTML;
  29608. }
  29609. defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML;
  29610. var normalize = options.normalizeLineEndings || normalizeLineEndings;
  29611. if (source && typeof source === 'string') {
  29612. sax.parse(normalize(source), defaultNSMap, entityMap);
  29613. } else {
  29614. sax.errorHandler.error('invalid doc source');
  29615. }
  29616. return domBuilder.doc;
  29617. };
  29618. function buildErrorHandler(errorImpl, domBuilder, locator) {
  29619. if (!errorImpl) {
  29620. if (domBuilder instanceof DOMHandler) {
  29621. return domBuilder;
  29622. }
  29623. errorImpl = domBuilder;
  29624. }
  29625. var errorHandler = {};
  29626. var isCallback = errorImpl instanceof Function;
  29627. locator = locator || {};
  29628. function build(key) {
  29629. var fn = errorImpl[key];
  29630. if (!fn && isCallback) {
  29631. fn = errorImpl.length == 2 ? function (msg) {
  29632. errorImpl(key, msg);
  29633. } : errorImpl;
  29634. }
  29635. errorHandler[key] = fn && function (msg) {
  29636. fn('[xmldom ' + key + ']\t' + msg + _locator(locator));
  29637. } || function () {};
  29638. }
  29639. build('warning');
  29640. build('error');
  29641. build('fatalError');
  29642. return errorHandler;
  29643. }
  29644. //console.log('#\n\n\n\n\n\n\n####')
  29645. /**
  29646. * +ContentHandler+ErrorHandler
  29647. * +LexicalHandler+EntityResolver2
  29648. * -DeclHandler-DTDHandler
  29649. *
  29650. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  29651. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  29652. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  29653. */
  29654. function DOMHandler() {
  29655. this.cdata = false;
  29656. }
  29657. function position(locator, node) {
  29658. node.lineNumber = locator.lineNumber;
  29659. node.columnNumber = locator.columnNumber;
  29660. }
  29661. /**
  29662. * @see org.xml.sax.ContentHandler#startDocument
  29663. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  29664. */
  29665. DOMHandler.prototype = {
  29666. startDocument: function () {
  29667. this.doc = new DOMImplementation().createDocument(null, null, null);
  29668. if (this.locator) {
  29669. this.doc.documentURI = this.locator.systemId;
  29670. }
  29671. },
  29672. startElement: function (namespaceURI, localName, qName, attrs) {
  29673. var doc = this.doc;
  29674. var el = doc.createElementNS(namespaceURI, qName || localName);
  29675. var len = attrs.length;
  29676. appendElement(this, el);
  29677. this.currentElement = el;
  29678. this.locator && position(this.locator, el);
  29679. for (var i = 0; i < len; i++) {
  29680. var namespaceURI = attrs.getURI(i);
  29681. var value = attrs.getValue(i);
  29682. var qName = attrs.getQName(i);
  29683. var attr = doc.createAttributeNS(namespaceURI, qName);
  29684. this.locator && position(attrs.getLocator(i), attr);
  29685. attr.value = attr.nodeValue = value;
  29686. el.setAttributeNode(attr);
  29687. }
  29688. },
  29689. endElement: function (namespaceURI, localName, qName) {
  29690. var current = this.currentElement;
  29691. current.tagName;
  29692. this.currentElement = current.parentNode;
  29693. },
  29694. startPrefixMapping: function (prefix, uri) {},
  29695. endPrefixMapping: function (prefix) {},
  29696. processingInstruction: function (target, data) {
  29697. var ins = this.doc.createProcessingInstruction(target, data);
  29698. this.locator && position(this.locator, ins);
  29699. appendElement(this, ins);
  29700. },
  29701. ignorableWhitespace: function (ch, start, length) {},
  29702. characters: function (chars, start, length) {
  29703. chars = _toString.apply(this, arguments);
  29704. //console.log(chars)
  29705. if (chars) {
  29706. if (this.cdata) {
  29707. var charNode = this.doc.createCDATASection(chars);
  29708. } else {
  29709. var charNode = this.doc.createTextNode(chars);
  29710. }
  29711. if (this.currentElement) {
  29712. this.currentElement.appendChild(charNode);
  29713. } else if (/^\s*$/.test(chars)) {
  29714. this.doc.appendChild(charNode);
  29715. //process xml
  29716. }
  29717. this.locator && position(this.locator, charNode);
  29718. }
  29719. },
  29720. skippedEntity: function (name) {},
  29721. endDocument: function () {
  29722. this.doc.normalize();
  29723. },
  29724. setDocumentLocator: function (locator) {
  29725. if (this.locator = locator) {
  29726. // && !('lineNumber' in locator)){
  29727. locator.lineNumber = 0;
  29728. }
  29729. },
  29730. //LexicalHandler
  29731. comment: function (chars, start, length) {
  29732. chars = _toString.apply(this, arguments);
  29733. var comm = this.doc.createComment(chars);
  29734. this.locator && position(this.locator, comm);
  29735. appendElement(this, comm);
  29736. },
  29737. startCDATA: function () {
  29738. //used in characters() methods
  29739. this.cdata = true;
  29740. },
  29741. endCDATA: function () {
  29742. this.cdata = false;
  29743. },
  29744. startDTD: function (name, publicId, systemId) {
  29745. var impl = this.doc.implementation;
  29746. if (impl && impl.createDocumentType) {
  29747. var dt = impl.createDocumentType(name, publicId, systemId);
  29748. this.locator && position(this.locator, dt);
  29749. appendElement(this, dt);
  29750. this.doc.doctype = dt;
  29751. }
  29752. },
  29753. /**
  29754. * @see org.xml.sax.ErrorHandler
  29755. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  29756. */
  29757. warning: function (error) {
  29758. console.warn('[xmldom warning]\t' + error, _locator(this.locator));
  29759. },
  29760. error: function (error) {
  29761. console.error('[xmldom error]\t' + error, _locator(this.locator));
  29762. },
  29763. fatalError: function (error) {
  29764. throw new ParseError(error, this.locator);
  29765. }
  29766. };
  29767. function _locator(l) {
  29768. if (l) {
  29769. return '\n@' + (l.systemId || '') + '#[line:' + l.lineNumber + ',col:' + l.columnNumber + ']';
  29770. }
  29771. }
  29772. function _toString(chars, start, length) {
  29773. if (typeof chars == 'string') {
  29774. return chars.substr(start, length);
  29775. } else {
  29776. //java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  29777. if (chars.length >= start + length || start) {
  29778. return new java.lang.String(chars, start, length) + '';
  29779. }
  29780. return chars;
  29781. }
  29782. }
  29783. /*
  29784. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  29785. * used method of org.xml.sax.ext.LexicalHandler:
  29786. * #comment(chars, start, length)
  29787. * #startCDATA()
  29788. * #endCDATA()
  29789. * #startDTD(name, publicId, systemId)
  29790. *
  29791. *
  29792. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  29793. * #endDTD()
  29794. * #startEntity(name)
  29795. * #endEntity(name)
  29796. *
  29797. *
  29798. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  29799. * IGNORED method of org.xml.sax.ext.DeclHandler
  29800. * #attributeDecl(eName, aName, type, mode, value)
  29801. * #elementDecl(name, model)
  29802. * #externalEntityDecl(name, publicId, systemId)
  29803. * #internalEntityDecl(name, value)
  29804. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  29805. * IGNORED method of org.xml.sax.EntityResolver2
  29806. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  29807. * #resolveEntity(publicId, systemId)
  29808. * #getExternalSubset(name, baseURI)
  29809. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  29810. * IGNORED method of org.xml.sax.DTDHandler
  29811. * #notationDecl(name, publicId, systemId) {};
  29812. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  29813. */
  29814. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g, function (key) {
  29815. DOMHandler.prototype[key] = function () {
  29816. return null;
  29817. };
  29818. });
  29819. /* 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 */
  29820. function appendElement(hander, node) {
  29821. if (!hander.currentElement) {
  29822. hander.doc.appendChild(node);
  29823. } else {
  29824. hander.currentElement.appendChild(node);
  29825. }
  29826. } //appendChild and setAttributeNS are preformance key
  29827. var __DOMHandler = DOMHandler;
  29828. var normalizeLineEndings_1 = normalizeLineEndings;
  29829. var DOMParser_1 = DOMParser$1;
  29830. var domParser = {
  29831. __DOMHandler: __DOMHandler,
  29832. normalizeLineEndings: normalizeLineEndings_1,
  29833. DOMParser: DOMParser_1
  29834. };
  29835. var DOMParser = domParser.DOMParser;
  29836. /*! @name mpd-parser @version 1.0.1 @license Apache-2.0 */
  29837. const isObject = obj => {
  29838. return !!obj && typeof obj === 'object';
  29839. };
  29840. const merge$1 = (...objects) => {
  29841. return objects.reduce((result, source) => {
  29842. if (typeof source !== 'object') {
  29843. return result;
  29844. }
  29845. Object.keys(source).forEach(key => {
  29846. if (Array.isArray(result[key]) && Array.isArray(source[key])) {
  29847. result[key] = result[key].concat(source[key]);
  29848. } else if (isObject(result[key]) && isObject(source[key])) {
  29849. result[key] = merge$1(result[key], source[key]);
  29850. } else {
  29851. result[key] = source[key];
  29852. }
  29853. });
  29854. return result;
  29855. }, {});
  29856. };
  29857. const values = o => Object.keys(o).map(k => o[k]);
  29858. const range = (start, end) => {
  29859. const result = [];
  29860. for (let i = start; i < end; i++) {
  29861. result.push(i);
  29862. }
  29863. return result;
  29864. };
  29865. const flatten = lists => lists.reduce((x, y) => x.concat(y), []);
  29866. const from = list => {
  29867. if (!list.length) {
  29868. return [];
  29869. }
  29870. const result = [];
  29871. for (let i = 0; i < list.length; i++) {
  29872. result.push(list[i]);
  29873. }
  29874. return result;
  29875. };
  29876. const findIndexes = (l, key) => l.reduce((a, e, i) => {
  29877. if (e[key]) {
  29878. a.push(i);
  29879. }
  29880. return a;
  29881. }, []);
  29882. /**
  29883. * Returns a union of the included lists provided each element can be identified by a key.
  29884. *
  29885. * @param {Array} list - list of lists to get the union of
  29886. * @param {Function} keyFunction - the function to use as a key for each element
  29887. *
  29888. * @return {Array} the union of the arrays
  29889. */
  29890. const union = (lists, keyFunction) => {
  29891. return values(lists.reduce((acc, list) => {
  29892. list.forEach(el => {
  29893. acc[keyFunction(el)] = el;
  29894. });
  29895. return acc;
  29896. }, {}));
  29897. };
  29898. var errors = {
  29899. INVALID_NUMBER_OF_PERIOD: 'INVALID_NUMBER_OF_PERIOD',
  29900. DASH_EMPTY_MANIFEST: 'DASH_EMPTY_MANIFEST',
  29901. DASH_INVALID_XML: 'DASH_INVALID_XML',
  29902. NO_BASE_URL: 'NO_BASE_URL',
  29903. MISSING_SEGMENT_INFORMATION: 'MISSING_SEGMENT_INFORMATION',
  29904. SEGMENT_TIME_UNSPECIFIED: 'SEGMENT_TIME_UNSPECIFIED',
  29905. UNSUPPORTED_UTC_TIMING_SCHEME: 'UNSUPPORTED_UTC_TIMING_SCHEME'
  29906. };
  29907. /**
  29908. * @typedef {Object} SingleUri
  29909. * @property {string} uri - relative location of segment
  29910. * @property {string} resolvedUri - resolved location of segment
  29911. * @property {Object} byterange - Object containing information on how to make byte range
  29912. * requests following byte-range-spec per RFC2616.
  29913. * @property {String} byterange.length - length of range request
  29914. * @property {String} byterange.offset - byte offset of range request
  29915. *
  29916. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1
  29917. */
  29918. /**
  29919. * Converts a URLType node (5.3.9.2.3 Table 13) to a segment object
  29920. * that conforms to how m3u8-parser is structured
  29921. *
  29922. * @see https://github.com/videojs/m3u8-parser
  29923. *
  29924. * @param {string} baseUrl - baseUrl provided by <BaseUrl> nodes
  29925. * @param {string} source - source url for segment
  29926. * @param {string} range - optional range used for range calls,
  29927. * follows RFC 2616, Clause 14.35.1
  29928. * @return {SingleUri} full segment information transformed into a format similar
  29929. * to m3u8-parser
  29930. */
  29931. const urlTypeToSegment = ({
  29932. baseUrl = '',
  29933. source = '',
  29934. range = '',
  29935. indexRange = ''
  29936. }) => {
  29937. const segment = {
  29938. uri: source,
  29939. resolvedUri: resolveUrl$1(baseUrl || '', source)
  29940. };
  29941. if (range || indexRange) {
  29942. const rangeStr = range ? range : indexRange;
  29943. const ranges = rangeStr.split('-'); // default to parsing this as a BigInt if possible
  29944. let startRange = window.BigInt ? window.BigInt(ranges[0]) : parseInt(ranges[0], 10);
  29945. let endRange = window.BigInt ? window.BigInt(ranges[1]) : parseInt(ranges[1], 10); // convert back to a number if less than MAX_SAFE_INTEGER
  29946. if (startRange < Number.MAX_SAFE_INTEGER && typeof startRange === 'bigint') {
  29947. startRange = Number(startRange);
  29948. }
  29949. if (endRange < Number.MAX_SAFE_INTEGER && typeof endRange === 'bigint') {
  29950. endRange = Number(endRange);
  29951. }
  29952. let length;
  29953. if (typeof endRange === 'bigint' || typeof startRange === 'bigint') {
  29954. length = window.BigInt(endRange) - window.BigInt(startRange) + window.BigInt(1);
  29955. } else {
  29956. length = endRange - startRange + 1;
  29957. }
  29958. if (typeof length === 'bigint' && length < Number.MAX_SAFE_INTEGER) {
  29959. length = Number(length);
  29960. } // byterange should be inclusive according to
  29961. // RFC 2616, Clause 14.35.1
  29962. segment.byterange = {
  29963. length,
  29964. offset: startRange
  29965. };
  29966. }
  29967. return segment;
  29968. };
  29969. const byteRangeToString = byterange => {
  29970. // `endRange` is one less than `offset + length` because the HTTP range
  29971. // header uses inclusive ranges
  29972. let endRange;
  29973. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  29974. endRange = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  29975. } else {
  29976. endRange = byterange.offset + byterange.length - 1;
  29977. }
  29978. return `${byterange.offset}-${endRange}`;
  29979. };
  29980. /**
  29981. * parse the end number attribue that can be a string
  29982. * number, or undefined.
  29983. *
  29984. * @param {string|number|undefined} endNumber
  29985. * The end number attribute.
  29986. *
  29987. * @return {number|null}
  29988. * The result of parsing the end number.
  29989. */
  29990. const parseEndNumber = endNumber => {
  29991. if (endNumber && typeof endNumber !== 'number') {
  29992. endNumber = parseInt(endNumber, 10);
  29993. }
  29994. if (isNaN(endNumber)) {
  29995. return null;
  29996. }
  29997. return endNumber;
  29998. };
  29999. /**
  30000. * Functions for calculating the range of available segments in static and dynamic
  30001. * manifests.
  30002. */
  30003. const segmentRange = {
  30004. /**
  30005. * Returns the entire range of available segments for a static MPD
  30006. *
  30007. * @param {Object} attributes
  30008. * Inheritied MPD attributes
  30009. * @return {{ start: number, end: number }}
  30010. * The start and end numbers for available segments
  30011. */
  30012. static(attributes) {
  30013. const {
  30014. duration,
  30015. timescale = 1,
  30016. sourceDuration,
  30017. periodDuration
  30018. } = attributes;
  30019. const endNumber = parseEndNumber(attributes.endNumber);
  30020. const segmentDuration = duration / timescale;
  30021. if (typeof endNumber === 'number') {
  30022. return {
  30023. start: 0,
  30024. end: endNumber
  30025. };
  30026. }
  30027. if (typeof periodDuration === 'number') {
  30028. return {
  30029. start: 0,
  30030. end: periodDuration / segmentDuration
  30031. };
  30032. }
  30033. return {
  30034. start: 0,
  30035. end: sourceDuration / segmentDuration
  30036. };
  30037. },
  30038. /**
  30039. * Returns the current live window range of available segments for a dynamic MPD
  30040. *
  30041. * @param {Object} attributes
  30042. * Inheritied MPD attributes
  30043. * @return {{ start: number, end: number }}
  30044. * The start and end numbers for available segments
  30045. */
  30046. dynamic(attributes) {
  30047. const {
  30048. NOW,
  30049. clientOffset,
  30050. availabilityStartTime,
  30051. timescale = 1,
  30052. duration,
  30053. periodStart = 0,
  30054. minimumUpdatePeriod = 0,
  30055. timeShiftBufferDepth = Infinity
  30056. } = attributes;
  30057. const endNumber = parseEndNumber(attributes.endNumber); // clientOffset is passed in at the top level of mpd-parser and is an offset calculated
  30058. // after retrieving UTC server time.
  30059. const now = (NOW + clientOffset) / 1000; // WC stands for Wall Clock.
  30060. // Convert the period start time to EPOCH.
  30061. const periodStartWC = availabilityStartTime + periodStart; // Period end in EPOCH is manifest's retrieval time + time until next update.
  30062. const periodEndWC = now + minimumUpdatePeriod;
  30063. const periodDuration = periodEndWC - periodStartWC;
  30064. const segmentCount = Math.ceil(periodDuration * timescale / duration);
  30065. const availableStart = Math.floor((now - periodStartWC - timeShiftBufferDepth) * timescale / duration);
  30066. const availableEnd = Math.floor((now - periodStartWC) * timescale / duration);
  30067. return {
  30068. start: Math.max(0, availableStart),
  30069. end: typeof endNumber === 'number' ? endNumber : Math.min(segmentCount, availableEnd)
  30070. };
  30071. }
  30072. };
  30073. /**
  30074. * Maps a range of numbers to objects with information needed to build the corresponding
  30075. * segment list
  30076. *
  30077. * @name toSegmentsCallback
  30078. * @function
  30079. * @param {number} number
  30080. * Number of the segment
  30081. * @param {number} index
  30082. * Index of the number in the range list
  30083. * @return {{ number: Number, duration: Number, timeline: Number, time: Number }}
  30084. * Object with segment timing and duration info
  30085. */
  30086. /**
  30087. * Returns a callback for Array.prototype.map for mapping a range of numbers to
  30088. * information needed to build the segment list.
  30089. *
  30090. * @param {Object} attributes
  30091. * Inherited MPD attributes
  30092. * @return {toSegmentsCallback}
  30093. * Callback map function
  30094. */
  30095. const toSegments = attributes => number => {
  30096. const {
  30097. duration,
  30098. timescale = 1,
  30099. periodStart,
  30100. startNumber = 1
  30101. } = attributes;
  30102. return {
  30103. number: startNumber + number,
  30104. duration: duration / timescale,
  30105. timeline: periodStart,
  30106. time: number * duration
  30107. };
  30108. };
  30109. /**
  30110. * Returns a list of objects containing segment timing and duration info used for
  30111. * building the list of segments. This uses the @duration attribute specified
  30112. * in the MPD manifest to derive the range of segments.
  30113. *
  30114. * @param {Object} attributes
  30115. * Inherited MPD attributes
  30116. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  30117. * List of Objects with segment timing and duration info
  30118. */
  30119. const parseByDuration = attributes => {
  30120. const {
  30121. type,
  30122. duration,
  30123. timescale = 1,
  30124. periodDuration,
  30125. sourceDuration
  30126. } = attributes;
  30127. const {
  30128. start,
  30129. end
  30130. } = segmentRange[type](attributes);
  30131. const segments = range(start, end).map(toSegments(attributes));
  30132. if (type === 'static') {
  30133. const index = segments.length - 1; // section is either a period or the full source
  30134. const sectionDuration = typeof periodDuration === 'number' ? periodDuration : sourceDuration; // final segment may be less than full segment duration
  30135. segments[index].duration = sectionDuration - duration / timescale * index;
  30136. }
  30137. return segments;
  30138. };
  30139. /**
  30140. * Translates SegmentBase into a set of segments.
  30141. * (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  30142. * node should be translated into segment.
  30143. *
  30144. * @param {Object} attributes
  30145. * Object containing all inherited attributes from parent elements with attribute
  30146. * names as keys
  30147. * @return {Object.<Array>} list of segments
  30148. */
  30149. const segmentsFromBase = attributes => {
  30150. const {
  30151. baseUrl,
  30152. initialization = {},
  30153. sourceDuration,
  30154. indexRange = '',
  30155. periodStart,
  30156. presentationTime,
  30157. number = 0,
  30158. duration
  30159. } = attributes; // base url is required for SegmentBase to work, per spec (Section 5.3.9.2.1)
  30160. if (!baseUrl) {
  30161. throw new Error(errors.NO_BASE_URL);
  30162. }
  30163. const initSegment = urlTypeToSegment({
  30164. baseUrl,
  30165. source: initialization.sourceURL,
  30166. range: initialization.range
  30167. });
  30168. const segment = urlTypeToSegment({
  30169. baseUrl,
  30170. source: baseUrl,
  30171. indexRange
  30172. });
  30173. segment.map = initSegment; // If there is a duration, use it, otherwise use the given duration of the source
  30174. // (since SegmentBase is only for one total segment)
  30175. if (duration) {
  30176. const segmentTimeInfo = parseByDuration(attributes);
  30177. if (segmentTimeInfo.length) {
  30178. segment.duration = segmentTimeInfo[0].duration;
  30179. segment.timeline = segmentTimeInfo[0].timeline;
  30180. }
  30181. } else if (sourceDuration) {
  30182. segment.duration = sourceDuration;
  30183. segment.timeline = periodStart;
  30184. } // If presentation time is provided, these segments are being generated by SIDX
  30185. // references, and should use the time provided. For the general case of SegmentBase,
  30186. // there should only be one segment in the period, so its presentation time is the same
  30187. // as its period start.
  30188. segment.presentationTime = presentationTime || periodStart;
  30189. segment.number = number;
  30190. return [segment];
  30191. };
  30192. /**
  30193. * Given a playlist, a sidx box, and a baseUrl, update the segment list of the playlist
  30194. * according to the sidx information given.
  30195. *
  30196. * playlist.sidx has metadadata about the sidx where-as the sidx param
  30197. * is the parsed sidx box itself.
  30198. *
  30199. * @param {Object} playlist the playlist to update the sidx information for
  30200. * @param {Object} sidx the parsed sidx box
  30201. * @return {Object} the playlist object with the updated sidx information
  30202. */
  30203. const addSidxSegmentsToPlaylist$1 = (playlist, sidx, baseUrl) => {
  30204. // Retain init segment information
  30205. const initSegment = playlist.sidx.map ? playlist.sidx.map : null; // Retain source duration from initial main manifest parsing
  30206. const sourceDuration = playlist.sidx.duration; // Retain source timeline
  30207. const timeline = playlist.timeline || 0;
  30208. const sidxByteRange = playlist.sidx.byterange;
  30209. const sidxEnd = sidxByteRange.offset + sidxByteRange.length; // Retain timescale of the parsed sidx
  30210. const timescale = sidx.timescale; // referenceType 1 refers to other sidx boxes
  30211. const mediaReferences = sidx.references.filter(r => r.referenceType !== 1);
  30212. const segments = [];
  30213. const type = playlist.endList ? 'static' : 'dynamic';
  30214. const periodStart = playlist.sidx.timeline;
  30215. let presentationTime = periodStart;
  30216. let number = playlist.mediaSequence || 0; // firstOffset is the offset from the end of the sidx box
  30217. let startIndex; // eslint-disable-next-line
  30218. if (typeof sidx.firstOffset === 'bigint') {
  30219. startIndex = window.BigInt(sidxEnd) + sidx.firstOffset;
  30220. } else {
  30221. startIndex = sidxEnd + sidx.firstOffset;
  30222. }
  30223. for (let i = 0; i < mediaReferences.length; i++) {
  30224. const reference = sidx.references[i]; // size of the referenced (sub)segment
  30225. const size = reference.referencedSize; // duration of the referenced (sub)segment, in the timescale
  30226. // this will be converted to seconds when generating segments
  30227. const duration = reference.subsegmentDuration; // should be an inclusive range
  30228. let endIndex; // eslint-disable-next-line
  30229. if (typeof startIndex === 'bigint') {
  30230. endIndex = startIndex + window.BigInt(size) - window.BigInt(1);
  30231. } else {
  30232. endIndex = startIndex + size - 1;
  30233. }
  30234. const indexRange = `${startIndex}-${endIndex}`;
  30235. const attributes = {
  30236. baseUrl,
  30237. timescale,
  30238. timeline,
  30239. periodStart,
  30240. presentationTime,
  30241. number,
  30242. duration,
  30243. sourceDuration,
  30244. indexRange,
  30245. type
  30246. };
  30247. const segment = segmentsFromBase(attributes)[0];
  30248. if (initSegment) {
  30249. segment.map = initSegment;
  30250. }
  30251. segments.push(segment);
  30252. if (typeof startIndex === 'bigint') {
  30253. startIndex += window.BigInt(size);
  30254. } else {
  30255. startIndex += size;
  30256. }
  30257. presentationTime += duration / timescale;
  30258. number++;
  30259. }
  30260. playlist.segments = segments;
  30261. return playlist;
  30262. };
  30263. const SUPPORTED_MEDIA_TYPES = ['AUDIO', 'SUBTITLES']; // allow one 60fps frame as leniency (arbitrarily chosen)
  30264. const TIME_FUDGE = 1 / 60;
  30265. /**
  30266. * Given a list of timelineStarts, combines, dedupes, and sorts them.
  30267. *
  30268. * @param {TimelineStart[]} timelineStarts - list of timeline starts
  30269. *
  30270. * @return {TimelineStart[]} the combined and deduped timeline starts
  30271. */
  30272. const getUniqueTimelineStarts = timelineStarts => {
  30273. return union(timelineStarts, ({
  30274. timeline
  30275. }) => timeline).sort((a, b) => a.timeline > b.timeline ? 1 : -1);
  30276. };
  30277. /**
  30278. * Finds the playlist with the matching NAME attribute.
  30279. *
  30280. * @param {Array} playlists - playlists to search through
  30281. * @param {string} name - the NAME attribute to search for
  30282. *
  30283. * @return {Object|null} the matching playlist object, or null
  30284. */
  30285. const findPlaylistWithName = (playlists, name) => {
  30286. for (let i = 0; i < playlists.length; i++) {
  30287. if (playlists[i].attributes.NAME === name) {
  30288. return playlists[i];
  30289. }
  30290. }
  30291. return null;
  30292. };
  30293. /**
  30294. * Gets a flattened array of media group playlists.
  30295. *
  30296. * @param {Object} manifest - the main manifest object
  30297. *
  30298. * @return {Array} the media group playlists
  30299. */
  30300. const getMediaGroupPlaylists = manifest => {
  30301. let mediaGroupPlaylists = [];
  30302. forEachMediaGroup$1(manifest, SUPPORTED_MEDIA_TYPES, (properties, type, group, label) => {
  30303. mediaGroupPlaylists = mediaGroupPlaylists.concat(properties.playlists || []);
  30304. });
  30305. return mediaGroupPlaylists;
  30306. };
  30307. /**
  30308. * Updates the playlist's media sequence numbers.
  30309. *
  30310. * @param {Object} config - options object
  30311. * @param {Object} config.playlist - the playlist to update
  30312. * @param {number} config.mediaSequence - the mediaSequence number to start with
  30313. */
  30314. const updateMediaSequenceForPlaylist = ({
  30315. playlist,
  30316. mediaSequence
  30317. }) => {
  30318. playlist.mediaSequence = mediaSequence;
  30319. playlist.segments.forEach((segment, index) => {
  30320. segment.number = playlist.mediaSequence + index;
  30321. });
  30322. };
  30323. /**
  30324. * Updates the media and discontinuity sequence numbers of newPlaylists given oldPlaylists
  30325. * and a complete list of timeline starts.
  30326. *
  30327. * If no matching playlist is found, only the discontinuity sequence number of the playlist
  30328. * will be updated.
  30329. *
  30330. * Since early available timelines are not supported, at least one segment must be present.
  30331. *
  30332. * @param {Object} config - options object
  30333. * @param {Object[]} oldPlaylists - the old playlists to use as a reference
  30334. * @param {Object[]} newPlaylists - the new playlists to update
  30335. * @param {Object} timelineStarts - all timelineStarts seen in the stream to this point
  30336. */
  30337. const updateSequenceNumbers = ({
  30338. oldPlaylists,
  30339. newPlaylists,
  30340. timelineStarts
  30341. }) => {
  30342. newPlaylists.forEach(playlist => {
  30343. playlist.discontinuitySequence = timelineStarts.findIndex(function ({
  30344. timeline
  30345. }) {
  30346. return timeline === playlist.timeline;
  30347. }); // Playlists NAMEs come from DASH Representation IDs, which are mandatory
  30348. // (see ISO_23009-1-2012 5.3.5.2).
  30349. //
  30350. // If the same Representation existed in a prior Period, it will retain the same NAME.
  30351. const oldPlaylist = findPlaylistWithName(oldPlaylists, playlist.attributes.NAME);
  30352. if (!oldPlaylist) {
  30353. // Since this is a new playlist, the media sequence values can start from 0 without
  30354. // consequence.
  30355. return;
  30356. } // TODO better support for live SIDX
  30357. //
  30358. // As of this writing, mpd-parser does not support multiperiod SIDX (in live or VOD).
  30359. // This is evident by a playlist only having a single SIDX reference. In a multiperiod
  30360. // playlist there would need to be multiple SIDX references. In addition, live SIDX is
  30361. // not supported when the SIDX properties change on refreshes.
  30362. //
  30363. // In the future, if support needs to be added, the merging logic here can be called
  30364. // after SIDX references are resolved. For now, exit early to prevent exceptions being
  30365. // thrown due to undefined references.
  30366. if (playlist.sidx) {
  30367. return;
  30368. } // Since we don't yet support early available timelines, we don't need to support
  30369. // playlists with no segments.
  30370. const firstNewSegment = playlist.segments[0];
  30371. const oldMatchingSegmentIndex = oldPlaylist.segments.findIndex(function (oldSegment) {
  30372. return Math.abs(oldSegment.presentationTime - firstNewSegment.presentationTime) < TIME_FUDGE;
  30373. }); // No matching segment from the old playlist means the entire playlist was refreshed.
  30374. // In this case the media sequence should account for this update, and the new segments
  30375. // should be marked as discontinuous from the prior content, since the last prior
  30376. // timeline was removed.
  30377. if (oldMatchingSegmentIndex === -1) {
  30378. updateMediaSequenceForPlaylist({
  30379. playlist,
  30380. mediaSequence: oldPlaylist.mediaSequence + oldPlaylist.segments.length
  30381. });
  30382. playlist.segments[0].discontinuity = true;
  30383. playlist.discontinuityStarts.unshift(0); // No matching segment does not necessarily mean there's missing content.
  30384. //
  30385. // If the new playlist's timeline is the same as the last seen segment's timeline,
  30386. // then a discontinuity can be added to identify that there's potentially missing
  30387. // content. If there's no missing content, the discontinuity should still be rather
  30388. // harmless. It's possible that if segment durations are accurate enough, that the
  30389. // existence of a gap can be determined using the presentation times and durations,
  30390. // but if the segment timing info is off, it may introduce more problems than simply
  30391. // adding the discontinuity.
  30392. //
  30393. // If the new playlist's timeline is different from the last seen segment's timeline,
  30394. // then a discontinuity can be added to identify that this is the first seen segment
  30395. // of a new timeline. However, the logic at the start of this function that
  30396. // determined the disconinuity sequence by timeline index is now off by one (the
  30397. // discontinuity of the newest timeline hasn't yet fallen off the manifest...since
  30398. // we added it), so the disconinuity sequence must be decremented.
  30399. //
  30400. // A period may also have a duration of zero, so the case of no segments is handled
  30401. // here even though we don't yet support early available periods.
  30402. if (!oldPlaylist.segments.length && playlist.timeline > oldPlaylist.timeline || oldPlaylist.segments.length && playlist.timeline > oldPlaylist.segments[oldPlaylist.segments.length - 1].timeline) {
  30403. playlist.discontinuitySequence--;
  30404. }
  30405. return;
  30406. } // If the first segment matched with a prior segment on a discontinuity (it's matching
  30407. // on the first segment of a period), then the discontinuitySequence shouldn't be the
  30408. // timeline's matching one, but instead should be the one prior, and the first segment
  30409. // of the new manifest should be marked with a discontinuity.
  30410. //
  30411. // The reason for this special case is that discontinuity sequence shows how many
  30412. // discontinuities have fallen off of the playlist, and discontinuities are marked on
  30413. // the first segment of a new "timeline." Because of this, while DASH will retain that
  30414. // Period while the "timeline" exists, HLS keeps track of it via the discontinuity
  30415. // sequence, and that first segment is an indicator, but can be removed before that
  30416. // timeline is gone.
  30417. const oldMatchingSegment = oldPlaylist.segments[oldMatchingSegmentIndex];
  30418. if (oldMatchingSegment.discontinuity && !firstNewSegment.discontinuity) {
  30419. firstNewSegment.discontinuity = true;
  30420. playlist.discontinuityStarts.unshift(0);
  30421. playlist.discontinuitySequence--;
  30422. }
  30423. updateMediaSequenceForPlaylist({
  30424. playlist,
  30425. mediaSequence: oldPlaylist.segments[oldMatchingSegmentIndex].number
  30426. });
  30427. });
  30428. };
  30429. /**
  30430. * Given an old parsed manifest object and a new parsed manifest object, updates the
  30431. * sequence and timing values within the new manifest to ensure that it lines up with the
  30432. * old.
  30433. *
  30434. * @param {Array} oldManifest - the old main manifest object
  30435. * @param {Array} newManifest - the new main manifest object
  30436. *
  30437. * @return {Object} the updated new manifest object
  30438. */
  30439. const positionManifestOnTimeline = ({
  30440. oldManifest,
  30441. newManifest
  30442. }) => {
  30443. // Starting from v4.1.2 of the IOP, section 4.4.3.3 states:
  30444. //
  30445. // "MPD@availabilityStartTime and Period@start shall not be changed over MPD updates."
  30446. //
  30447. // This was added from https://github.com/Dash-Industry-Forum/DASH-IF-IOP/issues/160
  30448. //
  30449. // Because of this change, and the difficulty of supporting periods with changing start
  30450. // times, periods with changing start times are not supported. This makes the logic much
  30451. // simpler, since periods with the same start time can be considerred the same period
  30452. // across refreshes.
  30453. //
  30454. // To give an example as to the difficulty of handling periods where the start time may
  30455. // change, if a single period manifest is refreshed with another manifest with a single
  30456. // period, and both the start and end times are increased, then the only way to determine
  30457. // if it's a new period or an old one that has changed is to look through the segments of
  30458. // each playlist and determine the presentation time bounds to find a match. In addition,
  30459. // if the period start changed to exceed the old period end, then there would be no
  30460. // match, and it would not be possible to determine whether the refreshed period is a new
  30461. // one or the old one.
  30462. const oldPlaylists = oldManifest.playlists.concat(getMediaGroupPlaylists(oldManifest));
  30463. const newPlaylists = newManifest.playlists.concat(getMediaGroupPlaylists(newManifest)); // Save all seen timelineStarts to the new manifest. Although this potentially means that
  30464. // there's a "memory leak" in that it will never stop growing, in reality, only a couple
  30465. // of properties are saved for each seen Period. Even long running live streams won't
  30466. // generate too many Periods, unless the stream is watched for decades. In the future,
  30467. // this can be optimized by mapping to discontinuity sequence numbers for each timeline,
  30468. // but it may not become an issue, and the additional info can be useful for debugging.
  30469. newManifest.timelineStarts = getUniqueTimelineStarts([oldManifest.timelineStarts, newManifest.timelineStarts]);
  30470. updateSequenceNumbers({
  30471. oldPlaylists,
  30472. newPlaylists,
  30473. timelineStarts: newManifest.timelineStarts
  30474. });
  30475. return newManifest;
  30476. };
  30477. const generateSidxKey = sidx => sidx && sidx.uri + '-' + byteRangeToString(sidx.byterange);
  30478. const mergeDiscontiguousPlaylists = playlists => {
  30479. const mergedPlaylists = values(playlists.reduce((acc, playlist) => {
  30480. // assuming playlist IDs are the same across periods
  30481. // TODO: handle multiperiod where representation sets are not the same
  30482. // across periods
  30483. const name = playlist.attributes.id + (playlist.attributes.lang || '');
  30484. if (!acc[name]) {
  30485. // First Period
  30486. acc[name] = playlist;
  30487. acc[name].attributes.timelineStarts = [];
  30488. } else {
  30489. // Subsequent Periods
  30490. if (playlist.segments) {
  30491. // first segment of subsequent periods signal a discontinuity
  30492. if (playlist.segments[0]) {
  30493. playlist.segments[0].discontinuity = true;
  30494. }
  30495. acc[name].segments.push(...playlist.segments);
  30496. } // bubble up contentProtection, this assumes all DRM content
  30497. // has the same contentProtection
  30498. if (playlist.attributes.contentProtection) {
  30499. acc[name].attributes.contentProtection = playlist.attributes.contentProtection;
  30500. }
  30501. }
  30502. acc[name].attributes.timelineStarts.push({
  30503. // Although they represent the same number, it's important to have both to make it
  30504. // compatible with HLS potentially having a similar attribute.
  30505. start: playlist.attributes.periodStart,
  30506. timeline: playlist.attributes.periodStart
  30507. });
  30508. return acc;
  30509. }, {}));
  30510. return mergedPlaylists.map(playlist => {
  30511. playlist.discontinuityStarts = findIndexes(playlist.segments || [], 'discontinuity');
  30512. return playlist;
  30513. });
  30514. };
  30515. const addSidxSegmentsToPlaylist = (playlist, sidxMapping) => {
  30516. const sidxKey = generateSidxKey(playlist.sidx);
  30517. const sidxMatch = sidxKey && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx;
  30518. if (sidxMatch) {
  30519. addSidxSegmentsToPlaylist$1(playlist, sidxMatch, playlist.sidx.resolvedUri);
  30520. }
  30521. return playlist;
  30522. };
  30523. const addSidxSegmentsToPlaylists = (playlists, sidxMapping = {}) => {
  30524. if (!Object.keys(sidxMapping).length) {
  30525. return playlists;
  30526. }
  30527. for (const i in playlists) {
  30528. playlists[i] = addSidxSegmentsToPlaylist(playlists[i], sidxMapping);
  30529. }
  30530. return playlists;
  30531. };
  30532. const formatAudioPlaylist = ({
  30533. attributes,
  30534. segments,
  30535. sidx,
  30536. mediaSequence,
  30537. discontinuitySequence,
  30538. discontinuityStarts
  30539. }, isAudioOnly) => {
  30540. const playlist = {
  30541. attributes: {
  30542. NAME: attributes.id,
  30543. BANDWIDTH: attributes.bandwidth,
  30544. CODECS: attributes.codecs,
  30545. ['PROGRAM-ID']: 1
  30546. },
  30547. uri: '',
  30548. endList: attributes.type === 'static',
  30549. timeline: attributes.periodStart,
  30550. resolvedUri: '',
  30551. targetDuration: attributes.duration,
  30552. discontinuitySequence,
  30553. discontinuityStarts,
  30554. timelineStarts: attributes.timelineStarts,
  30555. mediaSequence,
  30556. segments
  30557. };
  30558. if (attributes.contentProtection) {
  30559. playlist.contentProtection = attributes.contentProtection;
  30560. }
  30561. if (sidx) {
  30562. playlist.sidx = sidx;
  30563. }
  30564. if (isAudioOnly) {
  30565. playlist.attributes.AUDIO = 'audio';
  30566. playlist.attributes.SUBTITLES = 'subs';
  30567. }
  30568. return playlist;
  30569. };
  30570. const formatVttPlaylist = ({
  30571. attributes,
  30572. segments,
  30573. mediaSequence,
  30574. discontinuityStarts,
  30575. discontinuitySequence
  30576. }) => {
  30577. if (typeof segments === 'undefined') {
  30578. // vtt tracks may use single file in BaseURL
  30579. segments = [{
  30580. uri: attributes.baseUrl,
  30581. timeline: attributes.periodStart,
  30582. resolvedUri: attributes.baseUrl || '',
  30583. duration: attributes.sourceDuration,
  30584. number: 0
  30585. }]; // targetDuration should be the same duration as the only segment
  30586. attributes.duration = attributes.sourceDuration;
  30587. }
  30588. const m3u8Attributes = {
  30589. NAME: attributes.id,
  30590. BANDWIDTH: attributes.bandwidth,
  30591. ['PROGRAM-ID']: 1
  30592. };
  30593. if (attributes.codecs) {
  30594. m3u8Attributes.CODECS = attributes.codecs;
  30595. }
  30596. return {
  30597. attributes: m3u8Attributes,
  30598. uri: '',
  30599. endList: attributes.type === 'static',
  30600. timeline: attributes.periodStart,
  30601. resolvedUri: attributes.baseUrl || '',
  30602. targetDuration: attributes.duration,
  30603. timelineStarts: attributes.timelineStarts,
  30604. discontinuityStarts,
  30605. discontinuitySequence,
  30606. mediaSequence,
  30607. segments
  30608. };
  30609. };
  30610. const organizeAudioPlaylists = (playlists, sidxMapping = {}, isAudioOnly = false) => {
  30611. let mainPlaylist;
  30612. const formattedPlaylists = playlists.reduce((a, playlist) => {
  30613. const role = playlist.attributes.role && playlist.attributes.role.value || '';
  30614. const language = playlist.attributes.lang || '';
  30615. let label = playlist.attributes.label || 'main';
  30616. if (language && !playlist.attributes.label) {
  30617. const roleLabel = role ? ` (${role})` : '';
  30618. label = `${playlist.attributes.lang}${roleLabel}`;
  30619. }
  30620. if (!a[label]) {
  30621. a[label] = {
  30622. language,
  30623. autoselect: true,
  30624. default: role === 'main',
  30625. playlists: [],
  30626. uri: ''
  30627. };
  30628. }
  30629. const formatted = addSidxSegmentsToPlaylist(formatAudioPlaylist(playlist, isAudioOnly), sidxMapping);
  30630. a[label].playlists.push(formatted);
  30631. if (typeof mainPlaylist === 'undefined' && role === 'main') {
  30632. mainPlaylist = playlist;
  30633. mainPlaylist.default = true;
  30634. }
  30635. return a;
  30636. }, {}); // if no playlists have role "main", mark the first as main
  30637. if (!mainPlaylist) {
  30638. const firstLabel = Object.keys(formattedPlaylists)[0];
  30639. formattedPlaylists[firstLabel].default = true;
  30640. }
  30641. return formattedPlaylists;
  30642. };
  30643. const organizeVttPlaylists = (playlists, sidxMapping = {}) => {
  30644. return playlists.reduce((a, playlist) => {
  30645. const label = playlist.attributes.lang || 'text';
  30646. if (!a[label]) {
  30647. a[label] = {
  30648. language: label,
  30649. default: false,
  30650. autoselect: false,
  30651. playlists: [],
  30652. uri: ''
  30653. };
  30654. }
  30655. a[label].playlists.push(addSidxSegmentsToPlaylist(formatVttPlaylist(playlist), sidxMapping));
  30656. return a;
  30657. }, {});
  30658. };
  30659. const organizeCaptionServices = captionServices => captionServices.reduce((svcObj, svc) => {
  30660. if (!svc) {
  30661. return svcObj;
  30662. }
  30663. svc.forEach(service => {
  30664. const {
  30665. channel,
  30666. language
  30667. } = service;
  30668. svcObj[language] = {
  30669. autoselect: false,
  30670. default: false,
  30671. instreamId: channel,
  30672. language
  30673. };
  30674. if (service.hasOwnProperty('aspectRatio')) {
  30675. svcObj[language].aspectRatio = service.aspectRatio;
  30676. }
  30677. if (service.hasOwnProperty('easyReader')) {
  30678. svcObj[language].easyReader = service.easyReader;
  30679. }
  30680. if (service.hasOwnProperty('3D')) {
  30681. svcObj[language]['3D'] = service['3D'];
  30682. }
  30683. });
  30684. return svcObj;
  30685. }, {});
  30686. const formatVideoPlaylist = ({
  30687. attributes,
  30688. segments,
  30689. sidx,
  30690. discontinuityStarts
  30691. }) => {
  30692. const playlist = {
  30693. attributes: {
  30694. NAME: attributes.id,
  30695. AUDIO: 'audio',
  30696. SUBTITLES: 'subs',
  30697. RESOLUTION: {
  30698. width: attributes.width,
  30699. height: attributes.height
  30700. },
  30701. CODECS: attributes.codecs,
  30702. BANDWIDTH: attributes.bandwidth,
  30703. ['PROGRAM-ID']: 1
  30704. },
  30705. uri: '',
  30706. endList: attributes.type === 'static',
  30707. timeline: attributes.periodStart,
  30708. resolvedUri: '',
  30709. targetDuration: attributes.duration,
  30710. discontinuityStarts,
  30711. timelineStarts: attributes.timelineStarts,
  30712. segments
  30713. };
  30714. if (attributes.frameRate) {
  30715. playlist.attributes['FRAME-RATE'] = attributes.frameRate;
  30716. }
  30717. if (attributes.contentProtection) {
  30718. playlist.contentProtection = attributes.contentProtection;
  30719. }
  30720. if (sidx) {
  30721. playlist.sidx = sidx;
  30722. }
  30723. return playlist;
  30724. };
  30725. const videoOnly = ({
  30726. attributes
  30727. }) => attributes.mimeType === 'video/mp4' || attributes.mimeType === 'video/webm' || attributes.contentType === 'video';
  30728. const audioOnly = ({
  30729. attributes
  30730. }) => attributes.mimeType === 'audio/mp4' || attributes.mimeType === 'audio/webm' || attributes.contentType === 'audio';
  30731. const vttOnly = ({
  30732. attributes
  30733. }) => attributes.mimeType === 'text/vtt' || attributes.contentType === 'text';
  30734. /**
  30735. * Contains start and timeline properties denoting a timeline start. For DASH, these will
  30736. * be the same number.
  30737. *
  30738. * @typedef {Object} TimelineStart
  30739. * @property {number} start - the start time of the timeline
  30740. * @property {number} timeline - the timeline number
  30741. */
  30742. /**
  30743. * Adds appropriate media and discontinuity sequence values to the segments and playlists.
  30744. *
  30745. * Throughout mpd-parser, the `number` attribute is used in relation to `startNumber`, a
  30746. * DASH specific attribute used in constructing segment URI's from templates. However, from
  30747. * an HLS perspective, the `number` attribute on a segment would be its `mediaSequence`
  30748. * value, which should start at the original media sequence value (or 0) and increment by 1
  30749. * for each segment thereafter. Since DASH's `startNumber` values are independent per
  30750. * period, it doesn't make sense to use it for `number`. Instead, assume everything starts
  30751. * from a 0 mediaSequence value and increment from there.
  30752. *
  30753. * Note that VHS currently doesn't use the `number` property, but it can be helpful for
  30754. * debugging and making sense of the manifest.
  30755. *
  30756. * For live playlists, to account for values increasing in manifests when periods are
  30757. * removed on refreshes, merging logic should be used to update the numbers to their
  30758. * appropriate values (to ensure they're sequential and increasing).
  30759. *
  30760. * @param {Object[]} playlists - the playlists to update
  30761. * @param {TimelineStart[]} timelineStarts - the timeline starts for the manifest
  30762. */
  30763. const addMediaSequenceValues = (playlists, timelineStarts) => {
  30764. // increment all segments sequentially
  30765. playlists.forEach(playlist => {
  30766. playlist.mediaSequence = 0;
  30767. playlist.discontinuitySequence = timelineStarts.findIndex(function ({
  30768. timeline
  30769. }) {
  30770. return timeline === playlist.timeline;
  30771. });
  30772. if (!playlist.segments) {
  30773. return;
  30774. }
  30775. playlist.segments.forEach((segment, index) => {
  30776. segment.number = index;
  30777. });
  30778. });
  30779. };
  30780. /**
  30781. * Given a media group object, flattens all playlists within the media group into a single
  30782. * array.
  30783. *
  30784. * @param {Object} mediaGroupObject - the media group object
  30785. *
  30786. * @return {Object[]}
  30787. * The media group playlists
  30788. */
  30789. const flattenMediaGroupPlaylists = mediaGroupObject => {
  30790. if (!mediaGroupObject) {
  30791. return [];
  30792. }
  30793. return Object.keys(mediaGroupObject).reduce((acc, label) => {
  30794. const labelContents = mediaGroupObject[label];
  30795. return acc.concat(labelContents.playlists);
  30796. }, []);
  30797. };
  30798. const toM3u8 = ({
  30799. dashPlaylists,
  30800. locations,
  30801. sidxMapping = {},
  30802. previousManifest
  30803. }) => {
  30804. if (!dashPlaylists.length) {
  30805. return {};
  30806. } // grab all main manifest attributes
  30807. const {
  30808. sourceDuration: duration,
  30809. type,
  30810. suggestedPresentationDelay,
  30811. minimumUpdatePeriod
  30812. } = dashPlaylists[0].attributes;
  30813. const videoPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist);
  30814. const audioPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly));
  30815. const vttPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(vttOnly));
  30816. const captions = dashPlaylists.map(playlist => playlist.attributes.captionServices).filter(Boolean);
  30817. const manifest = {
  30818. allowCache: true,
  30819. discontinuityStarts: [],
  30820. segments: [],
  30821. endList: true,
  30822. mediaGroups: {
  30823. AUDIO: {},
  30824. VIDEO: {},
  30825. ['CLOSED-CAPTIONS']: {},
  30826. SUBTITLES: {}
  30827. },
  30828. uri: '',
  30829. duration,
  30830. playlists: addSidxSegmentsToPlaylists(videoPlaylists, sidxMapping)
  30831. };
  30832. if (minimumUpdatePeriod >= 0) {
  30833. manifest.minimumUpdatePeriod = minimumUpdatePeriod * 1000;
  30834. }
  30835. if (locations) {
  30836. manifest.locations = locations;
  30837. }
  30838. if (type === 'dynamic') {
  30839. manifest.suggestedPresentationDelay = suggestedPresentationDelay;
  30840. }
  30841. const isAudioOnly = manifest.playlists.length === 0;
  30842. const organizedAudioGroup = audioPlaylists.length ? organizeAudioPlaylists(audioPlaylists, sidxMapping, isAudioOnly) : null;
  30843. const organizedVttGroup = vttPlaylists.length ? organizeVttPlaylists(vttPlaylists, sidxMapping) : null;
  30844. const formattedPlaylists = videoPlaylists.concat(flattenMediaGroupPlaylists(organizedAudioGroup), flattenMediaGroupPlaylists(organizedVttGroup));
  30845. const playlistTimelineStarts = formattedPlaylists.map(({
  30846. timelineStarts
  30847. }) => timelineStarts);
  30848. manifest.timelineStarts = getUniqueTimelineStarts(playlistTimelineStarts);
  30849. addMediaSequenceValues(formattedPlaylists, manifest.timelineStarts);
  30850. if (organizedAudioGroup) {
  30851. manifest.mediaGroups.AUDIO.audio = organizedAudioGroup;
  30852. }
  30853. if (organizedVttGroup) {
  30854. manifest.mediaGroups.SUBTITLES.subs = organizedVttGroup;
  30855. }
  30856. if (captions.length) {
  30857. manifest.mediaGroups['CLOSED-CAPTIONS'].cc = organizeCaptionServices(captions);
  30858. }
  30859. if (previousManifest) {
  30860. return positionManifestOnTimeline({
  30861. oldManifest: previousManifest,
  30862. newManifest: manifest
  30863. });
  30864. }
  30865. return manifest;
  30866. };
  30867. /**
  30868. * Calculates the R (repetition) value for a live stream (for the final segment
  30869. * in a manifest where the r value is negative 1)
  30870. *
  30871. * @param {Object} attributes
  30872. * Object containing all inherited attributes from parent elements with attribute
  30873. * names as keys
  30874. * @param {number} time
  30875. * current time (typically the total time up until the final segment)
  30876. * @param {number} duration
  30877. * duration property for the given <S />
  30878. *
  30879. * @return {number}
  30880. * R value to reach the end of the given period
  30881. */
  30882. const getLiveRValue = (attributes, time, duration) => {
  30883. const {
  30884. NOW,
  30885. clientOffset,
  30886. availabilityStartTime,
  30887. timescale = 1,
  30888. periodStart = 0,
  30889. minimumUpdatePeriod = 0
  30890. } = attributes;
  30891. const now = (NOW + clientOffset) / 1000;
  30892. const periodStartWC = availabilityStartTime + periodStart;
  30893. const periodEndWC = now + minimumUpdatePeriod;
  30894. const periodDuration = periodEndWC - periodStartWC;
  30895. return Math.ceil((periodDuration * timescale - time) / duration);
  30896. };
  30897. /**
  30898. * Uses information provided by SegmentTemplate.SegmentTimeline to determine segment
  30899. * timing and duration
  30900. *
  30901. * @param {Object} attributes
  30902. * Object containing all inherited attributes from parent elements with attribute
  30903. * names as keys
  30904. * @param {Object[]} segmentTimeline
  30905. * List of objects representing the attributes of each S element contained within
  30906. *
  30907. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  30908. * List of Objects with segment timing and duration info
  30909. */
  30910. const parseByTimeline = (attributes, segmentTimeline) => {
  30911. const {
  30912. type,
  30913. minimumUpdatePeriod = 0,
  30914. media = '',
  30915. sourceDuration,
  30916. timescale = 1,
  30917. startNumber = 1,
  30918. periodStart: timeline
  30919. } = attributes;
  30920. const segments = [];
  30921. let time = -1;
  30922. for (let sIndex = 0; sIndex < segmentTimeline.length; sIndex++) {
  30923. const S = segmentTimeline[sIndex];
  30924. const duration = S.d;
  30925. const repeat = S.r || 0;
  30926. const segmentTime = S.t || 0;
  30927. if (time < 0) {
  30928. // first segment
  30929. time = segmentTime;
  30930. }
  30931. if (segmentTime && segmentTime > time) {
  30932. // discontinuity
  30933. // TODO: How to handle this type of discontinuity
  30934. // timeline++ here would treat it like HLS discontuity and content would
  30935. // get appended without gap
  30936. // E.G.
  30937. // <S t="0" d="1" />
  30938. // <S d="1" />
  30939. // <S d="1" />
  30940. // <S t="5" d="1" />
  30941. // would have $Time$ values of [0, 1, 2, 5]
  30942. // should this be appened at time positions [0, 1, 2, 3],(#EXT-X-DISCONTINUITY)
  30943. // or [0, 1, 2, gap, gap, 5]? (#EXT-X-GAP)
  30944. // does the value of sourceDuration consider this when calculating arbitrary
  30945. // negative @r repeat value?
  30946. // E.G. Same elements as above with this added at the end
  30947. // <S d="1" r="-1" />
  30948. // with a sourceDuration of 10
  30949. // Would the 2 gaps be included in the time duration calculations resulting in
  30950. // 8 segments with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9] or 10 segments
  30951. // with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9, 10, 11] ?
  30952. time = segmentTime;
  30953. }
  30954. let count;
  30955. if (repeat < 0) {
  30956. const nextS = sIndex + 1;
  30957. if (nextS === segmentTimeline.length) {
  30958. // last segment
  30959. if (type === 'dynamic' && minimumUpdatePeriod > 0 && media.indexOf('$Number$') > 0) {
  30960. count = getLiveRValue(attributes, time, duration);
  30961. } else {
  30962. // TODO: This may be incorrect depending on conclusion of TODO above
  30963. count = (sourceDuration * timescale - time) / duration;
  30964. }
  30965. } else {
  30966. count = (segmentTimeline[nextS].t - time) / duration;
  30967. }
  30968. } else {
  30969. count = repeat + 1;
  30970. }
  30971. const end = startNumber + segments.length + count;
  30972. let number = startNumber + segments.length;
  30973. while (number < end) {
  30974. segments.push({
  30975. number,
  30976. duration: duration / timescale,
  30977. time,
  30978. timeline
  30979. });
  30980. time += duration;
  30981. number++;
  30982. }
  30983. }
  30984. return segments;
  30985. };
  30986. const identifierPattern = /\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g;
  30987. /**
  30988. * Replaces template identifiers with corresponding values. To be used as the callback
  30989. * for String.prototype.replace
  30990. *
  30991. * @name replaceCallback
  30992. * @function
  30993. * @param {string} match
  30994. * Entire match of identifier
  30995. * @param {string} identifier
  30996. * Name of matched identifier
  30997. * @param {string} format
  30998. * Format tag string. Its presence indicates that padding is expected
  30999. * @param {string} width
  31000. * Desired length of the replaced value. Values less than this width shall be left
  31001. * zero padded
  31002. * @return {string}
  31003. * Replacement for the matched identifier
  31004. */
  31005. /**
  31006. * Returns a function to be used as a callback for String.prototype.replace to replace
  31007. * template identifiers
  31008. *
  31009. * @param {Obect} values
  31010. * Object containing values that shall be used to replace known identifiers
  31011. * @param {number} values.RepresentationID
  31012. * Value of the Representation@id attribute
  31013. * @param {number} values.Number
  31014. * Number of the corresponding segment
  31015. * @param {number} values.Bandwidth
  31016. * Value of the Representation@bandwidth attribute.
  31017. * @param {number} values.Time
  31018. * Timestamp value of the corresponding segment
  31019. * @return {replaceCallback}
  31020. * Callback to be used with String.prototype.replace to replace identifiers
  31021. */
  31022. const identifierReplacement = values => (match, identifier, format, width) => {
  31023. if (match === '$$') {
  31024. // escape sequence
  31025. return '$';
  31026. }
  31027. if (typeof values[identifier] === 'undefined') {
  31028. return match;
  31029. }
  31030. const value = '' + values[identifier];
  31031. if (identifier === 'RepresentationID') {
  31032. // Format tag shall not be present with RepresentationID
  31033. return value;
  31034. }
  31035. if (!format) {
  31036. width = 1;
  31037. } else {
  31038. width = parseInt(width, 10);
  31039. }
  31040. if (value.length >= width) {
  31041. return value;
  31042. }
  31043. return `${new Array(width - value.length + 1).join('0')}${value}`;
  31044. };
  31045. /**
  31046. * Constructs a segment url from a template string
  31047. *
  31048. * @param {string} url
  31049. * Template string to construct url from
  31050. * @param {Obect} values
  31051. * Object containing values that shall be used to replace known identifiers
  31052. * @param {number} values.RepresentationID
  31053. * Value of the Representation@id attribute
  31054. * @param {number} values.Number
  31055. * Number of the corresponding segment
  31056. * @param {number} values.Bandwidth
  31057. * Value of the Representation@bandwidth attribute.
  31058. * @param {number} values.Time
  31059. * Timestamp value of the corresponding segment
  31060. * @return {string}
  31061. * Segment url with identifiers replaced
  31062. */
  31063. const constructTemplateUrl = (url, values) => url.replace(identifierPattern, identifierReplacement(values));
  31064. /**
  31065. * Generates a list of objects containing timing and duration information about each
  31066. * segment needed to generate segment uris and the complete segment object
  31067. *
  31068. * @param {Object} attributes
  31069. * Object containing all inherited attributes from parent elements with attribute
  31070. * names as keys
  31071. * @param {Object[]|undefined} segmentTimeline
  31072. * List of objects representing the attributes of each S element contained within
  31073. * the SegmentTimeline element
  31074. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  31075. * List of Objects with segment timing and duration info
  31076. */
  31077. const parseTemplateInfo = (attributes, segmentTimeline) => {
  31078. if (!attributes.duration && !segmentTimeline) {
  31079. // if neither @duration or SegmentTimeline are present, then there shall be exactly
  31080. // one media segment
  31081. return [{
  31082. number: attributes.startNumber || 1,
  31083. duration: attributes.sourceDuration,
  31084. time: 0,
  31085. timeline: attributes.periodStart
  31086. }];
  31087. }
  31088. if (attributes.duration) {
  31089. return parseByDuration(attributes);
  31090. }
  31091. return parseByTimeline(attributes, segmentTimeline);
  31092. };
  31093. /**
  31094. * Generates a list of segments using information provided by the SegmentTemplate element
  31095. *
  31096. * @param {Object} attributes
  31097. * Object containing all inherited attributes from parent elements with attribute
  31098. * names as keys
  31099. * @param {Object[]|undefined} segmentTimeline
  31100. * List of objects representing the attributes of each S element contained within
  31101. * the SegmentTimeline element
  31102. * @return {Object[]}
  31103. * List of segment objects
  31104. */
  31105. const segmentsFromTemplate = (attributes, segmentTimeline) => {
  31106. const templateValues = {
  31107. RepresentationID: attributes.id,
  31108. Bandwidth: attributes.bandwidth || 0
  31109. };
  31110. const {
  31111. initialization = {
  31112. sourceURL: '',
  31113. range: ''
  31114. }
  31115. } = attributes;
  31116. const mapSegment = urlTypeToSegment({
  31117. baseUrl: attributes.baseUrl,
  31118. source: constructTemplateUrl(initialization.sourceURL, templateValues),
  31119. range: initialization.range
  31120. });
  31121. const segments = parseTemplateInfo(attributes, segmentTimeline);
  31122. return segments.map(segment => {
  31123. templateValues.Number = segment.number;
  31124. templateValues.Time = segment.time;
  31125. const uri = constructTemplateUrl(attributes.media || '', templateValues); // See DASH spec section 5.3.9.2.2
  31126. // - if timescale isn't present on any level, default to 1.
  31127. const timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  31128. const presentationTimeOffset = attributes.presentationTimeOffset || 0;
  31129. const presentationTime =
  31130. // Even if the @t attribute is not specified for the segment, segment.time is
  31131. // calculated in mpd-parser prior to this, so it's assumed to be available.
  31132. attributes.periodStart + (segment.time - presentationTimeOffset) / timescale;
  31133. const map = {
  31134. uri,
  31135. timeline: segment.timeline,
  31136. duration: segment.duration,
  31137. resolvedUri: resolveUrl$1(attributes.baseUrl || '', uri),
  31138. map: mapSegment,
  31139. number: segment.number,
  31140. presentationTime
  31141. };
  31142. return map;
  31143. });
  31144. };
  31145. /**
  31146. * Converts a <SegmentUrl> (of type URLType from the DASH spec 5.3.9.2 Table 14)
  31147. * to an object that matches the output of a segment in videojs/mpd-parser
  31148. *
  31149. * @param {Object} attributes
  31150. * Object containing all inherited attributes from parent elements with attribute
  31151. * names as keys
  31152. * @param {Object} segmentUrl
  31153. * <SegmentURL> node to translate into a segment object
  31154. * @return {Object} translated segment object
  31155. */
  31156. const SegmentURLToSegmentObject = (attributes, segmentUrl) => {
  31157. const {
  31158. baseUrl,
  31159. initialization = {}
  31160. } = attributes;
  31161. const initSegment = urlTypeToSegment({
  31162. baseUrl,
  31163. source: initialization.sourceURL,
  31164. range: initialization.range
  31165. });
  31166. const segment = urlTypeToSegment({
  31167. baseUrl,
  31168. source: segmentUrl.media,
  31169. range: segmentUrl.mediaRange
  31170. });
  31171. segment.map = initSegment;
  31172. return segment;
  31173. };
  31174. /**
  31175. * Generates a list of segments using information provided by the SegmentList element
  31176. * SegmentList (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  31177. * node should be translated into segment.
  31178. *
  31179. * @param {Object} attributes
  31180. * Object containing all inherited attributes from parent elements with attribute
  31181. * names as keys
  31182. * @param {Object[]|undefined} segmentTimeline
  31183. * List of objects representing the attributes of each S element contained within
  31184. * the SegmentTimeline element
  31185. * @return {Object.<Array>} list of segments
  31186. */
  31187. const segmentsFromList = (attributes, segmentTimeline) => {
  31188. const {
  31189. duration,
  31190. segmentUrls = [],
  31191. periodStart
  31192. } = attributes; // Per spec (5.3.9.2.1) no way to determine segment duration OR
  31193. // if both SegmentTimeline and @duration are defined, it is outside of spec.
  31194. if (!duration && !segmentTimeline || duration && segmentTimeline) {
  31195. throw new Error(errors.SEGMENT_TIME_UNSPECIFIED);
  31196. }
  31197. const segmentUrlMap = segmentUrls.map(segmentUrlObject => SegmentURLToSegmentObject(attributes, segmentUrlObject));
  31198. let segmentTimeInfo;
  31199. if (duration) {
  31200. segmentTimeInfo = parseByDuration(attributes);
  31201. }
  31202. if (segmentTimeline) {
  31203. segmentTimeInfo = parseByTimeline(attributes, segmentTimeline);
  31204. }
  31205. const segments = segmentTimeInfo.map((segmentTime, index) => {
  31206. if (segmentUrlMap[index]) {
  31207. const segment = segmentUrlMap[index]; // See DASH spec section 5.3.9.2.2
  31208. // - if timescale isn't present on any level, default to 1.
  31209. const timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  31210. const presentationTimeOffset = attributes.presentationTimeOffset || 0;
  31211. segment.timeline = segmentTime.timeline;
  31212. segment.duration = segmentTime.duration;
  31213. segment.number = segmentTime.number;
  31214. segment.presentationTime = periodStart + (segmentTime.time - presentationTimeOffset) / timescale;
  31215. return segment;
  31216. } // Since we're mapping we should get rid of any blank segments (in case
  31217. // the given SegmentTimeline is handling for more elements than we have
  31218. // SegmentURLs for).
  31219. }).filter(segment => segment);
  31220. return segments;
  31221. };
  31222. const generateSegments = ({
  31223. attributes,
  31224. segmentInfo
  31225. }) => {
  31226. let segmentAttributes;
  31227. let segmentsFn;
  31228. if (segmentInfo.template) {
  31229. segmentsFn = segmentsFromTemplate;
  31230. segmentAttributes = merge$1(attributes, segmentInfo.template);
  31231. } else if (segmentInfo.base) {
  31232. segmentsFn = segmentsFromBase;
  31233. segmentAttributes = merge$1(attributes, segmentInfo.base);
  31234. } else if (segmentInfo.list) {
  31235. segmentsFn = segmentsFromList;
  31236. segmentAttributes = merge$1(attributes, segmentInfo.list);
  31237. }
  31238. const segmentsInfo = {
  31239. attributes
  31240. };
  31241. if (!segmentsFn) {
  31242. return segmentsInfo;
  31243. }
  31244. const segments = segmentsFn(segmentAttributes, segmentInfo.segmentTimeline); // The @duration attribute will be used to determin the playlist's targetDuration which
  31245. // must be in seconds. Since we've generated the segment list, we no longer need
  31246. // @duration to be in @timescale units, so we can convert it here.
  31247. if (segmentAttributes.duration) {
  31248. const {
  31249. duration,
  31250. timescale = 1
  31251. } = segmentAttributes;
  31252. segmentAttributes.duration = duration / timescale;
  31253. } else if (segments.length) {
  31254. // if there is no @duration attribute, use the largest segment duration as
  31255. // as target duration
  31256. segmentAttributes.duration = segments.reduce((max, segment) => {
  31257. return Math.max(max, Math.ceil(segment.duration));
  31258. }, 0);
  31259. } else {
  31260. segmentAttributes.duration = 0;
  31261. }
  31262. segmentsInfo.attributes = segmentAttributes;
  31263. segmentsInfo.segments = segments; // This is a sidx box without actual segment information
  31264. if (segmentInfo.base && segmentAttributes.indexRange) {
  31265. segmentsInfo.sidx = segments[0];
  31266. segmentsInfo.segments = [];
  31267. }
  31268. return segmentsInfo;
  31269. };
  31270. const toPlaylists = representations => representations.map(generateSegments);
  31271. const findChildren = (element, name) => from(element.childNodes).filter(({
  31272. tagName
  31273. }) => tagName === name);
  31274. const getContent = element => element.textContent.trim();
  31275. /**
  31276. * Converts the provided string that may contain a division operation to a number.
  31277. *
  31278. * @param {string} value - the provided string value
  31279. *
  31280. * @return {number} the parsed string value
  31281. */
  31282. const parseDivisionValue = value => {
  31283. return parseFloat(value.split('/').reduce((prev, current) => prev / current));
  31284. };
  31285. const parseDuration = str => {
  31286. const SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
  31287. const SECONDS_IN_MONTH = 30 * 24 * 60 * 60;
  31288. const SECONDS_IN_DAY = 24 * 60 * 60;
  31289. const SECONDS_IN_HOUR = 60 * 60;
  31290. const SECONDS_IN_MIN = 60; // P10Y10M10DT10H10M10.1S
  31291. const durationRegex = /P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/;
  31292. const match = durationRegex.exec(str);
  31293. if (!match) {
  31294. return 0;
  31295. }
  31296. const [year, month, day, hour, minute, second] = match.slice(1);
  31297. 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);
  31298. };
  31299. const parseDate = str => {
  31300. // Date format without timezone according to ISO 8601
  31301. // YYY-MM-DDThh:mm:ss.ssssss
  31302. const dateRegex = /^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/; // If the date string does not specifiy a timezone, we must specifiy UTC. This is
  31303. // expressed by ending with 'Z'
  31304. if (dateRegex.test(str)) {
  31305. str += 'Z';
  31306. }
  31307. return Date.parse(str);
  31308. };
  31309. const parsers = {
  31310. /**
  31311. * Specifies the duration of the entire Media Presentation. Format is a duration string
  31312. * as specified in ISO 8601
  31313. *
  31314. * @param {string} value
  31315. * value of attribute as a string
  31316. * @return {number}
  31317. * The duration in seconds
  31318. */
  31319. mediaPresentationDuration(value) {
  31320. return parseDuration(value);
  31321. },
  31322. /**
  31323. * Specifies the Segment availability start time for all Segments referred to in this
  31324. * MPD. For a dynamic manifest, it specifies the anchor for the earliest availability
  31325. * time. Format is a date string as specified in ISO 8601
  31326. *
  31327. * @param {string} value
  31328. * value of attribute as a string
  31329. * @return {number}
  31330. * The date as seconds from unix epoch
  31331. */
  31332. availabilityStartTime(value) {
  31333. return parseDate(value) / 1000;
  31334. },
  31335. /**
  31336. * Specifies the smallest period between potential changes to the MPD. Format is a
  31337. * duration string as specified in ISO 8601
  31338. *
  31339. * @param {string} value
  31340. * value of attribute as a string
  31341. * @return {number}
  31342. * The duration in seconds
  31343. */
  31344. minimumUpdatePeriod(value) {
  31345. return parseDuration(value);
  31346. },
  31347. /**
  31348. * Specifies the suggested presentation delay. Format is a
  31349. * duration string as specified in ISO 8601
  31350. *
  31351. * @param {string} value
  31352. * value of attribute as a string
  31353. * @return {number}
  31354. * The duration in seconds
  31355. */
  31356. suggestedPresentationDelay(value) {
  31357. return parseDuration(value);
  31358. },
  31359. /**
  31360. * specifices the type of mpd. Can be either "static" or "dynamic"
  31361. *
  31362. * @param {string} value
  31363. * value of attribute as a string
  31364. *
  31365. * @return {string}
  31366. * The type as a string
  31367. */
  31368. type(value) {
  31369. return value;
  31370. },
  31371. /**
  31372. * Specifies the duration of the smallest time shifting buffer for any Representation
  31373. * in the MPD. Format is a duration string as specified in ISO 8601
  31374. *
  31375. * @param {string} value
  31376. * value of attribute as a string
  31377. * @return {number}
  31378. * The duration in seconds
  31379. */
  31380. timeShiftBufferDepth(value) {
  31381. return parseDuration(value);
  31382. },
  31383. /**
  31384. * Specifies the PeriodStart time of the Period relative to the availabilityStarttime.
  31385. * Format is a duration string as specified in ISO 8601
  31386. *
  31387. * @param {string} value
  31388. * value of attribute as a string
  31389. * @return {number}
  31390. * The duration in seconds
  31391. */
  31392. start(value) {
  31393. return parseDuration(value);
  31394. },
  31395. /**
  31396. * Specifies the width of the visual presentation
  31397. *
  31398. * @param {string} value
  31399. * value of attribute as a string
  31400. * @return {number}
  31401. * The parsed width
  31402. */
  31403. width(value) {
  31404. return parseInt(value, 10);
  31405. },
  31406. /**
  31407. * Specifies the height of the visual presentation
  31408. *
  31409. * @param {string} value
  31410. * value of attribute as a string
  31411. * @return {number}
  31412. * The parsed height
  31413. */
  31414. height(value) {
  31415. return parseInt(value, 10);
  31416. },
  31417. /**
  31418. * Specifies the bitrate of the representation
  31419. *
  31420. * @param {string} value
  31421. * value of attribute as a string
  31422. * @return {number}
  31423. * The parsed bandwidth
  31424. */
  31425. bandwidth(value) {
  31426. return parseInt(value, 10);
  31427. },
  31428. /**
  31429. * Specifies the frame rate of the representation
  31430. *
  31431. * @param {string} value
  31432. * value of attribute as a string
  31433. * @return {number}
  31434. * The parsed frame rate
  31435. */
  31436. frameRate(value) {
  31437. return parseDivisionValue(value);
  31438. },
  31439. /**
  31440. * Specifies the number of the first Media Segment in this Representation in the Period
  31441. *
  31442. * @param {string} value
  31443. * value of attribute as a string
  31444. * @return {number}
  31445. * The parsed number
  31446. */
  31447. startNumber(value) {
  31448. return parseInt(value, 10);
  31449. },
  31450. /**
  31451. * Specifies the timescale in units per seconds
  31452. *
  31453. * @param {string} value
  31454. * value of attribute as a string
  31455. * @return {number}
  31456. * The parsed timescale
  31457. */
  31458. timescale(value) {
  31459. return parseInt(value, 10);
  31460. },
  31461. /**
  31462. * Specifies the presentationTimeOffset.
  31463. *
  31464. * @param {string} value
  31465. * value of the attribute as a string
  31466. *
  31467. * @return {number}
  31468. * The parsed presentationTimeOffset
  31469. */
  31470. presentationTimeOffset(value) {
  31471. return parseInt(value, 10);
  31472. },
  31473. /**
  31474. * Specifies the constant approximate Segment duration
  31475. * NOTE: The <Period> element also contains an @duration attribute. This duration
  31476. * specifies the duration of the Period. This attribute is currently not
  31477. * supported by the rest of the parser, however we still check for it to prevent
  31478. * errors.
  31479. *
  31480. * @param {string} value
  31481. * value of attribute as a string
  31482. * @return {number}
  31483. * The parsed duration
  31484. */
  31485. duration(value) {
  31486. const parsedValue = parseInt(value, 10);
  31487. if (isNaN(parsedValue)) {
  31488. return parseDuration(value);
  31489. }
  31490. return parsedValue;
  31491. },
  31492. /**
  31493. * Specifies the Segment duration, in units of the value of the @timescale.
  31494. *
  31495. * @param {string} value
  31496. * value of attribute as a string
  31497. * @return {number}
  31498. * The parsed duration
  31499. */
  31500. d(value) {
  31501. return parseInt(value, 10);
  31502. },
  31503. /**
  31504. * Specifies the MPD start time, in @timescale units, the first Segment in the series
  31505. * starts relative to the beginning of the Period
  31506. *
  31507. * @param {string} value
  31508. * value of attribute as a string
  31509. * @return {number}
  31510. * The parsed time
  31511. */
  31512. t(value) {
  31513. return parseInt(value, 10);
  31514. },
  31515. /**
  31516. * Specifies the repeat count of the number of following contiguous Segments with the
  31517. * same duration expressed by the value of @d
  31518. *
  31519. * @param {string} value
  31520. * value of attribute as a string
  31521. * @return {number}
  31522. * The parsed number
  31523. */
  31524. r(value) {
  31525. return parseInt(value, 10);
  31526. },
  31527. /**
  31528. * Default parser for all other attributes. Acts as a no-op and just returns the value
  31529. * as a string
  31530. *
  31531. * @param {string} value
  31532. * value of attribute as a string
  31533. * @return {string}
  31534. * Unparsed value
  31535. */
  31536. DEFAULT(value) {
  31537. return value;
  31538. }
  31539. };
  31540. /**
  31541. * Gets all the attributes and values of the provided node, parses attributes with known
  31542. * types, and returns an object with attribute names mapped to values.
  31543. *
  31544. * @param {Node} el
  31545. * The node to parse attributes from
  31546. * @return {Object}
  31547. * Object with all attributes of el parsed
  31548. */
  31549. const parseAttributes = el => {
  31550. if (!(el && el.attributes)) {
  31551. return {};
  31552. }
  31553. return from(el.attributes).reduce((a, e) => {
  31554. const parseFn = parsers[e.name] || parsers.DEFAULT;
  31555. a[e.name] = parseFn(e.value);
  31556. return a;
  31557. }, {});
  31558. };
  31559. const keySystemsMap = {
  31560. 'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b': 'org.w3.clearkey',
  31561. 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed': 'com.widevine.alpha',
  31562. 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95': 'com.microsoft.playready',
  31563. 'urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb': 'com.adobe.primetime'
  31564. };
  31565. /**
  31566. * Builds a list of urls that is the product of the reference urls and BaseURL values
  31567. *
  31568. * @param {string[]} referenceUrls
  31569. * List of reference urls to resolve to
  31570. * @param {Node[]} baseUrlElements
  31571. * List of BaseURL nodes from the mpd
  31572. * @return {string[]}
  31573. * List of resolved urls
  31574. */
  31575. const buildBaseUrls = (referenceUrls, baseUrlElements) => {
  31576. if (!baseUrlElements.length) {
  31577. return referenceUrls;
  31578. }
  31579. return flatten(referenceUrls.map(function (reference) {
  31580. return baseUrlElements.map(function (baseUrlElement) {
  31581. return resolveUrl$1(reference, getContent(baseUrlElement));
  31582. });
  31583. }));
  31584. };
  31585. /**
  31586. * Contains all Segment information for its containing AdaptationSet
  31587. *
  31588. * @typedef {Object} SegmentInformation
  31589. * @property {Object|undefined} template
  31590. * Contains the attributes for the SegmentTemplate node
  31591. * @property {Object[]|undefined} segmentTimeline
  31592. * Contains a list of atrributes for each S node within the SegmentTimeline node
  31593. * @property {Object|undefined} list
  31594. * Contains the attributes for the SegmentList node
  31595. * @property {Object|undefined} base
  31596. * Contains the attributes for the SegmentBase node
  31597. */
  31598. /**
  31599. * Returns all available Segment information contained within the AdaptationSet node
  31600. *
  31601. * @param {Node} adaptationSet
  31602. * The AdaptationSet node to get Segment information from
  31603. * @return {SegmentInformation}
  31604. * The Segment information contained within the provided AdaptationSet
  31605. */
  31606. const getSegmentInformation = adaptationSet => {
  31607. const segmentTemplate = findChildren(adaptationSet, 'SegmentTemplate')[0];
  31608. const segmentList = findChildren(adaptationSet, 'SegmentList')[0];
  31609. const segmentUrls = segmentList && findChildren(segmentList, 'SegmentURL').map(s => merge$1({
  31610. tag: 'SegmentURL'
  31611. }, parseAttributes(s)));
  31612. const segmentBase = findChildren(adaptationSet, 'SegmentBase')[0];
  31613. const segmentTimelineParentNode = segmentList || segmentTemplate;
  31614. const segmentTimeline = segmentTimelineParentNode && findChildren(segmentTimelineParentNode, 'SegmentTimeline')[0];
  31615. const segmentInitializationParentNode = segmentList || segmentBase || segmentTemplate;
  31616. const segmentInitialization = segmentInitializationParentNode && findChildren(segmentInitializationParentNode, 'Initialization')[0]; // SegmentTemplate is handled slightly differently, since it can have both
  31617. // @initialization and an <Initialization> node. @initialization can be templated,
  31618. // while the node can have a url and range specified. If the <SegmentTemplate> has
  31619. // both @initialization and an <Initialization> subelement we opt to override with
  31620. // the node, as this interaction is not defined in the spec.
  31621. const template = segmentTemplate && parseAttributes(segmentTemplate);
  31622. if (template && segmentInitialization) {
  31623. template.initialization = segmentInitialization && parseAttributes(segmentInitialization);
  31624. } else if (template && template.initialization) {
  31625. // If it is @initialization we convert it to an object since this is the format that
  31626. // later functions will rely on for the initialization segment. This is only valid
  31627. // for <SegmentTemplate>
  31628. template.initialization = {
  31629. sourceURL: template.initialization
  31630. };
  31631. }
  31632. const segmentInfo = {
  31633. template,
  31634. segmentTimeline: segmentTimeline && findChildren(segmentTimeline, 'S').map(s => parseAttributes(s)),
  31635. list: segmentList && merge$1(parseAttributes(segmentList), {
  31636. segmentUrls,
  31637. initialization: parseAttributes(segmentInitialization)
  31638. }),
  31639. base: segmentBase && merge$1(parseAttributes(segmentBase), {
  31640. initialization: parseAttributes(segmentInitialization)
  31641. })
  31642. };
  31643. Object.keys(segmentInfo).forEach(key => {
  31644. if (!segmentInfo[key]) {
  31645. delete segmentInfo[key];
  31646. }
  31647. });
  31648. return segmentInfo;
  31649. };
  31650. /**
  31651. * Contains Segment information and attributes needed to construct a Playlist object
  31652. * from a Representation
  31653. *
  31654. * @typedef {Object} RepresentationInformation
  31655. * @property {SegmentInformation} segmentInfo
  31656. * Segment information for this Representation
  31657. * @property {Object} attributes
  31658. * Inherited attributes for this Representation
  31659. */
  31660. /**
  31661. * Maps a Representation node to an object containing Segment information and attributes
  31662. *
  31663. * @name inheritBaseUrlsCallback
  31664. * @function
  31665. * @param {Node} representation
  31666. * Representation node from the mpd
  31667. * @return {RepresentationInformation}
  31668. * Representation information needed to construct a Playlist object
  31669. */
  31670. /**
  31671. * Returns a callback for Array.prototype.map for mapping Representation nodes to
  31672. * Segment information and attributes using inherited BaseURL nodes.
  31673. *
  31674. * @param {Object} adaptationSetAttributes
  31675. * Contains attributes inherited by the AdaptationSet
  31676. * @param {string[]} adaptationSetBaseUrls
  31677. * Contains list of resolved base urls inherited by the AdaptationSet
  31678. * @param {SegmentInformation} adaptationSetSegmentInfo
  31679. * Contains Segment information for the AdaptationSet
  31680. * @return {inheritBaseUrlsCallback}
  31681. * Callback map function
  31682. */
  31683. const inheritBaseUrls = (adaptationSetAttributes, adaptationSetBaseUrls, adaptationSetSegmentInfo) => representation => {
  31684. const repBaseUrlElements = findChildren(representation, 'BaseURL');
  31685. const repBaseUrls = buildBaseUrls(adaptationSetBaseUrls, repBaseUrlElements);
  31686. const attributes = merge$1(adaptationSetAttributes, parseAttributes(representation));
  31687. const representationSegmentInfo = getSegmentInformation(representation);
  31688. return repBaseUrls.map(baseUrl => {
  31689. return {
  31690. segmentInfo: merge$1(adaptationSetSegmentInfo, representationSegmentInfo),
  31691. attributes: merge$1(attributes, {
  31692. baseUrl
  31693. })
  31694. };
  31695. });
  31696. };
  31697. /**
  31698. * Tranforms a series of content protection nodes to
  31699. * an object containing pssh data by key system
  31700. *
  31701. * @param {Node[]} contentProtectionNodes
  31702. * Content protection nodes
  31703. * @return {Object}
  31704. * Object containing pssh data by key system
  31705. */
  31706. const generateKeySystemInformation = contentProtectionNodes => {
  31707. return contentProtectionNodes.reduce((acc, node) => {
  31708. const attributes = parseAttributes(node); // Although it could be argued that according to the UUID RFC spec the UUID string (a-f chars) should be generated
  31709. // as a lowercase string it also mentions it should be treated as case-insensitive on input. Since the key system
  31710. // UUIDs in the keySystemsMap are hardcoded as lowercase in the codebase there isn't any reason not to do
  31711. // .toLowerCase() on the input UUID string from the manifest (at least I could not think of one).
  31712. if (attributes.schemeIdUri) {
  31713. attributes.schemeIdUri = attributes.schemeIdUri.toLowerCase();
  31714. }
  31715. const keySystem = keySystemsMap[attributes.schemeIdUri];
  31716. if (keySystem) {
  31717. acc[keySystem] = {
  31718. attributes
  31719. };
  31720. const psshNode = findChildren(node, 'cenc:pssh')[0];
  31721. if (psshNode) {
  31722. const pssh = getContent(psshNode);
  31723. acc[keySystem].pssh = pssh && decodeB64ToUint8Array(pssh);
  31724. }
  31725. }
  31726. return acc;
  31727. }, {});
  31728. }; // defined in ANSI_SCTE 214-1 2016
  31729. const parseCaptionServiceMetadata = service => {
  31730. // 608 captions
  31731. if (service.schemeIdUri === 'urn:scte:dash:cc:cea-608:2015') {
  31732. const values = typeof service.value !== 'string' ? [] : service.value.split(';');
  31733. return values.map(value => {
  31734. let channel;
  31735. let language; // default language to value
  31736. language = value;
  31737. if (/^CC\d=/.test(value)) {
  31738. [channel, language] = value.split('=');
  31739. } else if (/^CC\d$/.test(value)) {
  31740. channel = value;
  31741. }
  31742. return {
  31743. channel,
  31744. language
  31745. };
  31746. });
  31747. } else if (service.schemeIdUri === 'urn:scte:dash:cc:cea-708:2015') {
  31748. const values = typeof service.value !== 'string' ? [] : service.value.split(';');
  31749. return values.map(value => {
  31750. const flags = {
  31751. // service or channel number 1-63
  31752. 'channel': undefined,
  31753. // language is a 3ALPHA per ISO 639.2/B
  31754. // field is required
  31755. 'language': undefined,
  31756. // BIT 1/0 or ?
  31757. // default value is 1, meaning 16:9 aspect ratio, 0 is 4:3, ? is unknown
  31758. 'aspectRatio': 1,
  31759. // BIT 1/0
  31760. // easy reader flag indicated the text is tailed to the needs of beginning readers
  31761. // default 0, or off
  31762. 'easyReader': 0,
  31763. // BIT 1/0
  31764. // If 3d metadata is present (CEA-708.1) then 1
  31765. // default 0
  31766. '3D': 0
  31767. };
  31768. if (/=/.test(value)) {
  31769. const [channel, opts = ''] = value.split('=');
  31770. flags.channel = channel;
  31771. flags.language = value;
  31772. opts.split(',').forEach(opt => {
  31773. const [name, val] = opt.split(':');
  31774. if (name === 'lang') {
  31775. flags.language = val; // er for easyReadery
  31776. } else if (name === 'er') {
  31777. flags.easyReader = Number(val); // war for wide aspect ratio
  31778. } else if (name === 'war') {
  31779. flags.aspectRatio = Number(val);
  31780. } else if (name === '3D') {
  31781. flags['3D'] = Number(val);
  31782. }
  31783. });
  31784. } else {
  31785. flags.language = value;
  31786. }
  31787. if (flags.channel) {
  31788. flags.channel = 'SERVICE' + flags.channel;
  31789. }
  31790. return flags;
  31791. });
  31792. }
  31793. };
  31794. /**
  31795. * Maps an AdaptationSet node to a list of Representation information objects
  31796. *
  31797. * @name toRepresentationsCallback
  31798. * @function
  31799. * @param {Node} adaptationSet
  31800. * AdaptationSet node from the mpd
  31801. * @return {RepresentationInformation[]}
  31802. * List of objects containing Representaion information
  31803. */
  31804. /**
  31805. * Returns a callback for Array.prototype.map for mapping AdaptationSet nodes to a list of
  31806. * Representation information objects
  31807. *
  31808. * @param {Object} periodAttributes
  31809. * Contains attributes inherited by the Period
  31810. * @param {string[]} periodBaseUrls
  31811. * Contains list of resolved base urls inherited by the Period
  31812. * @param {string[]} periodSegmentInfo
  31813. * Contains Segment Information at the period level
  31814. * @return {toRepresentationsCallback}
  31815. * Callback map function
  31816. */
  31817. const toRepresentations = (periodAttributes, periodBaseUrls, periodSegmentInfo) => adaptationSet => {
  31818. const adaptationSetAttributes = parseAttributes(adaptationSet);
  31819. const adaptationSetBaseUrls = buildBaseUrls(periodBaseUrls, findChildren(adaptationSet, 'BaseURL'));
  31820. const role = findChildren(adaptationSet, 'Role')[0];
  31821. const roleAttributes = {
  31822. role: parseAttributes(role)
  31823. };
  31824. let attrs = merge$1(periodAttributes, adaptationSetAttributes, roleAttributes);
  31825. const accessibility = findChildren(adaptationSet, 'Accessibility')[0];
  31826. const captionServices = parseCaptionServiceMetadata(parseAttributes(accessibility));
  31827. if (captionServices) {
  31828. attrs = merge$1(attrs, {
  31829. captionServices
  31830. });
  31831. }
  31832. const label = findChildren(adaptationSet, 'Label')[0];
  31833. if (label && label.childNodes.length) {
  31834. const labelVal = label.childNodes[0].nodeValue.trim();
  31835. attrs = merge$1(attrs, {
  31836. label: labelVal
  31837. });
  31838. }
  31839. const contentProtection = generateKeySystemInformation(findChildren(adaptationSet, 'ContentProtection'));
  31840. if (Object.keys(contentProtection).length) {
  31841. attrs = merge$1(attrs, {
  31842. contentProtection
  31843. });
  31844. }
  31845. const segmentInfo = getSegmentInformation(adaptationSet);
  31846. const representations = findChildren(adaptationSet, 'Representation');
  31847. const adaptationSetSegmentInfo = merge$1(periodSegmentInfo, segmentInfo);
  31848. return flatten(representations.map(inheritBaseUrls(attrs, adaptationSetBaseUrls, adaptationSetSegmentInfo)));
  31849. };
  31850. /**
  31851. * Contains all period information for mapping nodes onto adaptation sets.
  31852. *
  31853. * @typedef {Object} PeriodInformation
  31854. * @property {Node} period.node
  31855. * Period node from the mpd
  31856. * @property {Object} period.attributes
  31857. * Parsed period attributes from node plus any added
  31858. */
  31859. /**
  31860. * Maps a PeriodInformation object to a list of Representation information objects for all
  31861. * AdaptationSet nodes contained within the Period.
  31862. *
  31863. * @name toAdaptationSetsCallback
  31864. * @function
  31865. * @param {PeriodInformation} period
  31866. * Period object containing necessary period information
  31867. * @param {number} periodStart
  31868. * Start time of the Period within the mpd
  31869. * @return {RepresentationInformation[]}
  31870. * List of objects containing Representaion information
  31871. */
  31872. /**
  31873. * Returns a callback for Array.prototype.map for mapping Period nodes to a list of
  31874. * Representation information objects
  31875. *
  31876. * @param {Object} mpdAttributes
  31877. * Contains attributes inherited by the mpd
  31878. * @param {string[]} mpdBaseUrls
  31879. * Contains list of resolved base urls inherited by the mpd
  31880. * @return {toAdaptationSetsCallback}
  31881. * Callback map function
  31882. */
  31883. const toAdaptationSets = (mpdAttributes, mpdBaseUrls) => (period, index) => {
  31884. const periodBaseUrls = buildBaseUrls(mpdBaseUrls, findChildren(period.node, 'BaseURL'));
  31885. const periodAttributes = merge$1(mpdAttributes, {
  31886. periodStart: period.attributes.start
  31887. });
  31888. if (typeof period.attributes.duration === 'number') {
  31889. periodAttributes.periodDuration = period.attributes.duration;
  31890. }
  31891. const adaptationSets = findChildren(period.node, 'AdaptationSet');
  31892. const periodSegmentInfo = getSegmentInformation(period.node);
  31893. return flatten(adaptationSets.map(toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo)));
  31894. };
  31895. /**
  31896. * Gets Period@start property for a given period.
  31897. *
  31898. * @param {Object} options
  31899. * Options object
  31900. * @param {Object} options.attributes
  31901. * Period attributes
  31902. * @param {Object} [options.priorPeriodAttributes]
  31903. * Prior period attributes (if prior period is available)
  31904. * @param {string} options.mpdType
  31905. * The MPD@type these periods came from
  31906. * @return {number|null}
  31907. * The period start, or null if it's an early available period or error
  31908. */
  31909. const getPeriodStart = ({
  31910. attributes,
  31911. priorPeriodAttributes,
  31912. mpdType
  31913. }) => {
  31914. // Summary of period start time calculation from DASH spec section 5.3.2.1
  31915. //
  31916. // A period's start is the first period's start + time elapsed after playing all
  31917. // prior periods to this one. Periods continue one after the other in time (without
  31918. // gaps) until the end of the presentation.
  31919. //
  31920. // The value of Period@start should be:
  31921. // 1. if Period@start is present: value of Period@start
  31922. // 2. if previous period exists and it has @duration: previous Period@start +
  31923. // previous Period@duration
  31924. // 3. if this is first period and MPD@type is 'static': 0
  31925. // 4. in all other cases, consider the period an "early available period" (note: not
  31926. // currently supported)
  31927. // (1)
  31928. if (typeof attributes.start === 'number') {
  31929. return attributes.start;
  31930. } // (2)
  31931. if (priorPeriodAttributes && typeof priorPeriodAttributes.start === 'number' && typeof priorPeriodAttributes.duration === 'number') {
  31932. return priorPeriodAttributes.start + priorPeriodAttributes.duration;
  31933. } // (3)
  31934. if (!priorPeriodAttributes && mpdType === 'static') {
  31935. return 0;
  31936. } // (4)
  31937. // There is currently no logic for calculating the Period@start value if there is
  31938. // no Period@start or prior Period@start and Period@duration available. This is not made
  31939. // explicit by the DASH interop guidelines or the DASH spec, however, since there's
  31940. // nothing about any other resolution strategies, it's implied. Thus, this case should
  31941. // be considered an early available period, or error, and null should suffice for both
  31942. // of those cases.
  31943. return null;
  31944. };
  31945. /**
  31946. * Traverses the mpd xml tree to generate a list of Representation information objects
  31947. * that have inherited attributes from parent nodes
  31948. *
  31949. * @param {Node} mpd
  31950. * The root node of the mpd
  31951. * @param {Object} options
  31952. * Available options for inheritAttributes
  31953. * @param {string} options.manifestUri
  31954. * The uri source of the mpd
  31955. * @param {number} options.NOW
  31956. * Current time per DASH IOP. Default is current time in ms since epoch
  31957. * @param {number} options.clientOffset
  31958. * Client time difference from NOW (in milliseconds)
  31959. * @return {RepresentationInformation[]}
  31960. * List of objects containing Representation information
  31961. */
  31962. const inheritAttributes = (mpd, options = {}) => {
  31963. const {
  31964. manifestUri = '',
  31965. NOW = Date.now(),
  31966. clientOffset = 0
  31967. } = options;
  31968. const periodNodes = findChildren(mpd, 'Period');
  31969. if (!periodNodes.length) {
  31970. throw new Error(errors.INVALID_NUMBER_OF_PERIOD);
  31971. }
  31972. const locations = findChildren(mpd, 'Location');
  31973. const mpdAttributes = parseAttributes(mpd);
  31974. const mpdBaseUrls = buildBaseUrls([manifestUri], findChildren(mpd, 'BaseURL')); // See DASH spec section 5.3.1.2, Semantics of MPD element. Default type to 'static'.
  31975. mpdAttributes.type = mpdAttributes.type || 'static';
  31976. mpdAttributes.sourceDuration = mpdAttributes.mediaPresentationDuration || 0;
  31977. mpdAttributes.NOW = NOW;
  31978. mpdAttributes.clientOffset = clientOffset;
  31979. if (locations.length) {
  31980. mpdAttributes.locations = locations.map(getContent);
  31981. }
  31982. const periods = []; // Since toAdaptationSets acts on individual periods right now, the simplest approach to
  31983. // adding properties that require looking at prior periods is to parse attributes and add
  31984. // missing ones before toAdaptationSets is called. If more such properties are added, it
  31985. // may be better to refactor toAdaptationSets.
  31986. periodNodes.forEach((node, index) => {
  31987. const attributes = parseAttributes(node); // Use the last modified prior period, as it may contain added information necessary
  31988. // for this period.
  31989. const priorPeriod = periods[index - 1];
  31990. attributes.start = getPeriodStart({
  31991. attributes,
  31992. priorPeriodAttributes: priorPeriod ? priorPeriod.attributes : null,
  31993. mpdType: mpdAttributes.type
  31994. });
  31995. periods.push({
  31996. node,
  31997. attributes
  31998. });
  31999. });
  32000. return {
  32001. locations: mpdAttributes.locations,
  32002. representationInfo: flatten(periods.map(toAdaptationSets(mpdAttributes, mpdBaseUrls)))
  32003. };
  32004. };
  32005. const stringToMpdXml = manifestString => {
  32006. if (manifestString === '') {
  32007. throw new Error(errors.DASH_EMPTY_MANIFEST);
  32008. }
  32009. const parser = new DOMParser();
  32010. let xml;
  32011. let mpd;
  32012. try {
  32013. xml = parser.parseFromString(manifestString, 'application/xml');
  32014. mpd = xml && xml.documentElement.tagName === 'MPD' ? xml.documentElement : null;
  32015. } catch (e) {// ie 11 throwsw on invalid xml
  32016. }
  32017. if (!mpd || mpd && mpd.getElementsByTagName('parsererror').length > 0) {
  32018. throw new Error(errors.DASH_INVALID_XML);
  32019. }
  32020. return mpd;
  32021. };
  32022. /**
  32023. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  32024. *
  32025. * @param {string} mpd
  32026. * XML string of the MPD manifest
  32027. * @return {Object|null}
  32028. * Attributes of UTCTiming node specified in the manifest. Null if none found
  32029. */
  32030. const parseUTCTimingScheme = mpd => {
  32031. const UTCTimingNode = findChildren(mpd, 'UTCTiming')[0];
  32032. if (!UTCTimingNode) {
  32033. return null;
  32034. }
  32035. const attributes = parseAttributes(UTCTimingNode);
  32036. switch (attributes.schemeIdUri) {
  32037. case 'urn:mpeg:dash:utc:http-head:2014':
  32038. case 'urn:mpeg:dash:utc:http-head:2012':
  32039. attributes.method = 'HEAD';
  32040. break;
  32041. case 'urn:mpeg:dash:utc:http-xsdate:2014':
  32042. case 'urn:mpeg:dash:utc:http-iso:2014':
  32043. case 'urn:mpeg:dash:utc:http-xsdate:2012':
  32044. case 'urn:mpeg:dash:utc:http-iso:2012':
  32045. attributes.method = 'GET';
  32046. break;
  32047. case 'urn:mpeg:dash:utc:direct:2014':
  32048. case 'urn:mpeg:dash:utc:direct:2012':
  32049. attributes.method = 'DIRECT';
  32050. attributes.value = Date.parse(attributes.value);
  32051. break;
  32052. case 'urn:mpeg:dash:utc:http-ntp:2014':
  32053. case 'urn:mpeg:dash:utc:ntp:2014':
  32054. case 'urn:mpeg:dash:utc:sntp:2014':
  32055. default:
  32056. throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME);
  32057. }
  32058. return attributes;
  32059. };
  32060. /*
  32061. * Given a DASH manifest string and options, parses the DASH manifest into an object in the
  32062. * form outputed by m3u8-parser and accepted by videojs/http-streaming.
  32063. *
  32064. * For live DASH manifests, if `previousManifest` is provided in options, then the newly
  32065. * parsed DASH manifest will have its media sequence and discontinuity sequence values
  32066. * updated to reflect its position relative to the prior manifest.
  32067. *
  32068. * @param {string} manifestString - the DASH manifest as a string
  32069. * @param {options} [options] - any options
  32070. *
  32071. * @return {Object} the manifest object
  32072. */
  32073. const parse = (manifestString, options = {}) => {
  32074. const parsedManifestInfo = inheritAttributes(stringToMpdXml(manifestString), options);
  32075. const playlists = toPlaylists(parsedManifestInfo.representationInfo);
  32076. return toM3u8({
  32077. dashPlaylists: playlists,
  32078. locations: parsedManifestInfo.locations,
  32079. sidxMapping: options.sidxMapping,
  32080. previousManifest: options.previousManifest
  32081. });
  32082. };
  32083. /**
  32084. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  32085. *
  32086. * @param {string} manifestString
  32087. * XML string of the MPD manifest
  32088. * @return {Object|null}
  32089. * Attributes of UTCTiming node specified in the manifest. Null if none found
  32090. */
  32091. const parseUTCTiming = manifestString => parseUTCTimingScheme(stringToMpdXml(manifestString));
  32092. var MAX_UINT32 = Math.pow(2, 32);
  32093. var getUint64$1 = function (uint8) {
  32094. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  32095. var value;
  32096. if (dv.getBigUint64) {
  32097. value = dv.getBigUint64(0);
  32098. if (value < Number.MAX_SAFE_INTEGER) {
  32099. return Number(value);
  32100. }
  32101. return value;
  32102. }
  32103. return dv.getUint32(0) * MAX_UINT32 + dv.getUint32(4);
  32104. };
  32105. var numbers = {
  32106. getUint64: getUint64$1,
  32107. MAX_UINT32: MAX_UINT32
  32108. };
  32109. var getUint64 = numbers.getUint64;
  32110. var parseSidx = function (data) {
  32111. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  32112. result = {
  32113. version: data[0],
  32114. flags: new Uint8Array(data.subarray(1, 4)),
  32115. references: [],
  32116. referenceId: view.getUint32(4),
  32117. timescale: view.getUint32(8)
  32118. },
  32119. i = 12;
  32120. if (result.version === 0) {
  32121. result.earliestPresentationTime = view.getUint32(i);
  32122. result.firstOffset = view.getUint32(i + 4);
  32123. i += 8;
  32124. } else {
  32125. // read 64 bits
  32126. result.earliestPresentationTime = getUint64(data.subarray(i));
  32127. result.firstOffset = getUint64(data.subarray(i + 8));
  32128. i += 16;
  32129. }
  32130. i += 2; // reserved
  32131. var referenceCount = view.getUint16(i);
  32132. i += 2; // start of references
  32133. for (; referenceCount > 0; i += 12, referenceCount--) {
  32134. result.references.push({
  32135. referenceType: (data[i] & 0x80) >>> 7,
  32136. referencedSize: view.getUint32(i) & 0x7FFFFFFF,
  32137. subsegmentDuration: view.getUint32(i + 4),
  32138. startsWithSap: !!(data[i + 8] & 0x80),
  32139. sapType: (data[i + 8] & 0x70) >>> 4,
  32140. sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
  32141. });
  32142. }
  32143. return result;
  32144. };
  32145. var parseSidx_1 = parseSidx;
  32146. var ID3 = toUint8([0x49, 0x44, 0x33]);
  32147. var getId3Size = function getId3Size(bytes, offset) {
  32148. if (offset === void 0) {
  32149. offset = 0;
  32150. }
  32151. bytes = toUint8(bytes);
  32152. var flags = bytes[offset + 5];
  32153. var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
  32154. var footerPresent = (flags & 16) >> 4;
  32155. if (footerPresent) {
  32156. return returnSize + 20;
  32157. }
  32158. return returnSize + 10;
  32159. };
  32160. var getId3Offset = function getId3Offset(bytes, offset) {
  32161. if (offset === void 0) {
  32162. offset = 0;
  32163. }
  32164. bytes = toUint8(bytes);
  32165. if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {
  32166. offset: offset
  32167. })) {
  32168. return offset;
  32169. }
  32170. offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files
  32171. // have multiple ID3 tag sections even though
  32172. // they should not.
  32173. return getId3Offset(bytes, offset);
  32174. };
  32175. var normalizePath$1 = function normalizePath(path) {
  32176. if (typeof path === 'string') {
  32177. return stringToBytes(path);
  32178. }
  32179. if (typeof path === 'number') {
  32180. return path;
  32181. }
  32182. return path;
  32183. };
  32184. var normalizePaths$1 = function normalizePaths(paths) {
  32185. if (!Array.isArray(paths)) {
  32186. return [normalizePath$1(paths)];
  32187. }
  32188. return paths.map(function (p) {
  32189. return normalizePath$1(p);
  32190. });
  32191. };
  32192. /**
  32193. * find any number of boxes by name given a path to it in an iso bmff
  32194. * such as mp4.
  32195. *
  32196. * @param {TypedArray} bytes
  32197. * bytes for the iso bmff to search for boxes in
  32198. *
  32199. * @param {Uint8Array[]|string[]|string|Uint8Array} name
  32200. * An array of paths or a single path representing the name
  32201. * of boxes to search through in bytes. Paths may be
  32202. * uint8 (character codes) or strings.
  32203. *
  32204. * @param {boolean} [complete=false]
  32205. * Should we search only for complete boxes on the final path.
  32206. * This is very useful when you do not want to get back partial boxes
  32207. * in the case of streaming files.
  32208. *
  32209. * @return {Uint8Array[]}
  32210. * An array of the end paths that we found.
  32211. */
  32212. var findBox = function findBox(bytes, paths, complete) {
  32213. if (complete === void 0) {
  32214. complete = false;
  32215. }
  32216. paths = normalizePaths$1(paths);
  32217. bytes = toUint8(bytes);
  32218. var results = [];
  32219. if (!paths.length) {
  32220. // short-circuit the search for empty paths
  32221. return results;
  32222. }
  32223. var i = 0;
  32224. while (i < bytes.length) {
  32225. var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
  32226. var type = bytes.subarray(i + 4, i + 8); // invalid box format.
  32227. if (size === 0) {
  32228. break;
  32229. }
  32230. var end = i + size;
  32231. if (end > bytes.length) {
  32232. // this box is bigger than the number of bytes we have
  32233. // and complete is set, we cannot find any more boxes.
  32234. if (complete) {
  32235. break;
  32236. }
  32237. end = bytes.length;
  32238. }
  32239. var data = bytes.subarray(i + 8, end);
  32240. if (bytesMatch(type, paths[0])) {
  32241. if (paths.length === 1) {
  32242. // this is the end of the path and we've found the box we were
  32243. // looking for
  32244. results.push(data);
  32245. } else {
  32246. // recursively search for the next box along the path
  32247. results.push.apply(results, findBox(data, paths.slice(1), complete));
  32248. }
  32249. }
  32250. i = end;
  32251. } // we've finished searching all of bytes
  32252. return results;
  32253. };
  32254. // https://matroska-org.github.io/libebml/specs.html
  32255. // https://www.matroska.org/technical/elements.html
  32256. // https://www.webmproject.org/docs/container/
  32257. var EBML_TAGS = {
  32258. EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),
  32259. DocType: toUint8([0x42, 0x82]),
  32260. Segment: toUint8([0x18, 0x53, 0x80, 0x67]),
  32261. SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),
  32262. Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),
  32263. Track: toUint8([0xAE]),
  32264. TrackNumber: toUint8([0xd7]),
  32265. DefaultDuration: toUint8([0x23, 0xe3, 0x83]),
  32266. TrackEntry: toUint8([0xAE]),
  32267. TrackType: toUint8([0x83]),
  32268. FlagDefault: toUint8([0x88]),
  32269. CodecID: toUint8([0x86]),
  32270. CodecPrivate: toUint8([0x63, 0xA2]),
  32271. VideoTrack: toUint8([0xe0]),
  32272. AudioTrack: toUint8([0xe1]),
  32273. // Not used yet, but will be used for live webm/mkv
  32274. // see https://www.matroska.org/technical/basics.html#block-structure
  32275. // see https://www.matroska.org/technical/basics.html#simpleblock-structure
  32276. Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),
  32277. Timestamp: toUint8([0xE7]),
  32278. TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),
  32279. BlockGroup: toUint8([0xA0]),
  32280. BlockDuration: toUint8([0x9B]),
  32281. Block: toUint8([0xA1]),
  32282. SimpleBlock: toUint8([0xA3])
  32283. };
  32284. /**
  32285. * This is a simple table to determine the length
  32286. * of things in ebml. The length is one based (starts at 1,
  32287. * rather than zero) and for every zero bit before a one bit
  32288. * we add one to length. We also need this table because in some
  32289. * case we have to xor all the length bits from another value.
  32290. */
  32291. var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
  32292. var getLength = function getLength(byte) {
  32293. var len = 1;
  32294. for (var i = 0; i < LENGTH_TABLE.length; i++) {
  32295. if (byte & LENGTH_TABLE[i]) {
  32296. break;
  32297. }
  32298. len++;
  32299. }
  32300. return len;
  32301. }; // length in ebml is stored in the first 4 to 8 bits
  32302. // of the first byte. 4 for the id length and 8 for the
  32303. // data size length. Length is measured by converting the number to binary
  32304. // then 1 + the number of zeros before a 1 is encountered starting
  32305. // from the left.
  32306. var getvint = function getvint(bytes, offset, removeLength, signed) {
  32307. if (removeLength === void 0) {
  32308. removeLength = true;
  32309. }
  32310. if (signed === void 0) {
  32311. signed = false;
  32312. }
  32313. var length = getLength(bytes[offset]);
  32314. var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes
  32315. // as they will be modified below to remove the dataSizeLen bits and we do not
  32316. // want to modify the original data. normally we could just call slice on
  32317. // uint8array but ie 11 does not support that...
  32318. if (removeLength) {
  32319. valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
  32320. valueBytes[0] ^= LENGTH_TABLE[length - 1];
  32321. }
  32322. return {
  32323. length: length,
  32324. value: bytesToNumber(valueBytes, {
  32325. signed: signed
  32326. }),
  32327. bytes: valueBytes
  32328. };
  32329. };
  32330. var normalizePath = function normalizePath(path) {
  32331. if (typeof path === 'string') {
  32332. return path.match(/.{1,2}/g).map(function (p) {
  32333. return normalizePath(p);
  32334. });
  32335. }
  32336. if (typeof path === 'number') {
  32337. return numberToBytes(path);
  32338. }
  32339. return path;
  32340. };
  32341. var normalizePaths = function normalizePaths(paths) {
  32342. if (!Array.isArray(paths)) {
  32343. return [normalizePath(paths)];
  32344. }
  32345. return paths.map(function (p) {
  32346. return normalizePath(p);
  32347. });
  32348. };
  32349. var getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {
  32350. if (offset >= bytes.length) {
  32351. return bytes.length;
  32352. }
  32353. var innerid = getvint(bytes, offset, false);
  32354. if (bytesMatch(id.bytes, innerid.bytes)) {
  32355. return offset;
  32356. }
  32357. var dataHeader = getvint(bytes, offset + innerid.length);
  32358. return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
  32359. };
  32360. /**
  32361. * Notes on the EBLM format.
  32362. *
  32363. * EBLM uses "vints" tags. Every vint tag contains
  32364. * two parts
  32365. *
  32366. * 1. The length from the first byte. You get this by
  32367. * converting the byte to binary and counting the zeros
  32368. * before a 1. Then you add 1 to that. Examples
  32369. * 00011111 = length 4 because there are 3 zeros before a 1.
  32370. * 00100000 = length 3 because there are 2 zeros before a 1.
  32371. * 00000011 = length 7 because there are 6 zeros before a 1.
  32372. *
  32373. * 2. The bits used for length are removed from the first byte
  32374. * Then all the bytes are merged into a value. NOTE: this
  32375. * is not the case for id ebml tags as there id includes
  32376. * length bits.
  32377. *
  32378. */
  32379. var findEbml = function findEbml(bytes, paths) {
  32380. paths = normalizePaths(paths);
  32381. bytes = toUint8(bytes);
  32382. var results = [];
  32383. if (!paths.length) {
  32384. return results;
  32385. }
  32386. var i = 0;
  32387. while (i < bytes.length) {
  32388. var id = getvint(bytes, i, false);
  32389. var dataHeader = getvint(bytes, i + id.length);
  32390. var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream
  32391. if (dataHeader.value === 0x7f) {
  32392. dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
  32393. if (dataHeader.value !== bytes.length) {
  32394. dataHeader.value -= dataStart;
  32395. }
  32396. }
  32397. var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
  32398. var data = bytes.subarray(dataStart, dataEnd);
  32399. if (bytesMatch(paths[0], id.bytes)) {
  32400. if (paths.length === 1) {
  32401. // this is the end of the paths and we've found the tag we were
  32402. // looking for
  32403. results.push(data);
  32404. } else {
  32405. // recursively search for the next tag inside of the data
  32406. // of this one
  32407. results = results.concat(findEbml(data, paths.slice(1)));
  32408. }
  32409. }
  32410. var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it
  32411. i += totalLength;
  32412. }
  32413. return results;
  32414. }; // see https://www.matroska.org/technical/basics.html#block-structure
  32415. var NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);
  32416. var NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);
  32417. var EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);
  32418. /**
  32419. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  32420. * Sequence Payload"
  32421. *
  32422. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  32423. * unit
  32424. * @return {Uint8Array} the RBSP without any Emulation
  32425. * Prevention Bytes
  32426. */
  32427. var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {
  32428. var positions = [];
  32429. var i = 1; // Find all `Emulation Prevention Bytes`
  32430. while (i < bytes.length - 2) {
  32431. if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
  32432. positions.push(i + 2);
  32433. i++;
  32434. }
  32435. i++;
  32436. } // If no Emulation Prevention Bytes were found just return the original
  32437. // array
  32438. if (positions.length === 0) {
  32439. return bytes;
  32440. } // Create a new array to hold the NAL unit data
  32441. var newLength = bytes.length - positions.length;
  32442. var newData = new Uint8Array(newLength);
  32443. var sourceIndex = 0;
  32444. for (i = 0; i < newLength; sourceIndex++, i++) {
  32445. if (sourceIndex === positions[0]) {
  32446. // Skip this byte
  32447. sourceIndex++; // Remove this position index
  32448. positions.shift();
  32449. }
  32450. newData[i] = bytes[sourceIndex];
  32451. }
  32452. return newData;
  32453. };
  32454. var findNal = function findNal(bytes, dataType, types, nalLimit) {
  32455. if (nalLimit === void 0) {
  32456. nalLimit = Infinity;
  32457. }
  32458. bytes = toUint8(bytes);
  32459. types = [].concat(types);
  32460. var i = 0;
  32461. var nalStart;
  32462. var nalsFound = 0; // keep searching until:
  32463. // we reach the end of bytes
  32464. // we reach the maximum number of nals they want to seach
  32465. // NOTE: that we disregard nalLimit when we have found the start
  32466. // of the nal we want so that we can find the end of the nal we want.
  32467. while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
  32468. var nalOffset = void 0;
  32469. if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
  32470. nalOffset = 4;
  32471. } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
  32472. nalOffset = 3;
  32473. } // we are unsynced,
  32474. // find the next nal unit
  32475. if (!nalOffset) {
  32476. i++;
  32477. continue;
  32478. }
  32479. nalsFound++;
  32480. if (nalStart) {
  32481. return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
  32482. }
  32483. var nalType = void 0;
  32484. if (dataType === 'h264') {
  32485. nalType = bytes[i + nalOffset] & 0x1f;
  32486. } else if (dataType === 'h265') {
  32487. nalType = bytes[i + nalOffset] >> 1 & 0x3f;
  32488. }
  32489. if (types.indexOf(nalType) !== -1) {
  32490. nalStart = i + nalOffset;
  32491. } // nal header is 1 length for h264, and 2 for h265
  32492. i += nalOffset + (dataType === 'h264' ? 1 : 2);
  32493. }
  32494. return bytes.subarray(0, 0);
  32495. };
  32496. var findH264Nal = function findH264Nal(bytes, type, nalLimit) {
  32497. return findNal(bytes, 'h264', type, nalLimit);
  32498. };
  32499. var findH265Nal = function findH265Nal(bytes, type, nalLimit) {
  32500. return findNal(bytes, 'h265', type, nalLimit);
  32501. };
  32502. var CONSTANTS = {
  32503. // "webm" string literal in hex
  32504. 'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),
  32505. // "matroska" string literal in hex
  32506. 'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
  32507. // "fLaC" string literal in hex
  32508. 'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),
  32509. // "OggS" string literal in hex
  32510. 'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),
  32511. // ac-3 sync byte, also works for ec-3 as that is simply a codec
  32512. // of ac-3
  32513. 'ac3': toUint8([0x0b, 0x77]),
  32514. // "RIFF" string literal in hex used for wav and avi
  32515. 'riff': toUint8([0x52, 0x49, 0x46, 0x46]),
  32516. // "AVI" string literal in hex
  32517. 'avi': toUint8([0x41, 0x56, 0x49]),
  32518. // "WAVE" string literal in hex
  32519. 'wav': toUint8([0x57, 0x41, 0x56, 0x45]),
  32520. // "ftyp3g" string literal in hex
  32521. '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
  32522. // "ftyp" string literal in hex
  32523. 'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),
  32524. // "styp" string literal in hex
  32525. 'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),
  32526. // "ftypqt" string literal in hex
  32527. 'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74]),
  32528. // moov string literal in hex
  32529. 'moov': toUint8([0x6D, 0x6F, 0x6F, 0x76]),
  32530. // moof string literal in hex
  32531. 'moof': toUint8([0x6D, 0x6F, 0x6F, 0x66])
  32532. };
  32533. var _isLikely = {
  32534. aac: function aac(bytes) {
  32535. var offset = getId3Offset(bytes);
  32536. return bytesMatch(bytes, [0xFF, 0x10], {
  32537. offset: offset,
  32538. mask: [0xFF, 0x16]
  32539. });
  32540. },
  32541. mp3: function mp3(bytes) {
  32542. var offset = getId3Offset(bytes);
  32543. return bytesMatch(bytes, [0xFF, 0x02], {
  32544. offset: offset,
  32545. mask: [0xFF, 0x06]
  32546. });
  32547. },
  32548. webm: function webm(bytes) {
  32549. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm
  32550. return bytesMatch(docType, CONSTANTS.webm);
  32551. },
  32552. mkv: function mkv(bytes) {
  32553. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska
  32554. return bytesMatch(docType, CONSTANTS.matroska);
  32555. },
  32556. mp4: function mp4(bytes) {
  32557. // if this file is another base media file format, it is not mp4
  32558. if (_isLikely['3gp'](bytes) || _isLikely.mov(bytes)) {
  32559. return false;
  32560. } // if this file starts with a ftyp or styp box its mp4
  32561. if (bytesMatch(bytes, CONSTANTS.mp4, {
  32562. offset: 4
  32563. }) || bytesMatch(bytes, CONSTANTS.fmp4, {
  32564. offset: 4
  32565. })) {
  32566. return true;
  32567. } // if this file starts with a moof/moov box its mp4
  32568. if (bytesMatch(bytes, CONSTANTS.moof, {
  32569. offset: 4
  32570. }) || bytesMatch(bytes, CONSTANTS.moov, {
  32571. offset: 4
  32572. })) {
  32573. return true;
  32574. }
  32575. },
  32576. mov: function mov(bytes) {
  32577. return bytesMatch(bytes, CONSTANTS.mov, {
  32578. offset: 4
  32579. });
  32580. },
  32581. '3gp': function gp(bytes) {
  32582. return bytesMatch(bytes, CONSTANTS['3gp'], {
  32583. offset: 4
  32584. });
  32585. },
  32586. ac3: function ac3(bytes) {
  32587. var offset = getId3Offset(bytes);
  32588. return bytesMatch(bytes, CONSTANTS.ac3, {
  32589. offset: offset
  32590. });
  32591. },
  32592. ts: function ts(bytes) {
  32593. if (bytes.length < 189 && bytes.length >= 1) {
  32594. return bytes[0] === 0x47;
  32595. }
  32596. var i = 0; // check the first 376 bytes for two matching sync bytes
  32597. while (i + 188 < bytes.length && i < 188) {
  32598. if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
  32599. return true;
  32600. }
  32601. i += 1;
  32602. }
  32603. return false;
  32604. },
  32605. flac: function flac(bytes) {
  32606. var offset = getId3Offset(bytes);
  32607. return bytesMatch(bytes, CONSTANTS.flac, {
  32608. offset: offset
  32609. });
  32610. },
  32611. ogg: function ogg(bytes) {
  32612. return bytesMatch(bytes, CONSTANTS.ogg);
  32613. },
  32614. avi: function avi(bytes) {
  32615. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {
  32616. offset: 8
  32617. });
  32618. },
  32619. wav: function wav(bytes) {
  32620. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {
  32621. offset: 8
  32622. });
  32623. },
  32624. 'h264': function h264(bytes) {
  32625. // find seq_parameter_set_rbsp
  32626. return findH264Nal(bytes, 7, 3).length;
  32627. },
  32628. 'h265': function h265(bytes) {
  32629. // find video_parameter_set_rbsp or seq_parameter_set_rbsp
  32630. return findH265Nal(bytes, [32, 33], 3).length;
  32631. }
  32632. }; // get all the isLikely functions
  32633. // but make sure 'ts' is above h264 and h265
  32634. // but below everything else as it is the least specific
  32635. var isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265
  32636. .filter(function (t) {
  32637. return t !== 'ts' && t !== 'h264' && t !== 'h265';
  32638. }) // add it back to the bottom
  32639. .concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.
  32640. isLikelyTypes.forEach(function (type) {
  32641. var isLikelyFn = _isLikely[type];
  32642. _isLikely[type] = function (bytes) {
  32643. return isLikelyFn(toUint8(bytes));
  32644. };
  32645. }); // export after wrapping
  32646. var isLikely = _isLikely; // A useful list of file signatures can be found here
  32647. // https://en.wikipedia.org/wiki/List_of_file_signatures
  32648. var detectContainerForBytes = function detectContainerForBytes(bytes) {
  32649. bytes = toUint8(bytes);
  32650. for (var i = 0; i < isLikelyTypes.length; i++) {
  32651. var type = isLikelyTypes[i];
  32652. if (isLikely[type](bytes)) {
  32653. return type;
  32654. }
  32655. }
  32656. return '';
  32657. }; // fmp4 is not a container
  32658. var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {
  32659. return findBox(bytes, ['moof']).length > 0;
  32660. };
  32661. /**
  32662. * mux.js
  32663. *
  32664. * Copyright (c) Brightcove
  32665. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  32666. */
  32667. var ONE_SECOND_IN_TS = 90000,
  32668. // 90kHz clock
  32669. secondsToVideoTs,
  32670. secondsToAudioTs,
  32671. videoTsToSeconds,
  32672. audioTsToSeconds,
  32673. audioTsToVideoTs,
  32674. videoTsToAudioTs,
  32675. metadataTsToSeconds;
  32676. secondsToVideoTs = function (seconds) {
  32677. return seconds * ONE_SECOND_IN_TS;
  32678. };
  32679. secondsToAudioTs = function (seconds, sampleRate) {
  32680. return seconds * sampleRate;
  32681. };
  32682. videoTsToSeconds = function (timestamp) {
  32683. return timestamp / ONE_SECOND_IN_TS;
  32684. };
  32685. audioTsToSeconds = function (timestamp, sampleRate) {
  32686. return timestamp / sampleRate;
  32687. };
  32688. audioTsToVideoTs = function (timestamp, sampleRate) {
  32689. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  32690. };
  32691. videoTsToAudioTs = function (timestamp, sampleRate) {
  32692. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  32693. };
  32694. /**
  32695. * Adjust ID3 tag or caption timing information by the timeline pts values
  32696. * (if keepOriginalTimestamps is false) and convert to seconds
  32697. */
  32698. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  32699. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  32700. };
  32701. var clock = {
  32702. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
  32703. secondsToVideoTs: secondsToVideoTs,
  32704. secondsToAudioTs: secondsToAudioTs,
  32705. videoTsToSeconds: videoTsToSeconds,
  32706. audioTsToSeconds: audioTsToSeconds,
  32707. audioTsToVideoTs: audioTsToVideoTs,
  32708. videoTsToAudioTs: videoTsToAudioTs,
  32709. metadataTsToSeconds: metadataTsToSeconds
  32710. };
  32711. var clock_1 = clock.ONE_SECOND_IN_TS;
  32712. /*! @name @videojs/http-streaming @version 3.0.2 @license Apache-2.0 */
  32713. /**
  32714. * @file resolve-url.js - Handling how URLs are resolved and manipulated
  32715. */
  32716. const resolveUrl = resolveUrl$2;
  32717. /**
  32718. * If the xhr request was redirected, return the responseURL, otherwise,
  32719. * return the original url.
  32720. *
  32721. * @api private
  32722. *
  32723. * @param {string} url - an url being requested
  32724. * @param {XMLHttpRequest} req - xhr request result
  32725. *
  32726. * @return {string}
  32727. */
  32728. const resolveManifestRedirect = (url, req) => {
  32729. // To understand how the responseURL below is set and generated:
  32730. // - https://fetch.spec.whatwg.org/#concept-response-url
  32731. // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
  32732. if (req && req.responseURL && url !== req.responseURL) {
  32733. return req.responseURL;
  32734. }
  32735. return url;
  32736. };
  32737. const logger = source => {
  32738. if (videojs.log.debug) {
  32739. return videojs.log.debug.bind(videojs, 'VHS:', `${source} >`);
  32740. }
  32741. return function () {};
  32742. };
  32743. /**
  32744. * Provides a compatibility layer between Video.js 7 and 8 API changes for VHS.
  32745. */
  32746. /**
  32747. * Delegates to videojs.obj.merge (Video.js 8) or
  32748. * videojs.mergeOptions (Video.js 7).
  32749. */
  32750. function merge(...args) {
  32751. const context = videojs.obj || videojs;
  32752. const fn = context.merge || context.mergeOptions;
  32753. return fn.apply(context, args);
  32754. }
  32755. /**
  32756. * Delegates to videojs.time.createTimeRanges (Video.js 8) or
  32757. * videojs.createTimeRanges (Video.js 7).
  32758. */
  32759. function createTimeRanges(...args) {
  32760. const context = videojs.time || videojs;
  32761. const fn = context.createTimeRanges || context.createTimeRanges;
  32762. return fn.apply(context, args);
  32763. }
  32764. /**
  32765. * ranges
  32766. *
  32767. * Utilities for working with TimeRanges.
  32768. *
  32769. */
  32770. const TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
  32771. // can be misleading because of precision differences or when the current media has poorly
  32772. // aligned audio and video, which can cause values to be slightly off from what you would
  32773. // expect. This value is what we consider to be safe to use in such comparisons to account
  32774. // for these scenarios.
  32775. const SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
  32776. const filterRanges = function (timeRanges, predicate) {
  32777. const results = [];
  32778. let i;
  32779. if (timeRanges && timeRanges.length) {
  32780. // Search for ranges that match the predicate
  32781. for (i = 0; i < timeRanges.length; i++) {
  32782. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  32783. results.push([timeRanges.start(i), timeRanges.end(i)]);
  32784. }
  32785. }
  32786. }
  32787. return createTimeRanges(results);
  32788. };
  32789. /**
  32790. * Attempts to find the buffered TimeRange that contains the specified
  32791. * time.
  32792. *
  32793. * @param {TimeRanges} buffered - the TimeRanges object to query
  32794. * @param {number} time - the time to filter on.
  32795. * @return {TimeRanges} a new TimeRanges object
  32796. */
  32797. const findRange = function (buffered, time) {
  32798. return filterRanges(buffered, function (start, end) {
  32799. return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  32800. });
  32801. };
  32802. /**
  32803. * Returns the TimeRanges that begin later than the specified time.
  32804. *
  32805. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  32806. * @param {number} time - the time to filter on.
  32807. * @return {TimeRanges} a new TimeRanges object.
  32808. */
  32809. const findNextRange = function (timeRanges, time) {
  32810. return filterRanges(timeRanges, function (start) {
  32811. return start - TIME_FUDGE_FACTOR >= time;
  32812. });
  32813. };
  32814. /**
  32815. * Returns gaps within a list of TimeRanges
  32816. *
  32817. * @param {TimeRanges} buffered - the TimeRanges object
  32818. * @return {TimeRanges} a TimeRanges object of gaps
  32819. */
  32820. const findGaps = function (buffered) {
  32821. if (buffered.length < 2) {
  32822. return createTimeRanges();
  32823. }
  32824. const ranges = [];
  32825. for (let i = 1; i < buffered.length; i++) {
  32826. const start = buffered.end(i - 1);
  32827. const end = buffered.start(i);
  32828. ranges.push([start, end]);
  32829. }
  32830. return createTimeRanges(ranges);
  32831. };
  32832. /**
  32833. * Calculate the intersection of two TimeRanges
  32834. *
  32835. * @param {TimeRanges} bufferA
  32836. * @param {TimeRanges} bufferB
  32837. * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
  32838. */
  32839. const bufferIntersection = function (bufferA, bufferB) {
  32840. let start = null;
  32841. let end = null;
  32842. let arity = 0;
  32843. const extents = [];
  32844. const ranges = [];
  32845. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  32846. return createTimeRanges();
  32847. } // Handle the case where we have both buffers and create an
  32848. // intersection of the two
  32849. let count = bufferA.length; // A) Gather up all start and end times
  32850. while (count--) {
  32851. extents.push({
  32852. time: bufferA.start(count),
  32853. type: 'start'
  32854. });
  32855. extents.push({
  32856. time: bufferA.end(count),
  32857. type: 'end'
  32858. });
  32859. }
  32860. count = bufferB.length;
  32861. while (count--) {
  32862. extents.push({
  32863. time: bufferB.start(count),
  32864. type: 'start'
  32865. });
  32866. extents.push({
  32867. time: bufferB.end(count),
  32868. type: 'end'
  32869. });
  32870. } // B) Sort them by time
  32871. extents.sort(function (a, b) {
  32872. return a.time - b.time;
  32873. }); // C) Go along one by one incrementing arity for start and decrementing
  32874. // arity for ends
  32875. for (count = 0; count < extents.length; count++) {
  32876. if (extents[count].type === 'start') {
  32877. arity++; // D) If arity is ever incremented to 2 we are entering an
  32878. // overlapping range
  32879. if (arity === 2) {
  32880. start = extents[count].time;
  32881. }
  32882. } else if (extents[count].type === 'end') {
  32883. arity--; // E) If arity is ever decremented to 1 we leaving an
  32884. // overlapping range
  32885. if (arity === 1) {
  32886. end = extents[count].time;
  32887. }
  32888. } // F) Record overlapping ranges
  32889. if (start !== null && end !== null) {
  32890. ranges.push([start, end]);
  32891. start = null;
  32892. end = null;
  32893. }
  32894. }
  32895. return createTimeRanges(ranges);
  32896. };
  32897. /**
  32898. * Gets a human readable string for a TimeRange
  32899. *
  32900. * @param {TimeRange} range
  32901. * @return {string} a human readable string
  32902. */
  32903. const printableRange = range => {
  32904. const strArr = [];
  32905. if (!range || !range.length) {
  32906. return '';
  32907. }
  32908. for (let i = 0; i < range.length; i++) {
  32909. strArr.push(range.start(i) + ' => ' + range.end(i));
  32910. }
  32911. return strArr.join(', ');
  32912. };
  32913. /**
  32914. * Calculates the amount of time left in seconds until the player hits the end of the
  32915. * buffer and causes a rebuffer
  32916. *
  32917. * @param {TimeRange} buffered
  32918. * The state of the buffer
  32919. * @param {Numnber} currentTime
  32920. * The current time of the player
  32921. * @param {number} playbackRate
  32922. * The current playback rate of the player. Defaults to 1.
  32923. * @return {number}
  32924. * Time until the player has to start rebuffering in seconds.
  32925. * @function timeUntilRebuffer
  32926. */
  32927. const timeUntilRebuffer = function (buffered, currentTime, playbackRate = 1) {
  32928. const bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  32929. return (bufferedEnd - currentTime) / playbackRate;
  32930. };
  32931. /**
  32932. * Converts a TimeRanges object into an array representation
  32933. *
  32934. * @param {TimeRanges} timeRanges
  32935. * @return {Array}
  32936. */
  32937. const timeRangesToArray = timeRanges => {
  32938. const timeRangesList = [];
  32939. for (let i = 0; i < timeRanges.length; i++) {
  32940. timeRangesList.push({
  32941. start: timeRanges.start(i),
  32942. end: timeRanges.end(i)
  32943. });
  32944. }
  32945. return timeRangesList;
  32946. };
  32947. /**
  32948. * Determines if two time range objects are different.
  32949. *
  32950. * @param {TimeRange} a
  32951. * the first time range object to check
  32952. *
  32953. * @param {TimeRange} b
  32954. * the second time range object to check
  32955. *
  32956. * @return {Boolean}
  32957. * Whether the time range objects differ
  32958. */
  32959. const isRangeDifferent = function (a, b) {
  32960. // same object
  32961. if (a === b) {
  32962. return false;
  32963. } // one or the other is undefined
  32964. if (!a && b || !b && a) {
  32965. return true;
  32966. } // length is different
  32967. if (a.length !== b.length) {
  32968. return true;
  32969. } // see if any start/end pair is different
  32970. for (let i = 0; i < a.length; i++) {
  32971. if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
  32972. return true;
  32973. }
  32974. } // if the length and every pair is the same
  32975. // this is the same time range
  32976. return false;
  32977. };
  32978. const lastBufferedEnd = function (a) {
  32979. if (!a || !a.length || !a.end) {
  32980. return;
  32981. }
  32982. return a.end(a.length - 1);
  32983. };
  32984. /**
  32985. * A utility function to add up the amount of time in a timeRange
  32986. * after a specified startTime.
  32987. * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0
  32988. * would return 40 as there are 40s seconds after 0 in the timeRange
  32989. *
  32990. * @param {TimeRange} range
  32991. * The range to check against
  32992. * @param {number} startTime
  32993. * The time in the time range that you should start counting from
  32994. *
  32995. * @return {number}
  32996. * The number of seconds in the buffer passed the specified time.
  32997. */
  32998. const timeAheadOf = function (range, startTime) {
  32999. let time = 0;
  33000. if (!range || !range.length) {
  33001. return time;
  33002. }
  33003. for (let i = 0; i < range.length; i++) {
  33004. const start = range.start(i);
  33005. const end = range.end(i); // startTime is after this range entirely
  33006. if (startTime > end) {
  33007. continue;
  33008. } // startTime is within this range
  33009. if (startTime > start && startTime <= end) {
  33010. time += end - startTime;
  33011. continue;
  33012. } // startTime is before this range.
  33013. time += end - start;
  33014. }
  33015. return time;
  33016. };
  33017. /**
  33018. * @file playlist.js
  33019. *
  33020. * Playlist related utilities.
  33021. */
  33022. /**
  33023. * Get the duration of a segment, with special cases for
  33024. * llhls segments that do not have a duration yet.
  33025. *
  33026. * @param {Object} playlist
  33027. * the playlist that the segment belongs to.
  33028. * @param {Object} segment
  33029. * the segment to get a duration for.
  33030. *
  33031. * @return {number}
  33032. * the segment duration
  33033. */
  33034. const segmentDurationWithParts = (playlist, segment) => {
  33035. // if this isn't a preload segment
  33036. // then we will have a segment duration that is accurate.
  33037. if (!segment.preload) {
  33038. return segment.duration;
  33039. } // otherwise we have to add up parts and preload hints
  33040. // to get an up to date duration.
  33041. let result = 0;
  33042. (segment.parts || []).forEach(function (p) {
  33043. result += p.duration;
  33044. }); // for preload hints we have to use partTargetDuration
  33045. // as they won't even have a duration yet.
  33046. (segment.preloadHints || []).forEach(function (p) {
  33047. if (p.type === 'PART') {
  33048. result += playlist.partTargetDuration;
  33049. }
  33050. });
  33051. return result;
  33052. };
  33053. /**
  33054. * A function to get a combined list of parts and segments with durations
  33055. * and indexes.
  33056. *
  33057. * @param {Playlist} playlist the playlist to get the list for.
  33058. *
  33059. * @return {Array} The part/segment list.
  33060. */
  33061. const getPartsAndSegments = playlist => (playlist.segments || []).reduce((acc, segment, si) => {
  33062. if (segment.parts) {
  33063. segment.parts.forEach(function (part, pi) {
  33064. acc.push({
  33065. duration: part.duration,
  33066. segmentIndex: si,
  33067. partIndex: pi,
  33068. part,
  33069. segment
  33070. });
  33071. });
  33072. } else {
  33073. acc.push({
  33074. duration: segment.duration,
  33075. segmentIndex: si,
  33076. partIndex: null,
  33077. segment,
  33078. part: null
  33079. });
  33080. }
  33081. return acc;
  33082. }, []);
  33083. const getLastParts = media => {
  33084. const lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  33085. return lastSegment && lastSegment.parts || [];
  33086. };
  33087. const getKnownPartCount = ({
  33088. preloadSegment
  33089. }) => {
  33090. if (!preloadSegment) {
  33091. return;
  33092. }
  33093. const {
  33094. parts,
  33095. preloadHints
  33096. } = preloadSegment;
  33097. let partCount = (preloadHints || []).reduce((count, hint) => count + (hint.type === 'PART' ? 1 : 0), 0);
  33098. partCount += parts && parts.length ? parts.length : 0;
  33099. return partCount;
  33100. };
  33101. /**
  33102. * Get the number of seconds to delay from the end of a
  33103. * live playlist.
  33104. *
  33105. * @param {Playlist} main the main playlist
  33106. * @param {Playlist} media the media playlist
  33107. * @return {number} the hold back in seconds.
  33108. */
  33109. const liveEdgeDelay = (main, media) => {
  33110. if (media.endList) {
  33111. return 0;
  33112. } // dash suggestedPresentationDelay trumps everything
  33113. if (main && main.suggestedPresentationDelay) {
  33114. return main.suggestedPresentationDelay;
  33115. }
  33116. const hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
  33117. if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
  33118. return media.serverControl.partHoldBack;
  33119. } else if (hasParts && media.partTargetDuration) {
  33120. return media.partTargetDuration * 3; // finally look for full segment delays
  33121. } else if (media.serverControl && media.serverControl.holdBack) {
  33122. return media.serverControl.holdBack;
  33123. } else if (media.targetDuration) {
  33124. return media.targetDuration * 3;
  33125. }
  33126. return 0;
  33127. };
  33128. /**
  33129. * walk backward until we find a duration we can use
  33130. * or return a failure
  33131. *
  33132. * @param {Playlist} playlist the playlist to walk through
  33133. * @param {Number} endSequence the mediaSequence to stop walking on
  33134. */
  33135. const backwardDuration = function (playlist, endSequence) {
  33136. let result = 0;
  33137. let i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
  33138. // the interval, use it
  33139. let segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
  33140. // information that is earlier than endSequence
  33141. if (segment) {
  33142. if (typeof segment.start !== 'undefined') {
  33143. return {
  33144. result: segment.start,
  33145. precise: true
  33146. };
  33147. }
  33148. if (typeof segment.end !== 'undefined') {
  33149. return {
  33150. result: segment.end - segment.duration,
  33151. precise: true
  33152. };
  33153. }
  33154. }
  33155. while (i--) {
  33156. segment = playlist.segments[i];
  33157. if (typeof segment.end !== 'undefined') {
  33158. return {
  33159. result: result + segment.end,
  33160. precise: true
  33161. };
  33162. }
  33163. result += segmentDurationWithParts(playlist, segment);
  33164. if (typeof segment.start !== 'undefined') {
  33165. return {
  33166. result: result + segment.start,
  33167. precise: true
  33168. };
  33169. }
  33170. }
  33171. return {
  33172. result,
  33173. precise: false
  33174. };
  33175. };
  33176. /**
  33177. * walk forward until we find a duration we can use
  33178. * or return a failure
  33179. *
  33180. * @param {Playlist} playlist the playlist to walk through
  33181. * @param {number} endSequence the mediaSequence to stop walking on
  33182. */
  33183. const forwardDuration = function (playlist, endSequence) {
  33184. let result = 0;
  33185. let segment;
  33186. let i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
  33187. // information
  33188. for (; i < playlist.segments.length; i++) {
  33189. segment = playlist.segments[i];
  33190. if (typeof segment.start !== 'undefined') {
  33191. return {
  33192. result: segment.start - result,
  33193. precise: true
  33194. };
  33195. }
  33196. result += segmentDurationWithParts(playlist, segment);
  33197. if (typeof segment.end !== 'undefined') {
  33198. return {
  33199. result: segment.end - result,
  33200. precise: true
  33201. };
  33202. }
  33203. } // indicate we didn't find a useful duration estimate
  33204. return {
  33205. result: -1,
  33206. precise: false
  33207. };
  33208. };
  33209. /**
  33210. * Calculate the media duration from the segments associated with a
  33211. * playlist. The duration of a subinterval of the available segments
  33212. * may be calculated by specifying an end index.
  33213. *
  33214. * @param {Object} playlist a media playlist object
  33215. * @param {number=} endSequence an exclusive upper boundary
  33216. * for the playlist. Defaults to playlist length.
  33217. * @param {number} expired the amount of time that has dropped
  33218. * off the front of the playlist in a live scenario
  33219. * @return {number} the duration between the first available segment
  33220. * and end index.
  33221. */
  33222. const intervalDuration = function (playlist, endSequence, expired) {
  33223. if (typeof endSequence === 'undefined') {
  33224. endSequence = playlist.mediaSequence + playlist.segments.length;
  33225. }
  33226. if (endSequence < playlist.mediaSequence) {
  33227. return 0;
  33228. } // do a backward walk to estimate the duration
  33229. const backward = backwardDuration(playlist, endSequence);
  33230. if (backward.precise) {
  33231. // if we were able to base our duration estimate on timing
  33232. // information provided directly from the Media Source, return
  33233. // it
  33234. return backward.result;
  33235. } // walk forward to see if a precise duration estimate can be made
  33236. // that way
  33237. const forward = forwardDuration(playlist, endSequence);
  33238. if (forward.precise) {
  33239. // we found a segment that has been buffered and so it's
  33240. // position is known precisely
  33241. return forward.result;
  33242. } // return the less-precise, playlist-based duration estimate
  33243. return backward.result + expired;
  33244. };
  33245. /**
  33246. * Calculates the duration of a playlist. If a start and end index
  33247. * are specified, the duration will be for the subset of the media
  33248. * timeline between those two indices. The total duration for live
  33249. * playlists is always Infinity.
  33250. *
  33251. * @param {Object} playlist a media playlist object
  33252. * @param {number=} endSequence an exclusive upper
  33253. * boundary for the playlist. Defaults to the playlist media
  33254. * sequence number plus its length.
  33255. * @param {number=} expired the amount of time that has
  33256. * dropped off the front of the playlist in a live scenario
  33257. * @return {number} the duration between the start index and end
  33258. * index.
  33259. */
  33260. const duration = function (playlist, endSequence, expired) {
  33261. if (!playlist) {
  33262. return 0;
  33263. }
  33264. if (typeof expired !== 'number') {
  33265. expired = 0;
  33266. } // if a slice of the total duration is not requested, use
  33267. // playlist-level duration indicators when they're present
  33268. if (typeof endSequence === 'undefined') {
  33269. // if present, use the duration specified in the playlist
  33270. if (playlist.totalDuration) {
  33271. return playlist.totalDuration;
  33272. } // duration should be Infinity for live playlists
  33273. if (!playlist.endList) {
  33274. return window.Infinity;
  33275. }
  33276. } // calculate the total duration based on the segment durations
  33277. return intervalDuration(playlist, endSequence, expired);
  33278. };
  33279. /**
  33280. * Calculate the time between two indexes in the current playlist
  33281. * neight the start- nor the end-index need to be within the current
  33282. * playlist in which case, the targetDuration of the playlist is used
  33283. * to approximate the durations of the segments
  33284. *
  33285. * @param {Array} options.durationList list to iterate over for durations.
  33286. * @param {number} options.defaultDuration duration to use for elements before or after the durationList
  33287. * @param {number} options.startIndex partsAndSegments index to start
  33288. * @param {number} options.endIndex partsAndSegments index to end.
  33289. * @return {number} the number of seconds between startIndex and endIndex
  33290. */
  33291. const sumDurations = function ({
  33292. defaultDuration,
  33293. durationList,
  33294. startIndex,
  33295. endIndex
  33296. }) {
  33297. let durations = 0;
  33298. if (startIndex > endIndex) {
  33299. [startIndex, endIndex] = [endIndex, startIndex];
  33300. }
  33301. if (startIndex < 0) {
  33302. for (let i = startIndex; i < Math.min(0, endIndex); i++) {
  33303. durations += defaultDuration;
  33304. }
  33305. startIndex = 0;
  33306. }
  33307. for (let i = startIndex; i < endIndex; i++) {
  33308. durations += durationList[i].duration;
  33309. }
  33310. return durations;
  33311. };
  33312. /**
  33313. * Calculates the playlist end time
  33314. *
  33315. * @param {Object} playlist a media playlist object
  33316. * @param {number=} expired the amount of time that has
  33317. * dropped off the front of the playlist in a live scenario
  33318. * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
  33319. * playlist end calculation should consider the safe live end
  33320. * (truncate the playlist end by three segments). This is normally
  33321. * used for calculating the end of the playlist's seekable range.
  33322. * This takes into account the value of liveEdgePadding.
  33323. * Setting liveEdgePadding to 0 is equivalent to setting this to false.
  33324. * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
  33325. * If this is provided, it is used in the safe live end calculation.
  33326. * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
  33327. * Corresponds to suggestedPresentationDelay in DASH manifests.
  33328. * @return {number} the end time of playlist
  33329. * @function playlistEnd
  33330. */
  33331. const playlistEnd = function (playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  33332. if (!playlist || !playlist.segments) {
  33333. return null;
  33334. }
  33335. if (playlist.endList) {
  33336. return duration(playlist);
  33337. }
  33338. if (expired === null) {
  33339. return null;
  33340. }
  33341. expired = expired || 0;
  33342. let lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  33343. if (useSafeLiveEnd) {
  33344. liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
  33345. lastSegmentEndTime -= liveEdgePadding;
  33346. } // don't return a time less than zero
  33347. return Math.max(0, lastSegmentEndTime);
  33348. };
  33349. /**
  33350. * Calculates the interval of time that is currently seekable in a
  33351. * playlist. The returned time ranges are relative to the earliest
  33352. * moment in the specified playlist that is still available. A full
  33353. * seekable implementation for live streams would need to offset
  33354. * these values by the duration of content that has expired from the
  33355. * stream.
  33356. *
  33357. * @param {Object} playlist a media playlist object
  33358. * dropped off the front of the playlist in a live scenario
  33359. * @param {number=} expired the amount of time that has
  33360. * dropped off the front of the playlist in a live scenario
  33361. * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
  33362. * Corresponds to suggestedPresentationDelay in DASH manifests.
  33363. * @return {TimeRanges} the periods of time that are valid targets
  33364. * for seeking
  33365. */
  33366. const seekable = function (playlist, expired, liveEdgePadding) {
  33367. const useSafeLiveEnd = true;
  33368. const seekableStart = expired || 0;
  33369. const seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  33370. if (seekableEnd === null) {
  33371. return createTimeRanges();
  33372. }
  33373. return createTimeRanges(seekableStart, seekableEnd);
  33374. };
  33375. /**
  33376. * Determine the index and estimated starting time of the segment that
  33377. * contains a specified playback position in a media playlist.
  33378. *
  33379. * @param {Object} options.playlist the media playlist to query
  33380. * @param {number} options.currentTime The number of seconds since the earliest
  33381. * possible position to determine the containing segment for
  33382. * @param {number} options.startTime the time when the segment/part starts
  33383. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  33384. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  33385. *
  33386. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  33387. */
  33388. const getMediaInfoForTime = function ({
  33389. playlist,
  33390. currentTime,
  33391. startingSegmentIndex,
  33392. startingPartIndex,
  33393. startTime,
  33394. exactManifestTimings
  33395. }) {
  33396. let time = currentTime - startTime;
  33397. const partsAndSegments = getPartsAndSegments(playlist);
  33398. let startIndex = 0;
  33399. for (let i = 0; i < partsAndSegments.length; i++) {
  33400. const partAndSegment = partsAndSegments[i];
  33401. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  33402. continue;
  33403. } // skip this if part index does not match.
  33404. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  33405. continue;
  33406. }
  33407. startIndex = i;
  33408. break;
  33409. }
  33410. if (time < 0) {
  33411. // Walk backward from startIndex in the playlist, adding durations
  33412. // until we find a segment that contains `time` and return it
  33413. if (startIndex > 0) {
  33414. for (let i = startIndex - 1; i >= 0; i--) {
  33415. const partAndSegment = partsAndSegments[i];
  33416. time += partAndSegment.duration;
  33417. if (exactManifestTimings) {
  33418. if (time < 0) {
  33419. continue;
  33420. }
  33421. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  33422. continue;
  33423. }
  33424. return {
  33425. partIndex: partAndSegment.partIndex,
  33426. segmentIndex: partAndSegment.segmentIndex,
  33427. startTime: startTime - sumDurations({
  33428. defaultDuration: playlist.targetDuration,
  33429. durationList: partsAndSegments,
  33430. startIndex,
  33431. endIndex: i
  33432. })
  33433. };
  33434. }
  33435. } // We were unable to find a good segment within the playlist
  33436. // so select the first segment
  33437. return {
  33438. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  33439. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  33440. startTime: currentTime
  33441. };
  33442. } // When startIndex is negative, we first walk forward to first segment
  33443. // adding target durations. If we "run out of time" before getting to
  33444. // the first segment, return the first segment
  33445. if (startIndex < 0) {
  33446. for (let i = startIndex; i < 0; i++) {
  33447. time -= playlist.targetDuration;
  33448. if (time < 0) {
  33449. return {
  33450. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  33451. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  33452. startTime: currentTime
  33453. };
  33454. }
  33455. }
  33456. startIndex = 0;
  33457. } // Walk forward from startIndex in the playlist, subtracting durations
  33458. // until we find a segment that contains `time` and return it
  33459. for (let i = startIndex; i < partsAndSegments.length; i++) {
  33460. const partAndSegment = partsAndSegments[i];
  33461. time -= partAndSegment.duration;
  33462. if (exactManifestTimings) {
  33463. if (time > 0) {
  33464. continue;
  33465. }
  33466. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  33467. continue;
  33468. }
  33469. return {
  33470. partIndex: partAndSegment.partIndex,
  33471. segmentIndex: partAndSegment.segmentIndex,
  33472. startTime: startTime + sumDurations({
  33473. defaultDuration: playlist.targetDuration,
  33474. durationList: partsAndSegments,
  33475. startIndex,
  33476. endIndex: i
  33477. })
  33478. };
  33479. } // We are out of possible candidates so load the last one...
  33480. return {
  33481. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  33482. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  33483. startTime: currentTime
  33484. };
  33485. };
  33486. /**
  33487. * Check whether the playlist is excluded or not.
  33488. *
  33489. * @param {Object} playlist the media playlist object
  33490. * @return {boolean} whether the playlist is excluded or not
  33491. * @function isExcluded
  33492. */
  33493. const isExcluded = function (playlist) {
  33494. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  33495. };
  33496. /**
  33497. * Check whether the playlist is compatible with current playback configuration or has
  33498. * been excluded permanently for being incompatible.
  33499. *
  33500. * @param {Object} playlist the media playlist object
  33501. * @return {boolean} whether the playlist is incompatible or not
  33502. * @function isIncompatible
  33503. */
  33504. const isIncompatible = function (playlist) {
  33505. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  33506. };
  33507. /**
  33508. * Check whether the playlist is enabled or not.
  33509. *
  33510. * @param {Object} playlist the media playlist object
  33511. * @return {boolean} whether the playlist is enabled or not
  33512. * @function isEnabled
  33513. */
  33514. const isEnabled = function (playlist) {
  33515. const excluded = isExcluded(playlist);
  33516. return !playlist.disabled && !excluded;
  33517. };
  33518. /**
  33519. * Check whether the playlist has been manually disabled through the representations api.
  33520. *
  33521. * @param {Object} playlist the media playlist object
  33522. * @return {boolean} whether the playlist is disabled manually or not
  33523. * @function isDisabled
  33524. */
  33525. const isDisabled = function (playlist) {
  33526. return playlist.disabled;
  33527. };
  33528. /**
  33529. * Returns whether the current playlist is an AES encrypted HLS stream
  33530. *
  33531. * @return {boolean} true if it's an AES encrypted HLS stream
  33532. */
  33533. const isAes = function (media) {
  33534. for (let i = 0; i < media.segments.length; i++) {
  33535. if (media.segments[i].key) {
  33536. return true;
  33537. }
  33538. }
  33539. return false;
  33540. };
  33541. /**
  33542. * Checks if the playlist has a value for the specified attribute
  33543. *
  33544. * @param {string} attr
  33545. * Attribute to check for
  33546. * @param {Object} playlist
  33547. * The media playlist object
  33548. * @return {boolean}
  33549. * Whether the playlist contains a value for the attribute or not
  33550. * @function hasAttribute
  33551. */
  33552. const hasAttribute = function (attr, playlist) {
  33553. return playlist.attributes && playlist.attributes[attr];
  33554. };
  33555. /**
  33556. * Estimates the time required to complete a segment download from the specified playlist
  33557. *
  33558. * @param {number} segmentDuration
  33559. * Duration of requested segment
  33560. * @param {number} bandwidth
  33561. * Current measured bandwidth of the player
  33562. * @param {Object} playlist
  33563. * The media playlist object
  33564. * @param {number=} bytesReceived
  33565. * Number of bytes already received for the request. Defaults to 0
  33566. * @return {number|NaN}
  33567. * The estimated time to request the segment. NaN if bandwidth information for
  33568. * the given playlist is unavailable
  33569. * @function estimateSegmentRequestTime
  33570. */
  33571. const estimateSegmentRequestTime = function (segmentDuration, bandwidth, playlist, bytesReceived = 0) {
  33572. if (!hasAttribute('BANDWIDTH', playlist)) {
  33573. return NaN;
  33574. }
  33575. const size = segmentDuration * playlist.attributes.BANDWIDTH;
  33576. return (size - bytesReceived * 8) / bandwidth;
  33577. };
  33578. /*
  33579. * Returns whether the current playlist is the lowest rendition
  33580. *
  33581. * @return {Boolean} true if on lowest rendition
  33582. */
  33583. const isLowestEnabledRendition = (main, media) => {
  33584. if (main.playlists.length === 1) {
  33585. return true;
  33586. }
  33587. const currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  33588. return main.playlists.filter(playlist => {
  33589. if (!isEnabled(playlist)) {
  33590. return false;
  33591. }
  33592. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  33593. }).length === 0;
  33594. };
  33595. const playlistMatch = (a, b) => {
  33596. // both playlits are null
  33597. // or only one playlist is non-null
  33598. // no match
  33599. if (!a && !b || !a && b || a && !b) {
  33600. return false;
  33601. } // playlist objects are the same, match
  33602. if (a === b) {
  33603. return true;
  33604. } // first try to use id as it should be the most
  33605. // accurate
  33606. if (a.id && b.id && a.id === b.id) {
  33607. return true;
  33608. } // next try to use reslovedUri as it should be the
  33609. // second most accurate.
  33610. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  33611. return true;
  33612. } // finally try to use uri as it should be accurate
  33613. // but might miss a few cases for relative uris
  33614. if (a.uri && b.uri && a.uri === b.uri) {
  33615. return true;
  33616. }
  33617. return false;
  33618. };
  33619. const someAudioVariant = function (main, callback) {
  33620. const AUDIO = main && main.mediaGroups && main.mediaGroups.AUDIO || {};
  33621. let found = false;
  33622. for (const groupName in AUDIO) {
  33623. for (const label in AUDIO[groupName]) {
  33624. found = callback(AUDIO[groupName][label]);
  33625. if (found) {
  33626. break;
  33627. }
  33628. }
  33629. if (found) {
  33630. break;
  33631. }
  33632. }
  33633. return !!found;
  33634. };
  33635. const isAudioOnly = main => {
  33636. // we are audio only if we have no main playlists but do
  33637. // have media group playlists.
  33638. if (!main || !main.playlists || !main.playlists.length) {
  33639. // without audio variants or playlists this
  33640. // is not an audio only main.
  33641. const found = someAudioVariant(main, variant => variant.playlists && variant.playlists.length || variant.uri);
  33642. return found;
  33643. } // if every playlist has only an audio codec it is audio only
  33644. for (let i = 0; i < main.playlists.length; i++) {
  33645. const playlist = main.playlists[i];
  33646. const CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  33647. if (CODECS && CODECS.split(',').every(c => isAudioCodec(c))) {
  33648. continue;
  33649. } // playlist is in an audio group it is audio only
  33650. const found = someAudioVariant(main, variant => playlistMatch(playlist, variant));
  33651. if (found) {
  33652. continue;
  33653. } // if we make it here this playlist isn't audio and we
  33654. // are not audio only
  33655. return false;
  33656. } // if we make it past every playlist without returning, then
  33657. // this is an audio only playlist.
  33658. return true;
  33659. }; // exports
  33660. var Playlist = {
  33661. liveEdgeDelay,
  33662. duration,
  33663. seekable,
  33664. getMediaInfoForTime,
  33665. isEnabled,
  33666. isDisabled,
  33667. isExcluded,
  33668. isIncompatible,
  33669. playlistEnd,
  33670. isAes,
  33671. hasAttribute,
  33672. estimateSegmentRequestTime,
  33673. isLowestEnabledRendition,
  33674. isAudioOnly,
  33675. playlistMatch,
  33676. segmentDurationWithParts
  33677. };
  33678. const {
  33679. log
  33680. } = videojs;
  33681. const createPlaylistID = (index, uri) => {
  33682. return `${index}-${uri}`;
  33683. }; // default function for creating a group id
  33684. const groupID = (type, group, label) => {
  33685. return `placeholder-uri-${type}-${group}-${label}`;
  33686. };
  33687. /**
  33688. * Parses a given m3u8 playlist
  33689. *
  33690. * @param {Function} [onwarn]
  33691. * a function to call when the parser triggers a warning event.
  33692. * @param {Function} [oninfo]
  33693. * a function to call when the parser triggers an info event.
  33694. * @param {string} manifestString
  33695. * The downloaded manifest string
  33696. * @param {Object[]} [customTagParsers]
  33697. * An array of custom tag parsers for the m3u8-parser instance
  33698. * @param {Object[]} [customTagMappers]
  33699. * An array of custom tag mappers for the m3u8-parser instance
  33700. * @param {boolean} [llhls]
  33701. * Whether to keep ll-hls features in the manifest after parsing.
  33702. * @return {Object}
  33703. * The manifest object
  33704. */
  33705. const parseManifest = ({
  33706. onwarn,
  33707. oninfo,
  33708. manifestString,
  33709. customTagParsers = [],
  33710. customTagMappers = [],
  33711. llhls
  33712. }) => {
  33713. const parser = new Parser();
  33714. if (onwarn) {
  33715. parser.on('warn', onwarn);
  33716. }
  33717. if (oninfo) {
  33718. parser.on('info', oninfo);
  33719. }
  33720. customTagParsers.forEach(customParser => parser.addParser(customParser));
  33721. customTagMappers.forEach(mapper => parser.addTagMapper(mapper));
  33722. parser.push(manifestString);
  33723. parser.end();
  33724. const manifest = parser.manifest; // remove llhls features from the parsed manifest
  33725. // if we don't want llhls support.
  33726. if (!llhls) {
  33727. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  33728. if (manifest.hasOwnProperty(k)) {
  33729. delete manifest[k];
  33730. }
  33731. });
  33732. if (manifest.segments) {
  33733. manifest.segments.forEach(function (segment) {
  33734. ['parts', 'preloadHints'].forEach(function (k) {
  33735. if (segment.hasOwnProperty(k)) {
  33736. delete segment[k];
  33737. }
  33738. });
  33739. });
  33740. }
  33741. }
  33742. if (!manifest.targetDuration) {
  33743. let targetDuration = 10;
  33744. if (manifest.segments && manifest.segments.length) {
  33745. targetDuration = manifest.segments.reduce((acc, s) => Math.max(acc, s.duration), 0);
  33746. }
  33747. if (onwarn) {
  33748. onwarn(`manifest has no targetDuration defaulting to ${targetDuration}`);
  33749. }
  33750. manifest.targetDuration = targetDuration;
  33751. }
  33752. const parts = getLastParts(manifest);
  33753. if (parts.length && !manifest.partTargetDuration) {
  33754. const partTargetDuration = parts.reduce((acc, p) => Math.max(acc, p.duration), 0);
  33755. if (onwarn) {
  33756. onwarn(`manifest has no partTargetDuration defaulting to ${partTargetDuration}`);
  33757. 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.');
  33758. }
  33759. manifest.partTargetDuration = partTargetDuration;
  33760. }
  33761. return manifest;
  33762. };
  33763. /**
  33764. * Loops through all supported media groups in main and calls the provided
  33765. * callback for each group
  33766. *
  33767. * @param {Object} main
  33768. * The parsed main manifest object
  33769. * @param {Function} callback
  33770. * Callback to call for each media group
  33771. */
  33772. const forEachMediaGroup = (main, callback) => {
  33773. if (!main.mediaGroups) {
  33774. return;
  33775. }
  33776. ['AUDIO', 'SUBTITLES'].forEach(mediaType => {
  33777. if (!main.mediaGroups[mediaType]) {
  33778. return;
  33779. }
  33780. for (const groupKey in main.mediaGroups[mediaType]) {
  33781. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  33782. const mediaProperties = main.mediaGroups[mediaType][groupKey][labelKey];
  33783. callback(mediaProperties, mediaType, groupKey, labelKey);
  33784. }
  33785. }
  33786. });
  33787. };
  33788. /**
  33789. * Adds properties and attributes to the playlist to keep consistent functionality for
  33790. * playlists throughout VHS.
  33791. *
  33792. * @param {Object} config
  33793. * Arguments object
  33794. * @param {Object} config.playlist
  33795. * The media playlist
  33796. * @param {string} [config.uri]
  33797. * The uri to the media playlist (if media playlist is not from within a main
  33798. * playlist)
  33799. * @param {string} id
  33800. * ID to use for the playlist
  33801. */
  33802. const setupMediaPlaylist = ({
  33803. playlist,
  33804. uri,
  33805. id
  33806. }) => {
  33807. playlist.id = id;
  33808. playlist.playlistErrors_ = 0;
  33809. if (uri) {
  33810. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  33811. // playlists do not contain their own source URI, but one is needed for consistency in
  33812. // VHS.
  33813. playlist.uri = uri;
  33814. } // For HLS main playlists, even though certain attributes MUST be defined, the
  33815. // stream may still be played without them.
  33816. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  33817. // manifest.
  33818. //
  33819. // To avoid undefined reference errors through the project, and make the code easier
  33820. // to write/read, add an empty attributes object for these cases.
  33821. playlist.attributes = playlist.attributes || {};
  33822. };
  33823. /**
  33824. * Adds ID, resolvedUri, and attributes properties to each playlist of the main, where
  33825. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  33826. * playlist references to the playlists array.
  33827. *
  33828. * @param {Object} main
  33829. * The main playlist
  33830. */
  33831. const setupMediaPlaylists = main => {
  33832. let i = main.playlists.length;
  33833. while (i--) {
  33834. const playlist = main.playlists[i];
  33835. setupMediaPlaylist({
  33836. playlist,
  33837. id: createPlaylistID(i, playlist.uri)
  33838. });
  33839. playlist.resolvedUri = resolveUrl(main.uri, playlist.uri);
  33840. main.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  33841. main.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  33842. // the stream can be played without it. Although an attributes property may have been
  33843. // added to the playlist to prevent undefined references, issue a warning to fix the
  33844. // manifest.
  33845. if (!playlist.attributes.BANDWIDTH) {
  33846. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  33847. }
  33848. }
  33849. };
  33850. /**
  33851. * Adds resolvedUri properties to each media group.
  33852. *
  33853. * @param {Object} main
  33854. * The main playlist
  33855. */
  33856. const resolveMediaGroupUris = main => {
  33857. forEachMediaGroup(main, properties => {
  33858. if (properties.uri) {
  33859. properties.resolvedUri = resolveUrl(main.uri, properties.uri);
  33860. }
  33861. });
  33862. };
  33863. /**
  33864. * Creates a main playlist wrapper to insert a sole media playlist into.
  33865. *
  33866. * @param {Object} media
  33867. * Media playlist
  33868. * @param {string} uri
  33869. * The media URI
  33870. *
  33871. * @return {Object}
  33872. * main playlist
  33873. */
  33874. const mainForMedia = (media, uri) => {
  33875. const id = createPlaylistID(0, uri);
  33876. const main = {
  33877. mediaGroups: {
  33878. 'AUDIO': {},
  33879. 'VIDEO': {},
  33880. 'CLOSED-CAPTIONS': {},
  33881. 'SUBTITLES': {}
  33882. },
  33883. uri: window.location.href,
  33884. resolvedUri: window.location.href,
  33885. playlists: [{
  33886. uri,
  33887. id,
  33888. resolvedUri: uri,
  33889. // m3u8-parser does not attach an attributes property to media playlists so make
  33890. // sure that the property is attached to avoid undefined reference errors
  33891. attributes: {}
  33892. }]
  33893. }; // set up ID reference
  33894. main.playlists[id] = main.playlists[0]; // URI reference added for backwards compatibility
  33895. main.playlists[uri] = main.playlists[0];
  33896. return main;
  33897. };
  33898. /**
  33899. * Does an in-place update of the main manifest to add updated playlist URI references
  33900. * as well as other properties needed by VHS that aren't included by the parser.
  33901. *
  33902. * @param {Object} main
  33903. * main manifest object
  33904. * @param {string} uri
  33905. * The source URI
  33906. * @param {function} createGroupID
  33907. * A function to determine how to create the groupID for mediaGroups
  33908. */
  33909. const addPropertiesToMain = (main, uri, createGroupID = groupID) => {
  33910. main.uri = uri;
  33911. for (let i = 0; i < main.playlists.length; i++) {
  33912. if (!main.playlists[i].uri) {
  33913. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  33914. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  33915. // TODO: consider adding dummy URIs in mpd-parser
  33916. const phonyUri = `placeholder-uri-${i}`;
  33917. main.playlists[i].uri = phonyUri;
  33918. }
  33919. }
  33920. const audioOnlyMain = isAudioOnly(main);
  33921. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  33922. // add a playlist array under properties
  33923. if (!properties.playlists || !properties.playlists.length) {
  33924. // If the manifest is audio only and this media group does not have a uri, check
  33925. // if the media group is located in the main list of playlists. If it is, don't add
  33926. // placeholder properties as it shouldn't be considered an alternate audio track.
  33927. if (audioOnlyMain && mediaType === 'AUDIO' && !properties.uri) {
  33928. for (let i = 0; i < main.playlists.length; i++) {
  33929. const p = main.playlists[i];
  33930. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  33931. return;
  33932. }
  33933. }
  33934. }
  33935. properties.playlists = [_extends$1({}, properties)];
  33936. }
  33937. properties.playlists.forEach(function (p, i) {
  33938. const groupId = createGroupID(mediaType, groupKey, labelKey, p);
  33939. const id = createPlaylistID(i, groupId);
  33940. if (p.uri) {
  33941. p.resolvedUri = p.resolvedUri || resolveUrl(main.uri, p.uri);
  33942. } else {
  33943. // DEPRECATED, this has been added to prevent a breaking change.
  33944. // previously we only ever had a single media group playlist, so
  33945. // we mark the first playlist uri without prepending the index as we used to
  33946. // ideally we would do all of the playlists the same way.
  33947. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  33948. // the placeholder again
  33949. p.resolvedUri = p.uri;
  33950. }
  33951. p.id = p.id || id; // add an empty attributes object, all playlists are
  33952. // expected to have this.
  33953. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  33954. main.playlists[p.id] = p;
  33955. main.playlists[p.uri] = p;
  33956. });
  33957. });
  33958. setupMediaPlaylists(main);
  33959. resolveMediaGroupUris(main);
  33960. };
  33961. /**
  33962. * @file playlist-loader.js
  33963. *
  33964. * A state machine that manages the loading, caching, and updating of
  33965. * M3U8 playlists.
  33966. *
  33967. */
  33968. const {
  33969. EventTarget: EventTarget$1
  33970. } = videojs;
  33971. const addLLHLSQueryDirectives = (uri, media) => {
  33972. if (media.endList || !media.serverControl) {
  33973. return uri;
  33974. }
  33975. const parameters = {};
  33976. if (media.serverControl.canBlockReload) {
  33977. const {
  33978. preloadSegment
  33979. } = media; // next msn is a zero based value, length is not.
  33980. let nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  33981. // that we are going to request a part of that preload segment.
  33982. // the logic below is used to determine that.
  33983. if (preloadSegment) {
  33984. const parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  33985. const nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  33986. // length of parts, then we know we had part preload hints
  33987. // and we need to add the _HLS_part= query
  33988. if (nextPart > -1 && nextPart !== parts.length - 1) {
  33989. // add existing parts to our preload hints
  33990. // eslint-disable-next-line
  33991. parameters._HLS_part = nextPart;
  33992. } // this if statement makes sure that we request the msn
  33993. // of the preload segment if:
  33994. // 1. the preload segment had parts (and was not yet a full segment)
  33995. // but was added to our segments array
  33996. // 2. the preload segment had preload hints for parts that are not in
  33997. // the manifest yet.
  33998. // in all other cases we want the segment after the preload segment
  33999. // which will be given by using media.segments.length because it is 1 based
  34000. // rather than 0 based.
  34001. if (nextPart > -1 || parts.length) {
  34002. nextMSN--;
  34003. }
  34004. } // add _HLS_msn= in front of any _HLS_part query
  34005. // eslint-disable-next-line
  34006. parameters._HLS_msn = nextMSN;
  34007. }
  34008. if (media.serverControl && media.serverControl.canSkipUntil) {
  34009. // add _HLS_skip= infront of all other queries.
  34010. // eslint-disable-next-line
  34011. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  34012. }
  34013. if (Object.keys(parameters).length) {
  34014. const parsedUri = new window.URL(uri);
  34015. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  34016. if (!parameters.hasOwnProperty(name)) {
  34017. return;
  34018. }
  34019. parsedUri.searchParams.set(name, parameters[name]);
  34020. });
  34021. uri = parsedUri.toString();
  34022. }
  34023. return uri;
  34024. };
  34025. /**
  34026. * Returns a new segment object with properties and
  34027. * the parts array merged.
  34028. *
  34029. * @param {Object} a the old segment
  34030. * @param {Object} b the new segment
  34031. *
  34032. * @return {Object} the merged segment
  34033. */
  34034. const updateSegment = (a, b) => {
  34035. if (!a) {
  34036. return b;
  34037. }
  34038. const result = merge(a, b); // if only the old segment has preload hints
  34039. // and the new one does not, remove preload hints.
  34040. if (a.preloadHints && !b.preloadHints) {
  34041. delete result.preloadHints;
  34042. } // if only the old segment has parts
  34043. // then the parts are no longer valid
  34044. if (a.parts && !b.parts) {
  34045. delete result.parts; // if both segments have parts
  34046. // copy part propeties from the old segment
  34047. // to the new one.
  34048. } else if (a.parts && b.parts) {
  34049. for (let i = 0; i < b.parts.length; i++) {
  34050. if (a.parts && a.parts[i]) {
  34051. result.parts[i] = merge(a.parts[i], b.parts[i]);
  34052. }
  34053. }
  34054. } // set skipped to false for segments that have
  34055. // have had information merged from the old segment.
  34056. if (!a.skipped && b.skipped) {
  34057. result.skipped = false;
  34058. } // set preload to false for segments that have
  34059. // had information added in the new segment.
  34060. if (a.preload && !b.preload) {
  34061. result.preload = false;
  34062. }
  34063. return result;
  34064. };
  34065. /**
  34066. * Returns a new array of segments that is the result of merging
  34067. * properties from an older list of segments onto an updated
  34068. * list. No properties on the updated playlist will be ovewritten.
  34069. *
  34070. * @param {Array} original the outdated list of segments
  34071. * @param {Array} update the updated list of segments
  34072. * @param {number=} offset the index of the first update
  34073. * segment in the original segment list. For non-live playlists,
  34074. * this should always be zero and does not need to be
  34075. * specified. For live playlists, it should be the difference
  34076. * between the media sequence numbers in the original and updated
  34077. * playlists.
  34078. * @return {Array} a list of merged segment objects
  34079. */
  34080. const updateSegments = (original, update, offset) => {
  34081. const oldSegments = original.slice();
  34082. const newSegments = update.slice();
  34083. offset = offset || 0;
  34084. const result = [];
  34085. let currentMap;
  34086. for (let newIndex = 0; newIndex < newSegments.length; newIndex++) {
  34087. const oldSegment = oldSegments[newIndex + offset];
  34088. const newSegment = newSegments[newIndex];
  34089. if (oldSegment) {
  34090. currentMap = oldSegment.map || currentMap;
  34091. result.push(updateSegment(oldSegment, newSegment));
  34092. } else {
  34093. // carry over map to new segment if it is missing
  34094. if (currentMap && !newSegment.map) {
  34095. newSegment.map = currentMap;
  34096. }
  34097. result.push(newSegment);
  34098. }
  34099. }
  34100. return result;
  34101. };
  34102. const resolveSegmentUris = (segment, baseUri) => {
  34103. // preloadSegment will not have a uri at all
  34104. // as the segment isn't actually in the manifest yet, only parts
  34105. if (!segment.resolvedUri && segment.uri) {
  34106. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  34107. }
  34108. if (segment.key && !segment.key.resolvedUri) {
  34109. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  34110. }
  34111. if (segment.map && !segment.map.resolvedUri) {
  34112. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  34113. }
  34114. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  34115. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  34116. }
  34117. if (segment.parts && segment.parts.length) {
  34118. segment.parts.forEach(p => {
  34119. if (p.resolvedUri) {
  34120. return;
  34121. }
  34122. p.resolvedUri = resolveUrl(baseUri, p.uri);
  34123. });
  34124. }
  34125. if (segment.preloadHints && segment.preloadHints.length) {
  34126. segment.preloadHints.forEach(p => {
  34127. if (p.resolvedUri) {
  34128. return;
  34129. }
  34130. p.resolvedUri = resolveUrl(baseUri, p.uri);
  34131. });
  34132. }
  34133. };
  34134. const getAllSegments = function (media) {
  34135. const segments = media.segments || [];
  34136. const preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  34137. // a usable segment, only include a preloadSegment that has
  34138. // parts.
  34139. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  34140. // if preloadHints has a MAP that means that the
  34141. // init segment is going to change. We cannot use any of the parts
  34142. // from this preload segment.
  34143. if (preloadSegment.preloadHints) {
  34144. for (let i = 0; i < preloadSegment.preloadHints.length; i++) {
  34145. if (preloadSegment.preloadHints[i].type === 'MAP') {
  34146. return segments;
  34147. }
  34148. }
  34149. } // set the duration for our preload segment to target duration.
  34150. preloadSegment.duration = media.targetDuration;
  34151. preloadSegment.preload = true;
  34152. segments.push(preloadSegment);
  34153. }
  34154. return segments;
  34155. }; // consider the playlist unchanged if the playlist object is the same or
  34156. // the number of segments is equal, the media sequence number is unchanged,
  34157. // and this playlist hasn't become the end of the playlist
  34158. const isPlaylistUnchanged = (a, b) => a === b || a.segments && b.segments && a.segments.length === b.segments.length && a.endList === b.endList && a.mediaSequence === b.mediaSequence && a.preloadSegment === b.preloadSegment;
  34159. /**
  34160. * Returns a new main playlist that is the result of merging an
  34161. * updated media playlist into the original version. If the
  34162. * updated media playlist does not match any of the playlist
  34163. * entries in the original main playlist, null is returned.
  34164. *
  34165. * @param {Object} main a parsed main M3U8 object
  34166. * @param {Object} media a parsed media M3U8 object
  34167. * @return {Object} a new object that represents the original
  34168. * main playlist with the updated media playlist merged in, or
  34169. * null if the merge produced no change.
  34170. */
  34171. const updateMain$1 = (main, newMedia, unchangedCheck = isPlaylistUnchanged) => {
  34172. const result = merge(main, {});
  34173. const oldMedia = result.playlists[newMedia.id];
  34174. if (!oldMedia) {
  34175. return null;
  34176. }
  34177. if (unchangedCheck(oldMedia, newMedia)) {
  34178. return null;
  34179. }
  34180. newMedia.segments = getAllSegments(newMedia);
  34181. const mergedPlaylist = merge(oldMedia, newMedia); // always use the new media's preload segment
  34182. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  34183. delete mergedPlaylist.preloadSegment;
  34184. } // if the update could overlap existing segment information, merge the two segment lists
  34185. if (oldMedia.segments) {
  34186. if (newMedia.skip) {
  34187. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  34188. // old properties into the new segments
  34189. for (let i = 0; i < newMedia.skip.skippedSegments; i++) {
  34190. newMedia.segments.unshift({
  34191. skipped: true
  34192. });
  34193. }
  34194. }
  34195. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  34196. } // resolve any segment URIs to prevent us from having to do it later
  34197. mergedPlaylist.segments.forEach(segment => {
  34198. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  34199. }); // TODO Right now in the playlists array there are two references to each playlist, one
  34200. // that is referenced by index, and one by URI. The index reference may no longer be
  34201. // necessary.
  34202. for (let i = 0; i < result.playlists.length; i++) {
  34203. if (result.playlists[i].id === newMedia.id) {
  34204. result.playlists[i] = mergedPlaylist;
  34205. }
  34206. }
  34207. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  34208. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  34209. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  34210. if (!properties.playlists) {
  34211. return;
  34212. }
  34213. for (let i = 0; i < properties.playlists.length; i++) {
  34214. if (newMedia.id === properties.playlists[i].id) {
  34215. properties.playlists[i] = mergedPlaylist;
  34216. }
  34217. }
  34218. });
  34219. return result;
  34220. };
  34221. /**
  34222. * Calculates the time to wait before refreshing a live playlist
  34223. *
  34224. * @param {Object} media
  34225. * The current media
  34226. * @param {boolean} update
  34227. * True if there were any updates from the last refresh, false otherwise
  34228. * @return {number}
  34229. * The time in ms to wait before refreshing the live playlist
  34230. */
  34231. const refreshDelay = (media, update) => {
  34232. const segments = media.segments || [];
  34233. const lastSegment = segments[segments.length - 1];
  34234. const lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  34235. const lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  34236. if (update && lastDuration) {
  34237. return lastDuration * 1000;
  34238. } // if the playlist is unchanged since the last reload or last segment duration
  34239. // cannot be determined, try again after half the target duration
  34240. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  34241. };
  34242. /**
  34243. * Load a playlist from a remote location
  34244. *
  34245. * @class PlaylistLoader
  34246. * @extends Stream
  34247. * @param {string|Object} src url or object of manifest
  34248. * @param {boolean} withCredentials the withCredentials xhr option
  34249. * @class
  34250. */
  34251. class PlaylistLoader extends EventTarget$1 {
  34252. constructor(src, vhs, options = {}) {
  34253. super();
  34254. if (!src) {
  34255. throw new Error('A non-empty playlist URL or object is required');
  34256. }
  34257. this.logger_ = logger('PlaylistLoader');
  34258. const {
  34259. withCredentials = false
  34260. } = options;
  34261. this.src = src;
  34262. this.vhs_ = vhs;
  34263. this.withCredentials = withCredentials;
  34264. const vhsOptions = vhs.options_;
  34265. this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  34266. this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  34267. this.llhls = vhsOptions && vhsOptions.llhls; // initialize the loader state
  34268. this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  34269. this.handleMediaupdatetimeout_ = this.handleMediaupdatetimeout_.bind(this);
  34270. this.on('mediaupdatetimeout', this.handleMediaupdatetimeout_);
  34271. }
  34272. handleMediaupdatetimeout_() {
  34273. if (this.state !== 'HAVE_METADATA') {
  34274. // only refresh the media playlist if no other activity is going on
  34275. return;
  34276. }
  34277. const media = this.media();
  34278. let uri = resolveUrl(this.main.uri, media.uri);
  34279. if (this.llhls) {
  34280. uri = addLLHLSQueryDirectives(uri, media);
  34281. }
  34282. this.state = 'HAVE_CURRENT_METADATA';
  34283. this.request = this.vhs_.xhr({
  34284. uri,
  34285. withCredentials: this.withCredentials
  34286. }, (error, req) => {
  34287. // disposed
  34288. if (!this.request) {
  34289. return;
  34290. }
  34291. if (error) {
  34292. return this.playlistRequestError(this.request, this.media(), 'HAVE_METADATA');
  34293. }
  34294. this.haveMetadata({
  34295. playlistString: this.request.responseText,
  34296. url: this.media().uri,
  34297. id: this.media().id
  34298. });
  34299. });
  34300. }
  34301. playlistRequestError(xhr, playlist, startingState) {
  34302. const {
  34303. uri,
  34304. id
  34305. } = playlist; // any in-flight request is now finished
  34306. this.request = null;
  34307. if (startingState) {
  34308. this.state = startingState;
  34309. }
  34310. this.error = {
  34311. playlist: this.main.playlists[id],
  34312. status: xhr.status,
  34313. message: `HLS playlist request error at URL: ${uri}.`,
  34314. responseText: xhr.responseText,
  34315. code: xhr.status >= 500 ? 4 : 2
  34316. };
  34317. this.trigger('error');
  34318. }
  34319. parseManifest_({
  34320. url,
  34321. manifestString
  34322. }) {
  34323. return parseManifest({
  34324. onwarn: ({
  34325. message
  34326. }) => this.logger_(`m3u8-parser warn for ${url}: ${message}`),
  34327. oninfo: ({
  34328. message
  34329. }) => this.logger_(`m3u8-parser info for ${url}: ${message}`),
  34330. manifestString,
  34331. customTagParsers: this.customTagParsers,
  34332. customTagMappers: this.customTagMappers,
  34333. llhls: this.llhls
  34334. });
  34335. }
  34336. /**
  34337. * Update the playlist loader's state in response to a new or updated playlist.
  34338. *
  34339. * @param {string} [playlistString]
  34340. * Playlist string (if playlistObject is not provided)
  34341. * @param {Object} [playlistObject]
  34342. * Playlist object (if playlistString is not provided)
  34343. * @param {string} url
  34344. * URL of playlist
  34345. * @param {string} id
  34346. * ID to use for playlist
  34347. */
  34348. haveMetadata({
  34349. playlistString,
  34350. playlistObject,
  34351. url,
  34352. id
  34353. }) {
  34354. // any in-flight request is now finished
  34355. this.request = null;
  34356. this.state = 'HAVE_METADATA';
  34357. const playlist = playlistObject || this.parseManifest_({
  34358. url,
  34359. manifestString: playlistString
  34360. });
  34361. playlist.lastRequest = Date.now();
  34362. setupMediaPlaylist({
  34363. playlist,
  34364. uri: url,
  34365. id
  34366. }); // merge this playlist into the main manifest
  34367. const update = updateMain$1(this.main, playlist);
  34368. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  34369. this.pendingMedia_ = null;
  34370. if (update) {
  34371. this.main = update;
  34372. this.media_ = this.main.playlists[id];
  34373. } else {
  34374. this.trigger('playlistunchanged');
  34375. }
  34376. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  34377. this.trigger('loadedplaylist');
  34378. }
  34379. /**
  34380. * Abort any outstanding work and clean up.
  34381. */
  34382. dispose() {
  34383. this.trigger('dispose');
  34384. this.stopRequest();
  34385. window.clearTimeout(this.mediaUpdateTimeout);
  34386. window.clearTimeout(this.finalRenditionTimeout);
  34387. this.off();
  34388. }
  34389. stopRequest() {
  34390. if (this.request) {
  34391. const oldRequest = this.request;
  34392. this.request = null;
  34393. oldRequest.onreadystatechange = null;
  34394. oldRequest.abort();
  34395. }
  34396. }
  34397. /**
  34398. * When called without any arguments, returns the currently
  34399. * active media playlist. When called with a single argument,
  34400. * triggers the playlist loader to asynchronously switch to the
  34401. * specified media playlist. Calling this method while the
  34402. * loader is in the HAVE_NOTHING causes an error to be emitted
  34403. * but otherwise has no effect.
  34404. *
  34405. * @param {Object=} playlist the parsed media playlist
  34406. * object to switch to
  34407. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  34408. *
  34409. * @return {Playlist} the current loaded media
  34410. */
  34411. media(playlist, shouldDelay) {
  34412. // getter
  34413. if (!playlist) {
  34414. return this.media_;
  34415. } // setter
  34416. if (this.state === 'HAVE_NOTHING') {
  34417. throw new Error('Cannot switch media playlist from ' + this.state);
  34418. } // find the playlist object if the target playlist has been
  34419. // specified by URI
  34420. if (typeof playlist === 'string') {
  34421. if (!this.main.playlists[playlist]) {
  34422. throw new Error('Unknown playlist URI: ' + playlist);
  34423. }
  34424. playlist = this.main.playlists[playlist];
  34425. }
  34426. window.clearTimeout(this.finalRenditionTimeout);
  34427. if (shouldDelay) {
  34428. const delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  34429. this.finalRenditionTimeout = window.setTimeout(this.media.bind(this, playlist, false), delay);
  34430. return;
  34431. }
  34432. const startingState = this.state;
  34433. const mediaChange = !this.media_ || playlist.id !== this.media_.id;
  34434. const mainPlaylistRef = this.main.playlists[playlist.id]; // switch to fully loaded playlists immediately
  34435. if (mainPlaylistRef && mainPlaylistRef.endList ||
  34436. // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  34437. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  34438. playlist.endList && playlist.segments.length) {
  34439. // abort outstanding playlist requests
  34440. if (this.request) {
  34441. this.request.onreadystatechange = null;
  34442. this.request.abort();
  34443. this.request = null;
  34444. }
  34445. this.state = 'HAVE_METADATA';
  34446. this.media_ = playlist; // trigger media change if the active media has been updated
  34447. if (mediaChange) {
  34448. this.trigger('mediachanging');
  34449. if (startingState === 'HAVE_MAIN_MANIFEST') {
  34450. // The initial playlist was a main manifest, and the first media selected was
  34451. // also provided (in the form of a resolved playlist object) as part of the
  34452. // source object (rather than just a URL). Therefore, since the media playlist
  34453. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  34454. // normal flow, and needs an explicit trigger here.
  34455. this.trigger('loadedmetadata');
  34456. } else {
  34457. this.trigger('mediachange');
  34458. }
  34459. }
  34460. return;
  34461. } // We update/set the timeout here so that live playlists
  34462. // that are not a media change will "start" the loader as expected.
  34463. // We expect that this function will start the media update timeout
  34464. // cycle again. This also prevents a playlist switch failure from
  34465. // causing us to stall during live.
  34466. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  34467. if (!mediaChange) {
  34468. return;
  34469. }
  34470. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  34471. if (this.request) {
  34472. if (playlist.resolvedUri === this.request.url) {
  34473. // requesting to switch to the same playlist multiple times
  34474. // has no effect after the first
  34475. return;
  34476. }
  34477. this.request.onreadystatechange = null;
  34478. this.request.abort();
  34479. this.request = null;
  34480. } // request the new playlist
  34481. if (this.media_) {
  34482. this.trigger('mediachanging');
  34483. }
  34484. this.pendingMedia_ = playlist;
  34485. this.request = this.vhs_.xhr({
  34486. uri: playlist.resolvedUri,
  34487. withCredentials: this.withCredentials
  34488. }, (error, req) => {
  34489. // disposed
  34490. if (!this.request) {
  34491. return;
  34492. }
  34493. playlist.lastRequest = Date.now();
  34494. playlist.resolvedUri = resolveManifestRedirect(playlist.resolvedUri, req);
  34495. if (error) {
  34496. return this.playlistRequestError(this.request, playlist, startingState);
  34497. }
  34498. this.haveMetadata({
  34499. playlistString: req.responseText,
  34500. url: playlist.uri,
  34501. id: playlist.id
  34502. }); // fire loadedmetadata the first time a media playlist is loaded
  34503. if (startingState === 'HAVE_MAIN_MANIFEST') {
  34504. this.trigger('loadedmetadata');
  34505. } else {
  34506. this.trigger('mediachange');
  34507. }
  34508. });
  34509. }
  34510. /**
  34511. * pause loading of the playlist
  34512. */
  34513. pause() {
  34514. if (this.mediaUpdateTimeout) {
  34515. window.clearTimeout(this.mediaUpdateTimeout);
  34516. this.mediaUpdateTimeout = null;
  34517. }
  34518. this.stopRequest();
  34519. if (this.state === 'HAVE_NOTHING') {
  34520. // If we pause the loader before any data has been retrieved, its as if we never
  34521. // started, so reset to an unstarted state.
  34522. this.started = false;
  34523. } // Need to restore state now that no activity is happening
  34524. if (this.state === 'SWITCHING_MEDIA') {
  34525. // if the loader was in the process of switching media, it should either return to
  34526. // HAVE_MAIN_MANIFEST or HAVE_METADATA depending on if the loader has loaded a media
  34527. // playlist yet. This is determined by the existence of loader.media_
  34528. if (this.media_) {
  34529. this.state = 'HAVE_METADATA';
  34530. } else {
  34531. this.state = 'HAVE_MAIN_MANIFEST';
  34532. }
  34533. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  34534. this.state = 'HAVE_METADATA';
  34535. }
  34536. }
  34537. /**
  34538. * start loading of the playlist
  34539. */
  34540. load(shouldDelay) {
  34541. if (this.mediaUpdateTimeout) {
  34542. window.clearTimeout(this.mediaUpdateTimeout);
  34543. this.mediaUpdateTimeout = null;
  34544. }
  34545. const media = this.media();
  34546. if (shouldDelay) {
  34547. const delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  34548. this.mediaUpdateTimeout = window.setTimeout(() => {
  34549. this.mediaUpdateTimeout = null;
  34550. this.load();
  34551. }, delay);
  34552. return;
  34553. }
  34554. if (!this.started) {
  34555. this.start();
  34556. return;
  34557. }
  34558. if (media && !media.endList) {
  34559. this.trigger('mediaupdatetimeout');
  34560. } else {
  34561. this.trigger('loadedplaylist');
  34562. }
  34563. }
  34564. updateMediaUpdateTimeout_(delay) {
  34565. if (this.mediaUpdateTimeout) {
  34566. window.clearTimeout(this.mediaUpdateTimeout);
  34567. this.mediaUpdateTimeout = null;
  34568. } // we only have use mediaupdatetimeout for live playlists.
  34569. if (!this.media() || this.media().endList) {
  34570. return;
  34571. }
  34572. this.mediaUpdateTimeout = window.setTimeout(() => {
  34573. this.mediaUpdateTimeout = null;
  34574. this.trigger('mediaupdatetimeout');
  34575. this.updateMediaUpdateTimeout_(delay);
  34576. }, delay);
  34577. }
  34578. /**
  34579. * start loading of the playlist
  34580. */
  34581. start() {
  34582. this.started = true;
  34583. if (typeof this.src === 'object') {
  34584. // in the case of an entirely constructed manifest object (meaning there's no actual
  34585. // manifest on a server), default the uri to the page's href
  34586. if (!this.src.uri) {
  34587. this.src.uri = window.location.href;
  34588. } // resolvedUri is added on internally after the initial request. Since there's no
  34589. // request for pre-resolved manifests, add on resolvedUri here.
  34590. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  34591. // request can be skipped (since the top level of the manifest, at a minimum, is
  34592. // already available as a parsed manifest object). However, if the manifest object
  34593. // represents a main playlist, some media playlists may need to be resolved before
  34594. // the starting segment list is available. Therefore, go directly to setup of the
  34595. // initial playlist, and let the normal flow continue from there.
  34596. //
  34597. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  34598. // that the first request is asynchronous.
  34599. setTimeout(() => {
  34600. this.setupInitialPlaylist(this.src);
  34601. }, 0);
  34602. return;
  34603. } // request the specified URL
  34604. this.request = this.vhs_.xhr({
  34605. uri: this.src,
  34606. withCredentials: this.withCredentials
  34607. }, (error, req) => {
  34608. // disposed
  34609. if (!this.request) {
  34610. return;
  34611. } // clear the loader's request reference
  34612. this.request = null;
  34613. if (error) {
  34614. this.error = {
  34615. status: req.status,
  34616. message: `HLS playlist request error at URL: ${this.src}.`,
  34617. responseText: req.responseText,
  34618. // MEDIA_ERR_NETWORK
  34619. code: 2
  34620. };
  34621. if (this.state === 'HAVE_NOTHING') {
  34622. this.started = false;
  34623. }
  34624. return this.trigger('error');
  34625. }
  34626. this.src = resolveManifestRedirect(this.src, req);
  34627. const manifest = this.parseManifest_({
  34628. manifestString: req.responseText,
  34629. url: this.src
  34630. });
  34631. this.setupInitialPlaylist(manifest);
  34632. });
  34633. }
  34634. srcUri() {
  34635. return typeof this.src === 'string' ? this.src : this.src.uri;
  34636. }
  34637. /**
  34638. * Given a manifest object that's either a main or media playlist, trigger the proper
  34639. * events and set the state of the playlist loader.
  34640. *
  34641. * If the manifest object represents a main playlist, `loadedplaylist` will be
  34642. * triggered to allow listeners to select a playlist. If none is selected, the loader
  34643. * will default to the first one in the playlists array.
  34644. *
  34645. * If the manifest object represents a media playlist, `loadedplaylist` will be
  34646. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  34647. *
  34648. * In the case of a media playlist, a main playlist object wrapper with one playlist
  34649. * will be created so that all logic can handle playlists in the same fashion (as an
  34650. * assumed manifest object schema).
  34651. *
  34652. * @param {Object} manifest
  34653. * The parsed manifest object
  34654. */
  34655. setupInitialPlaylist(manifest) {
  34656. this.state = 'HAVE_MAIN_MANIFEST';
  34657. if (manifest.playlists) {
  34658. this.main = manifest;
  34659. addPropertiesToMain(this.main, this.srcUri()); // If the initial main playlist has playlists wtih segments already resolved,
  34660. // then resolve URIs in advance, as they are usually done after a playlist request,
  34661. // which may not happen if the playlist is resolved.
  34662. manifest.playlists.forEach(playlist => {
  34663. playlist.segments = getAllSegments(playlist);
  34664. playlist.segments.forEach(segment => {
  34665. resolveSegmentUris(segment, playlist.resolvedUri);
  34666. });
  34667. });
  34668. this.trigger('loadedplaylist');
  34669. if (!this.request) {
  34670. // no media playlist was specifically selected so start
  34671. // from the first listed one
  34672. this.media(this.main.playlists[0]);
  34673. }
  34674. return;
  34675. } // In order to support media playlists passed in as vhs-json, the case where the uri
  34676. // is not provided as part of the manifest should be considered, and an appropriate
  34677. // default used.
  34678. const uri = this.srcUri() || window.location.href;
  34679. this.main = mainForMedia(manifest, uri);
  34680. this.haveMetadata({
  34681. playlistObject: manifest,
  34682. url: uri,
  34683. id: this.main.playlists[0].id
  34684. });
  34685. this.trigger('loadedmetadata');
  34686. }
  34687. }
  34688. /**
  34689. * @file xhr.js
  34690. */
  34691. const {
  34692. xhr: videojsXHR
  34693. } = videojs;
  34694. const callbackWrapper = function (request, error, response, callback) {
  34695. const reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  34696. if (!error && reqResponse) {
  34697. request.responseTime = Date.now();
  34698. request.roundTripTime = request.responseTime - request.requestTime;
  34699. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  34700. if (!request.bandwidth) {
  34701. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  34702. }
  34703. }
  34704. if (response.headers) {
  34705. request.responseHeaders = response.headers;
  34706. } // videojs.xhr now uses a specific code on the error
  34707. // object to signal that a request has timed out instead
  34708. // of setting a boolean on the request object
  34709. if (error && error.code === 'ETIMEDOUT') {
  34710. request.timedout = true;
  34711. } // videojs.xhr no longer considers status codes outside of 200 and 0
  34712. // (for file uris) to be errors, but the old XHR did, so emulate that
  34713. // behavior. Status 206 may be used in response to byterange requests.
  34714. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  34715. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  34716. }
  34717. callback(error, request);
  34718. };
  34719. const xhrFactory = function () {
  34720. const xhr = function XhrFunction(options, callback) {
  34721. // Add a default timeout
  34722. options = merge({
  34723. timeout: 45e3
  34724. }, options); // Allow an optional user-specified function to modify the option
  34725. // object before we construct the xhr request
  34726. const beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest;
  34727. if (beforeRequest && typeof beforeRequest === 'function') {
  34728. const newOptions = beforeRequest(options);
  34729. if (newOptions) {
  34730. options = newOptions;
  34731. }
  34732. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  34733. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  34734. const xhrMethod = videojs.Vhs.xhr.original === true ? videojsXHR : videojs.Vhs.xhr;
  34735. const request = xhrMethod(options, function (error, response) {
  34736. return callbackWrapper(request, error, response, callback);
  34737. });
  34738. const originalAbort = request.abort;
  34739. request.abort = function () {
  34740. request.aborted = true;
  34741. return originalAbort.apply(request, arguments);
  34742. };
  34743. request.uri = options.uri;
  34744. request.requestTime = Date.now();
  34745. return request;
  34746. };
  34747. xhr.original = true;
  34748. return xhr;
  34749. };
  34750. /**
  34751. * Turns segment byterange into a string suitable for use in
  34752. * HTTP Range requests
  34753. *
  34754. * @param {Object} byterange - an object with two values defining the start and end
  34755. * of a byte-range
  34756. */
  34757. const byterangeStr = function (byterange) {
  34758. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  34759. // header uses inclusive ranges
  34760. let byterangeEnd;
  34761. const byterangeStart = byterange.offset;
  34762. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  34763. byterangeEnd = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  34764. } else {
  34765. byterangeEnd = byterange.offset + byterange.length - 1;
  34766. }
  34767. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  34768. };
  34769. /**
  34770. * Defines headers for use in the xhr request for a particular segment.
  34771. *
  34772. * @param {Object} segment - a simplified copy of the segmentInfo object
  34773. * from SegmentLoader
  34774. */
  34775. const segmentXhrHeaders = function (segment) {
  34776. const headers = {};
  34777. if (segment.byterange) {
  34778. headers.Range = byterangeStr(segment.byterange);
  34779. }
  34780. return headers;
  34781. };
  34782. /**
  34783. * @file bin-utils.js
  34784. */
  34785. /**
  34786. * convert a TimeRange to text
  34787. *
  34788. * @param {TimeRange} range the timerange to use for conversion
  34789. * @param {number} i the iterator on the range to convert
  34790. * @return {string} the range in string format
  34791. */
  34792. const textRange = function (range, i) {
  34793. return range.start(i) + '-' + range.end(i);
  34794. };
  34795. /**
  34796. * format a number as hex string
  34797. *
  34798. * @param {number} e The number
  34799. * @param {number} i the iterator
  34800. * @return {string} the hex formatted number as a string
  34801. */
  34802. const formatHexString = function (e, i) {
  34803. const value = e.toString(16);
  34804. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  34805. };
  34806. const formatAsciiString = function (e) {
  34807. if (e >= 0x20 && e < 0x7e) {
  34808. return String.fromCharCode(e);
  34809. }
  34810. return '.';
  34811. };
  34812. /**
  34813. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  34814. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  34815. *
  34816. * @param {Object} message
  34817. * Object of properties and values to send to the web worker
  34818. * @return {Object}
  34819. * Modified message with TypedArray values expanded
  34820. * @function createTransferableMessage
  34821. */
  34822. const createTransferableMessage = function (message) {
  34823. const transferable = {};
  34824. Object.keys(message).forEach(key => {
  34825. const value = message[key];
  34826. if (isArrayBufferView(value)) {
  34827. transferable[key] = {
  34828. bytes: value.buffer,
  34829. byteOffset: value.byteOffset,
  34830. byteLength: value.byteLength
  34831. };
  34832. } else {
  34833. transferable[key] = value;
  34834. }
  34835. });
  34836. return transferable;
  34837. };
  34838. /**
  34839. * Returns a unique string identifier for a media initialization
  34840. * segment.
  34841. *
  34842. * @param {Object} initSegment
  34843. * the init segment object.
  34844. *
  34845. * @return {string} the generated init segment id
  34846. */
  34847. const initSegmentId = function (initSegment) {
  34848. const byterange = initSegment.byterange || {
  34849. length: Infinity,
  34850. offset: 0
  34851. };
  34852. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  34853. };
  34854. /**
  34855. * Returns a unique string identifier for a media segment key.
  34856. *
  34857. * @param {Object} key the encryption key
  34858. * @return {string} the unique id for the media segment key.
  34859. */
  34860. const segmentKeyId = function (key) {
  34861. return key.resolvedUri;
  34862. };
  34863. /**
  34864. * utils to help dump binary data to the console
  34865. *
  34866. * @param {Array|TypedArray} data
  34867. * data to dump to a string
  34868. *
  34869. * @return {string} the data as a hex string.
  34870. */
  34871. const hexDump = data => {
  34872. const bytes = Array.prototype.slice.call(data);
  34873. const step = 16;
  34874. let result = '';
  34875. let hex;
  34876. let ascii;
  34877. for (let j = 0; j < bytes.length / step; j++) {
  34878. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  34879. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  34880. result += hex + ' ' + ascii + '\n';
  34881. }
  34882. return result;
  34883. };
  34884. const tagDump = ({
  34885. bytes
  34886. }) => hexDump(bytes);
  34887. const textRanges = ranges => {
  34888. let result = '';
  34889. let i;
  34890. for (i = 0; i < ranges.length; i++) {
  34891. result += textRange(ranges, i) + ' ';
  34892. }
  34893. return result;
  34894. };
  34895. var utils = /*#__PURE__*/Object.freeze({
  34896. __proto__: null,
  34897. createTransferableMessage: createTransferableMessage,
  34898. initSegmentId: initSegmentId,
  34899. segmentKeyId: segmentKeyId,
  34900. hexDump: hexDump,
  34901. tagDump: tagDump,
  34902. textRanges: textRanges
  34903. });
  34904. // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  34905. // 25% was arbitrarily chosen, and may need to be refined over time.
  34906. const SEGMENT_END_FUDGE_PERCENT = 0.25;
  34907. /**
  34908. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  34909. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  34910. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  34911. *
  34912. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  34913. * point" (a point where we have a mapping from program time to player time, with player
  34914. * time being the post transmux start of the segment).
  34915. *
  34916. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  34917. *
  34918. * @param {number} playerTime the player time
  34919. * @param {Object} segment the segment which contains the player time
  34920. * @return {Date} program time
  34921. */
  34922. const playerTimeToProgramTime = (playerTime, segment) => {
  34923. if (!segment.dateTimeObject) {
  34924. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  34925. // be used to map the start of a segment with a real world time).
  34926. return null;
  34927. }
  34928. const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  34929. const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  34930. const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  34931. const offsetFromSegmentStart = playerTime - startOfSegment;
  34932. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  34933. };
  34934. const originalSegmentVideoDuration = videoTimingInfo => {
  34935. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  34936. };
  34937. /**
  34938. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  34939. * returned segment might be an estimate or an accurate match.
  34940. *
  34941. * @param {string} programTime The ISO-8601 programTime to find a match for
  34942. * @param {Object} playlist A playlist object to search within
  34943. */
  34944. const findSegmentForProgramTime = (programTime, playlist) => {
  34945. // Assumptions:
  34946. // - verifyProgramDateTimeTags has already been run
  34947. // - live streams have been started
  34948. let dateTimeObject;
  34949. try {
  34950. dateTimeObject = new Date(programTime);
  34951. } catch (e) {
  34952. return null;
  34953. }
  34954. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  34955. return null;
  34956. }
  34957. let segment = playlist.segments[0];
  34958. if (dateTimeObject < segment.dateTimeObject) {
  34959. // Requested time is before stream start.
  34960. return null;
  34961. }
  34962. for (let i = 0; i < playlist.segments.length - 1; i++) {
  34963. segment = playlist.segments[i];
  34964. const nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
  34965. if (dateTimeObject < nextSegmentStart) {
  34966. break;
  34967. }
  34968. }
  34969. const lastSegment = playlist.segments[playlist.segments.length - 1];
  34970. const lastSegmentStart = lastSegment.dateTimeObject;
  34971. const lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  34972. const lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  34973. if (dateTimeObject > lastSegmentEnd) {
  34974. // Beyond the end of the stream, or our best guess of the end of the stream.
  34975. return null;
  34976. }
  34977. if (dateTimeObject > lastSegmentStart) {
  34978. segment = lastSegment;
  34979. }
  34980. return {
  34981. segment,
  34982. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  34983. // Although, given that all segments have accurate date time objects, the segment
  34984. // selected should be accurate, unless the video has been transmuxed at some point
  34985. // (determined by the presence of the videoTimingInfo object), the segment's "player
  34986. // time" (the start time in the player) can't be considered accurate.
  34987. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  34988. };
  34989. };
  34990. /**
  34991. * Finds a segment that contains the given player time(in seconds).
  34992. *
  34993. * @param {number} time The player time to find a match for
  34994. * @param {Object} playlist A playlist object to search within
  34995. */
  34996. const findSegmentForPlayerTime = (time, playlist) => {
  34997. // Assumptions:
  34998. // - there will always be a segment.duration
  34999. // - we can start from zero
  35000. // - segments are in time order
  35001. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  35002. return null;
  35003. }
  35004. let segmentEnd = 0;
  35005. let segment;
  35006. for (let i = 0; i < playlist.segments.length; i++) {
  35007. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  35008. // should contain the most accurate values we have for the segment's player times.
  35009. //
  35010. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  35011. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  35012. // calculate an end value.
  35013. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  35014. if (time <= segmentEnd) {
  35015. break;
  35016. }
  35017. }
  35018. const lastSegment = playlist.segments[playlist.segments.length - 1];
  35019. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  35020. // The time requested is beyond the stream end.
  35021. return null;
  35022. }
  35023. if (time > segmentEnd) {
  35024. // The time is within or beyond the last segment.
  35025. //
  35026. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  35027. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  35028. // Technically, because the duration value is only an estimate, the time may still
  35029. // exist in the last segment, however, there isn't enough information to make even
  35030. // a reasonable estimate.
  35031. return null;
  35032. }
  35033. segment = lastSegment;
  35034. }
  35035. return {
  35036. segment,
  35037. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  35038. // Because videoTimingInfo is only set after transmux, it is the only way to get
  35039. // accurate timing values.
  35040. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  35041. };
  35042. };
  35043. /**
  35044. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  35045. * If the offset returned is positive, the programTime occurs after the
  35046. * comparisonTimestamp.
  35047. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  35048. *
  35049. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  35050. * @param {string} programTime The programTime as an ISO-8601 string
  35051. * @return {number} offset
  35052. */
  35053. const getOffsetFromTimestamp = (comparisonTimeStamp, programTime) => {
  35054. let segmentDateTime;
  35055. let programDateTime;
  35056. try {
  35057. segmentDateTime = new Date(comparisonTimeStamp);
  35058. programDateTime = new Date(programTime);
  35059. } catch (e) {// TODO handle error
  35060. }
  35061. const segmentTimeEpoch = segmentDateTime.getTime();
  35062. const programTimeEpoch = programDateTime.getTime();
  35063. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  35064. };
  35065. /**
  35066. * Checks that all segments in this playlist have programDateTime tags.
  35067. *
  35068. * @param {Object} playlist A playlist object
  35069. */
  35070. const verifyProgramDateTimeTags = playlist => {
  35071. if (!playlist.segments || playlist.segments.length === 0) {
  35072. return false;
  35073. }
  35074. for (let i = 0; i < playlist.segments.length; i++) {
  35075. const segment = playlist.segments[i];
  35076. if (!segment.dateTimeObject) {
  35077. return false;
  35078. }
  35079. }
  35080. return true;
  35081. };
  35082. /**
  35083. * Returns the programTime of the media given a playlist and a playerTime.
  35084. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  35085. * If the segments containing the time requested have not been buffered yet, an estimate
  35086. * may be returned to the callback.
  35087. *
  35088. * @param {Object} args
  35089. * @param {Object} args.playlist A playlist object to search within
  35090. * @param {number} time A playerTime in seconds
  35091. * @param {Function} callback(err, programTime)
  35092. * @return {string} err.message A detailed error message
  35093. * @return {Object} programTime
  35094. * @return {number} programTime.mediaSeconds The streamTime in seconds
  35095. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  35096. */
  35097. const getProgramTime = ({
  35098. playlist,
  35099. time = undefined,
  35100. callback
  35101. }) => {
  35102. if (!callback) {
  35103. throw new Error('getProgramTime: callback must be provided');
  35104. }
  35105. if (!playlist || time === undefined) {
  35106. return callback({
  35107. message: 'getProgramTime: playlist and time must be provided'
  35108. });
  35109. }
  35110. const matchedSegment = findSegmentForPlayerTime(time, playlist);
  35111. if (!matchedSegment) {
  35112. return callback({
  35113. message: 'valid programTime was not found'
  35114. });
  35115. }
  35116. if (matchedSegment.type === 'estimate') {
  35117. return callback({
  35118. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  35119. seekTime: matchedSegment.estimatedStart
  35120. });
  35121. }
  35122. const programTimeObject = {
  35123. mediaSeconds: time
  35124. };
  35125. const programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  35126. if (programTime) {
  35127. programTimeObject.programDateTime = programTime.toISOString();
  35128. }
  35129. return callback(null, programTimeObject);
  35130. };
  35131. /**
  35132. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  35133. *
  35134. * @param {Object} args
  35135. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  35136. * @param {Object} args.playlist A playlist to look within
  35137. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  35138. * @param {Function} args.seekTo A method to perform a seek
  35139. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  35140. * @param {Object} args.tech The tech to seek on
  35141. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  35142. * @return {string} err.message A detailed error message
  35143. * @return {number} newTime The exact time that was seeked to in seconds
  35144. */
  35145. const seekToProgramTime = ({
  35146. programTime,
  35147. playlist,
  35148. retryCount = 2,
  35149. seekTo,
  35150. pauseAfterSeek = true,
  35151. tech,
  35152. callback
  35153. }) => {
  35154. if (!callback) {
  35155. throw new Error('seekToProgramTime: callback must be provided');
  35156. }
  35157. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  35158. return callback({
  35159. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  35160. });
  35161. }
  35162. if (!playlist.endList && !tech.hasStarted_) {
  35163. return callback({
  35164. message: 'player must be playing a live stream to start buffering'
  35165. });
  35166. }
  35167. if (!verifyProgramDateTimeTags(playlist)) {
  35168. return callback({
  35169. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  35170. });
  35171. }
  35172. const matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  35173. if (!matchedSegment) {
  35174. return callback({
  35175. message: `${programTime} was not found in the stream`
  35176. });
  35177. }
  35178. const segment = matchedSegment.segment;
  35179. const mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  35180. if (matchedSegment.type === 'estimate') {
  35181. // we've run out of retries
  35182. if (retryCount === 0) {
  35183. return callback({
  35184. message: `${programTime} is not buffered yet. Try again`
  35185. });
  35186. }
  35187. seekTo(matchedSegment.estimatedStart + mediaOffset);
  35188. tech.one('seeked', () => {
  35189. seekToProgramTime({
  35190. programTime,
  35191. playlist,
  35192. retryCount: retryCount - 1,
  35193. seekTo,
  35194. pauseAfterSeek,
  35195. tech,
  35196. callback
  35197. });
  35198. });
  35199. return;
  35200. } // Since the segment.start value is determined from the buffered end or ending time
  35201. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  35202. // modifications.
  35203. const seekToTime = segment.start + mediaOffset;
  35204. const seekedCallback = () => {
  35205. return callback(null, tech.currentTime());
  35206. }; // listen for seeked event
  35207. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  35208. if (pauseAfterSeek) {
  35209. tech.pause();
  35210. }
  35211. seekTo(seekToTime);
  35212. };
  35213. // which will only happen if the request is complete.
  35214. const callbackOnCompleted = (request, cb) => {
  35215. if (request.readyState === 4) {
  35216. return cb();
  35217. }
  35218. return;
  35219. };
  35220. const containerRequest = (uri, xhr, cb) => {
  35221. let bytes = [];
  35222. let id3Offset;
  35223. let finished = false;
  35224. const endRequestAndCallback = function (err, req, type, _bytes) {
  35225. req.abort();
  35226. finished = true;
  35227. return cb(err, req, type, _bytes);
  35228. };
  35229. const progressListener = function (error, request) {
  35230. if (finished) {
  35231. return;
  35232. }
  35233. if (error) {
  35234. return endRequestAndCallback(error, request, '', bytes);
  35235. } // grap the new part of content that was just downloaded
  35236. const newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  35237. bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
  35238. id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
  35239. // or we need at least two bytes after an id3Offset
  35240. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  35241. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  35242. }
  35243. const type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  35244. // to see the second sync byte, wait until we have enough data
  35245. // before declaring it ts
  35246. if (type === 'ts' && bytes.length < 188) {
  35247. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  35248. } // this may be an unsynced ts segment
  35249. // wait for 376 bytes before detecting no container
  35250. if (!type && bytes.length < 376) {
  35251. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  35252. }
  35253. return endRequestAndCallback(null, request, type, bytes);
  35254. };
  35255. const options = {
  35256. uri,
  35257. beforeSend(request) {
  35258. // this forces the browser to pass the bytes to us unprocessed
  35259. request.overrideMimeType('text/plain; charset=x-user-defined');
  35260. request.addEventListener('progress', function ({
  35261. total,
  35262. loaded
  35263. }) {
  35264. return callbackWrapper(request, null, {
  35265. statusCode: request.status
  35266. }, progressListener);
  35267. });
  35268. }
  35269. };
  35270. const request = xhr(options, function (error, response) {
  35271. return callbackWrapper(request, error, response, progressListener);
  35272. });
  35273. return request;
  35274. };
  35275. const {
  35276. EventTarget
  35277. } = videojs;
  35278. const dashPlaylistUnchanged = function (a, b) {
  35279. if (!isPlaylistUnchanged(a, b)) {
  35280. return false;
  35281. } // for dash the above check will often return true in scenarios where
  35282. // the playlist actually has changed because mediaSequence isn't a
  35283. // dash thing, and we often set it to 1. So if the playlists have the same amount
  35284. // of segments we return true.
  35285. // So for dash we need to make sure that the underlying segments are different.
  35286. // if sidx changed then the playlists are different.
  35287. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  35288. return false;
  35289. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  35290. return false;
  35291. } // one or the other does not have segments
  35292. // there was a change.
  35293. if (a.segments && !b.segments || !a.segments && b.segments) {
  35294. return false;
  35295. } // neither has segments nothing changed
  35296. if (!a.segments && !b.segments) {
  35297. return true;
  35298. } // check segments themselves
  35299. for (let i = 0; i < a.segments.length; i++) {
  35300. const aSegment = a.segments[i];
  35301. const bSegment = b.segments[i]; // if uris are different between segments there was a change
  35302. if (aSegment.uri !== bSegment.uri) {
  35303. return false;
  35304. } // neither segment has a byterange, there will be no byterange change.
  35305. if (!aSegment.byterange && !bSegment.byterange) {
  35306. continue;
  35307. }
  35308. const aByterange = aSegment.byterange;
  35309. const bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  35310. if (aByterange && !bByterange || !aByterange && bByterange) {
  35311. return false;
  35312. } // if both segments have byterange with different offsets, there was a change.
  35313. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  35314. return false;
  35315. }
  35316. } // if everything was the same with segments, this is the same playlist.
  35317. return true;
  35318. };
  35319. /**
  35320. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  35321. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  35322. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  35323. * periods without continuous playback this function may need modification as well as the parser.
  35324. */
  35325. const dashGroupId = (type, group, label, playlist) => {
  35326. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  35327. const playlistId = playlist.attributes.NAME || label;
  35328. return `placeholder-uri-${type}-${group}-${playlistId}`;
  35329. };
  35330. /**
  35331. * Parses the main XML string and updates playlist URI references.
  35332. *
  35333. * @param {Object} config
  35334. * Object of arguments
  35335. * @param {string} config.mainXml
  35336. * The mpd XML
  35337. * @param {string} config.srcUrl
  35338. * The mpd URL
  35339. * @param {Date} config.clientOffset
  35340. * A time difference between server and client
  35341. * @param {Object} config.sidxMapping
  35342. * SIDX mappings for moof/mdat URIs and byte ranges
  35343. * @return {Object}
  35344. * The parsed mpd manifest object
  35345. */
  35346. const parseMainXml = ({
  35347. mainXml,
  35348. srcUrl,
  35349. clientOffset,
  35350. sidxMapping,
  35351. previousManifest
  35352. }) => {
  35353. const manifest = parse(mainXml, {
  35354. manifestUri: srcUrl,
  35355. clientOffset,
  35356. sidxMapping,
  35357. previousManifest
  35358. });
  35359. addPropertiesToMain(manifest, srcUrl, dashGroupId);
  35360. return manifest;
  35361. };
  35362. /**
  35363. * Removes any mediaGroup labels that no longer exist in the newMain
  35364. *
  35365. * @param {Object} update
  35366. * The previous mpd object being updated
  35367. * @param {Object} newMain
  35368. * The new mpd object
  35369. */
  35370. const removeOldMediaGroupLabels = (update, newMain) => {
  35371. forEachMediaGroup(update, (properties, type, group, label) => {
  35372. if (!(label in newMain.mediaGroups[type][group])) {
  35373. delete update.mediaGroups[type][group][label];
  35374. }
  35375. });
  35376. };
  35377. /**
  35378. * Returns a new main manifest that is the result of merging an updated main manifest
  35379. * into the original version.
  35380. *
  35381. * @param {Object} oldMain
  35382. * The old parsed mpd object
  35383. * @param {Object} newMain
  35384. * The updated parsed mpd object
  35385. * @return {Object}
  35386. * A new object representing the original main manifest with the updated media
  35387. * playlists merged in
  35388. */
  35389. const updateMain = (oldMain, newMain, sidxMapping) => {
  35390. let noChanges = true;
  35391. let update = merge(oldMain, {
  35392. // These are top level properties that can be updated
  35393. duration: newMain.duration,
  35394. minimumUpdatePeriod: newMain.minimumUpdatePeriod,
  35395. timelineStarts: newMain.timelineStarts
  35396. }); // First update the playlists in playlist list
  35397. for (let i = 0; i < newMain.playlists.length; i++) {
  35398. const playlist = newMain.playlists[i];
  35399. if (playlist.sidx) {
  35400. const sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  35401. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  35402. addSidxSegmentsToPlaylist$1(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  35403. }
  35404. }
  35405. const playlistUpdate = updateMain$1(update, playlist, dashPlaylistUnchanged);
  35406. if (playlistUpdate) {
  35407. update = playlistUpdate;
  35408. noChanges = false;
  35409. }
  35410. } // Then update media group playlists
  35411. forEachMediaGroup(newMain, (properties, type, group, label) => {
  35412. if (properties.playlists && properties.playlists.length) {
  35413. const id = properties.playlists[0].id;
  35414. const playlistUpdate = updateMain$1(update, properties.playlists[0], dashPlaylistUnchanged);
  35415. if (playlistUpdate) {
  35416. update = playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  35417. if (!(label in update.mediaGroups[type][group])) {
  35418. update.mediaGroups[type][group][label] = properties;
  35419. } // update the playlist reference within media groups
  35420. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  35421. noChanges = false;
  35422. }
  35423. }
  35424. }); // remove mediaGroup labels and references that no longer exist in the newMain
  35425. removeOldMediaGroupLabels(update, newMain);
  35426. if (newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  35427. noChanges = false;
  35428. }
  35429. if (noChanges) {
  35430. return null;
  35431. }
  35432. return update;
  35433. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  35434. // If the SIDXs have maps, the two maps should match,
  35435. // both `a` and `b` missing SIDXs is considered matching.
  35436. // If `a` or `b` but not both have a map, they aren't matching.
  35437. const equivalentSidx = (a, b) => {
  35438. const neitherMap = Boolean(!a.map && !b.map);
  35439. const equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  35440. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  35441. }; // exported for testing
  35442. const compareSidxEntry = (playlists, oldSidxMapping) => {
  35443. const newSidxMapping = {};
  35444. for (const id in playlists) {
  35445. const playlist = playlists[id];
  35446. const currentSidxInfo = playlist.sidx;
  35447. if (currentSidxInfo) {
  35448. const key = generateSidxKey(currentSidxInfo);
  35449. if (!oldSidxMapping[key]) {
  35450. break;
  35451. }
  35452. const savedSidxInfo = oldSidxMapping[key].sidxInfo;
  35453. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  35454. newSidxMapping[key] = oldSidxMapping[key];
  35455. }
  35456. }
  35457. }
  35458. return newSidxMapping;
  35459. };
  35460. /**
  35461. * A function that filters out changed items as they need to be requested separately.
  35462. *
  35463. * The method is exported for testing
  35464. *
  35465. * @param {Object} main the parsed mpd XML returned via mpd-parser
  35466. * @param {Object} oldSidxMapping the SIDX to compare against
  35467. */
  35468. const filterChangedSidxMappings = (main, oldSidxMapping) => {
  35469. const videoSidx = compareSidxEntry(main.playlists, oldSidxMapping);
  35470. let mediaGroupSidx = videoSidx;
  35471. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  35472. if (properties.playlists && properties.playlists.length) {
  35473. const playlists = properties.playlists;
  35474. mediaGroupSidx = merge(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  35475. }
  35476. });
  35477. return mediaGroupSidx;
  35478. };
  35479. class DashPlaylistLoader extends EventTarget {
  35480. // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  35481. // playlist loader setups from media groups will expect to be able to pass a playlist
  35482. // (since there aren't external URLs to media playlists with DASH)
  35483. constructor(srcUrlOrPlaylist, vhs, options = {}, mainPlaylistLoader) {
  35484. super();
  35485. this.mainPlaylistLoader_ = mainPlaylistLoader || this;
  35486. if (!mainPlaylistLoader) {
  35487. this.isMain_ = true;
  35488. }
  35489. const {
  35490. withCredentials = false
  35491. } = options;
  35492. this.vhs_ = vhs;
  35493. this.withCredentials = withCredentials;
  35494. if (!srcUrlOrPlaylist) {
  35495. throw new Error('A non-empty playlist URL or object is required');
  35496. } // event naming?
  35497. this.on('minimumUpdatePeriod', () => {
  35498. this.refreshXml_();
  35499. }); // live playlist staleness timeout
  35500. this.on('mediaupdatetimeout', () => {
  35501. this.refreshMedia_(this.media().id);
  35502. });
  35503. this.state = 'HAVE_NOTHING';
  35504. this.loadedPlaylists_ = {};
  35505. this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  35506. // The mainPlaylistLoader will be created with a string
  35507. if (this.isMain_) {
  35508. this.mainPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  35509. // once multi-period is refactored
  35510. this.mainPlaylistLoader_.sidxMapping_ = {};
  35511. } else {
  35512. this.childPlaylist_ = srcUrlOrPlaylist;
  35513. }
  35514. }
  35515. requestErrored_(err, request, startingState) {
  35516. // disposed
  35517. if (!this.request) {
  35518. return true;
  35519. } // pending request is cleared
  35520. this.request = null;
  35521. if (err) {
  35522. // use the provided error object or create one
  35523. // based on the request/response
  35524. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  35525. status: request.status,
  35526. message: 'DASH request error at URL: ' + request.uri,
  35527. response: request.response,
  35528. // MEDIA_ERR_NETWORK
  35529. code: 2
  35530. };
  35531. if (startingState) {
  35532. this.state = startingState;
  35533. }
  35534. this.trigger('error');
  35535. return true;
  35536. }
  35537. }
  35538. /**
  35539. * Verify that the container of the sidx segment can be parsed
  35540. * and if it can, get and parse that segment.
  35541. */
  35542. addSidxSegments_(playlist, startingState, cb) {
  35543. const sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  35544. if (!playlist.sidx || !sidxKey || this.mainPlaylistLoader_.sidxMapping_[sidxKey]) {
  35545. // keep this function async
  35546. this.mediaRequest_ = window.setTimeout(() => cb(false), 0);
  35547. return;
  35548. } // resolve the segment URL relative to the playlist
  35549. const uri = resolveManifestRedirect(playlist.sidx.resolvedUri);
  35550. const fin = (err, request) => {
  35551. if (this.requestErrored_(err, request, startingState)) {
  35552. return;
  35553. }
  35554. const sidxMapping = this.mainPlaylistLoader_.sidxMapping_;
  35555. let sidx;
  35556. try {
  35557. sidx = parseSidx_1(toUint8(request.response).subarray(8));
  35558. } catch (e) {
  35559. // sidx parsing failed.
  35560. this.requestErrored_(e, request, startingState);
  35561. return;
  35562. }
  35563. sidxMapping[sidxKey] = {
  35564. sidxInfo: playlist.sidx,
  35565. sidx
  35566. };
  35567. addSidxSegmentsToPlaylist$1(playlist, sidx, playlist.sidx.resolvedUri);
  35568. return cb(true);
  35569. };
  35570. this.request = containerRequest(uri, this.vhs_.xhr, (err, request, container, bytes) => {
  35571. if (err) {
  35572. return fin(err, request);
  35573. }
  35574. if (!container || container !== 'mp4') {
  35575. return fin({
  35576. status: request.status,
  35577. message: `Unsupported ${container || 'unknown'} container type for sidx segment at URL: ${uri}`,
  35578. // response is just bytes in this case
  35579. // but we really don't want to return that.
  35580. response: '',
  35581. playlist,
  35582. internal: true,
  35583. playlistExclusionDuration: Infinity,
  35584. // MEDIA_ERR_NETWORK
  35585. code: 2
  35586. }, request);
  35587. } // if we already downloaded the sidx bytes in the container request, use them
  35588. const {
  35589. offset,
  35590. length
  35591. } = playlist.sidx.byterange;
  35592. if (bytes.length >= length + offset) {
  35593. return fin(err, {
  35594. response: bytes.subarray(offset, offset + length),
  35595. status: request.status,
  35596. uri: request.uri
  35597. });
  35598. } // otherwise request sidx bytes
  35599. this.request = this.vhs_.xhr({
  35600. uri,
  35601. responseType: 'arraybuffer',
  35602. headers: segmentXhrHeaders({
  35603. byterange: playlist.sidx.byterange
  35604. })
  35605. }, fin);
  35606. });
  35607. }
  35608. dispose() {
  35609. this.trigger('dispose');
  35610. this.stopRequest();
  35611. this.loadedPlaylists_ = {};
  35612. window.clearTimeout(this.minimumUpdatePeriodTimeout_);
  35613. window.clearTimeout(this.mediaRequest_);
  35614. window.clearTimeout(this.mediaUpdateTimeout);
  35615. this.mediaUpdateTimeout = null;
  35616. this.mediaRequest_ = null;
  35617. this.minimumUpdatePeriodTimeout_ = null;
  35618. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  35619. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  35620. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  35621. }
  35622. this.off();
  35623. }
  35624. hasPendingRequest() {
  35625. return this.request || this.mediaRequest_;
  35626. }
  35627. stopRequest() {
  35628. if (this.request) {
  35629. const oldRequest = this.request;
  35630. this.request = null;
  35631. oldRequest.onreadystatechange = null;
  35632. oldRequest.abort();
  35633. }
  35634. }
  35635. media(playlist) {
  35636. // getter
  35637. if (!playlist) {
  35638. return this.media_;
  35639. } // setter
  35640. if (this.state === 'HAVE_NOTHING') {
  35641. throw new Error('Cannot switch media playlist from ' + this.state);
  35642. }
  35643. const startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  35644. if (typeof playlist === 'string') {
  35645. if (!this.mainPlaylistLoader_.main.playlists[playlist]) {
  35646. throw new Error('Unknown playlist URI: ' + playlist);
  35647. }
  35648. playlist = this.mainPlaylistLoader_.main.playlists[playlist];
  35649. }
  35650. const mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  35651. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  35652. this.state = 'HAVE_METADATA';
  35653. this.media_ = playlist; // trigger media change if the active media has been updated
  35654. if (mediaChange) {
  35655. this.trigger('mediachanging');
  35656. this.trigger('mediachange');
  35657. }
  35658. return;
  35659. } // switching to the active playlist is a no-op
  35660. if (!mediaChange) {
  35661. return;
  35662. } // switching from an already loaded playlist
  35663. if (this.media_) {
  35664. this.trigger('mediachanging');
  35665. }
  35666. this.addSidxSegments_(playlist, startingState, sidxChanged => {
  35667. // everything is ready just continue to haveMetadata
  35668. this.haveMetadata({
  35669. startingState,
  35670. playlist
  35671. });
  35672. });
  35673. }
  35674. haveMetadata({
  35675. startingState,
  35676. playlist
  35677. }) {
  35678. this.state = 'HAVE_METADATA';
  35679. this.loadedPlaylists_[playlist.id] = playlist;
  35680. this.mediaRequest_ = null; // This will trigger loadedplaylist
  35681. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  35682. // to resolve setup of media groups
  35683. if (startingState === 'HAVE_MAIN_MANIFEST') {
  35684. this.trigger('loadedmetadata');
  35685. } else {
  35686. // trigger media change if the active media has been updated
  35687. this.trigger('mediachange');
  35688. }
  35689. }
  35690. pause() {
  35691. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  35692. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  35693. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  35694. }
  35695. this.stopRequest();
  35696. window.clearTimeout(this.mediaUpdateTimeout);
  35697. this.mediaUpdateTimeout = null;
  35698. if (this.isMain_) {
  35699. window.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_);
  35700. this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  35701. }
  35702. if (this.state === 'HAVE_NOTHING') {
  35703. // If we pause the loader before any data has been retrieved, its as if we never
  35704. // started, so reset to an unstarted state.
  35705. this.started = false;
  35706. }
  35707. }
  35708. load(isFinalRendition) {
  35709. window.clearTimeout(this.mediaUpdateTimeout);
  35710. this.mediaUpdateTimeout = null;
  35711. const media = this.media();
  35712. if (isFinalRendition) {
  35713. const delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  35714. this.mediaUpdateTimeout = window.setTimeout(() => this.load(), delay);
  35715. return;
  35716. } // because the playlists are internal to the manifest, load should either load the
  35717. // main manifest, or do nothing but trigger an event
  35718. if (!this.started) {
  35719. this.start();
  35720. return;
  35721. }
  35722. if (media && !media.endList) {
  35723. // Check to see if this is the main loader and the MUP was cleared (this happens
  35724. // when the loader was paused). `media` should be set at this point since one is always
  35725. // set during `start()`.
  35726. if (this.isMain_ && !this.minimumUpdatePeriodTimeout_) {
  35727. // Trigger minimumUpdatePeriod to refresh the main manifest
  35728. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  35729. this.updateMinimumUpdatePeriodTimeout_();
  35730. }
  35731. this.trigger('mediaupdatetimeout');
  35732. } else {
  35733. this.trigger('loadedplaylist');
  35734. }
  35735. }
  35736. start() {
  35737. this.started = true; // We don't need to request the main manifest again
  35738. // Call this asynchronously to match the xhr request behavior below
  35739. if (!this.isMain_) {
  35740. this.mediaRequest_ = window.setTimeout(() => this.haveMain_(), 0);
  35741. return;
  35742. }
  35743. this.requestMain_((req, mainChanged) => {
  35744. this.haveMain_();
  35745. if (!this.hasPendingRequest() && !this.media_) {
  35746. this.media(this.mainPlaylistLoader_.main.playlists[0]);
  35747. }
  35748. });
  35749. }
  35750. requestMain_(cb) {
  35751. this.request = this.vhs_.xhr({
  35752. uri: this.mainPlaylistLoader_.srcUrl,
  35753. withCredentials: this.withCredentials
  35754. }, (error, req) => {
  35755. if (this.requestErrored_(error, req)) {
  35756. if (this.state === 'HAVE_NOTHING') {
  35757. this.started = false;
  35758. }
  35759. return;
  35760. }
  35761. const mainChanged = req.responseText !== this.mainPlaylistLoader_.mainXml_;
  35762. this.mainPlaylistLoader_.mainXml_ = req.responseText;
  35763. if (req.responseHeaders && req.responseHeaders.date) {
  35764. this.mainLoaded_ = Date.parse(req.responseHeaders.date);
  35765. } else {
  35766. this.mainLoaded_ = Date.now();
  35767. }
  35768. this.mainPlaylistLoader_.srcUrl = resolveManifestRedirect(this.mainPlaylistLoader_.srcUrl, req);
  35769. if (mainChanged) {
  35770. this.handleMain_();
  35771. this.syncClientServerClock_(() => {
  35772. return cb(req, mainChanged);
  35773. });
  35774. return;
  35775. }
  35776. return cb(req, mainChanged);
  35777. });
  35778. }
  35779. /**
  35780. * Parses the main xml for UTCTiming node to sync the client clock to the server
  35781. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  35782. *
  35783. * @param {Function} done
  35784. * Function to call when clock sync has completed
  35785. */
  35786. syncClientServerClock_(done) {
  35787. const utcTiming = parseUTCTiming(this.mainPlaylistLoader_.mainXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  35788. // server clock
  35789. if (utcTiming === null) {
  35790. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  35791. return done();
  35792. }
  35793. if (utcTiming.method === 'DIRECT') {
  35794. this.mainPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  35795. return done();
  35796. }
  35797. this.request = this.vhs_.xhr({
  35798. uri: resolveUrl(this.mainPlaylistLoader_.srcUrl, utcTiming.value),
  35799. method: utcTiming.method,
  35800. withCredentials: this.withCredentials
  35801. }, (error, req) => {
  35802. // disposed
  35803. if (!this.request) {
  35804. return;
  35805. }
  35806. if (error) {
  35807. // sync request failed, fall back to using date header from mpd
  35808. // TODO: log warning
  35809. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  35810. return done();
  35811. }
  35812. let serverTime;
  35813. if (utcTiming.method === 'HEAD') {
  35814. if (!req.responseHeaders || !req.responseHeaders.date) {
  35815. // expected date header not preset, fall back to using date header from mpd
  35816. // TODO: log warning
  35817. serverTime = this.mainLoaded_;
  35818. } else {
  35819. serverTime = Date.parse(req.responseHeaders.date);
  35820. }
  35821. } else {
  35822. serverTime = Date.parse(req.responseText);
  35823. }
  35824. this.mainPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  35825. done();
  35826. });
  35827. }
  35828. haveMain_() {
  35829. this.state = 'HAVE_MAIN_MANIFEST';
  35830. if (this.isMain_) {
  35831. // We have the main playlist at this point, so
  35832. // trigger this to allow PlaylistController
  35833. // to make an initial playlist selection
  35834. this.trigger('loadedplaylist');
  35835. } else if (!this.media_) {
  35836. // no media playlist was specifically selected so select
  35837. // the one the child playlist loader was created with
  35838. this.media(this.childPlaylist_);
  35839. }
  35840. }
  35841. handleMain_() {
  35842. // clear media request
  35843. this.mediaRequest_ = null;
  35844. const oldMain = this.mainPlaylistLoader_.main;
  35845. let newMain = parseMainXml({
  35846. mainXml: this.mainPlaylistLoader_.mainXml_,
  35847. srcUrl: this.mainPlaylistLoader_.srcUrl,
  35848. clientOffset: this.mainPlaylistLoader_.clientOffset_,
  35849. sidxMapping: this.mainPlaylistLoader_.sidxMapping_,
  35850. previousManifest: oldMain
  35851. }); // if we have an old main to compare the new main against
  35852. if (oldMain) {
  35853. newMain = updateMain(oldMain, newMain, this.mainPlaylistLoader_.sidxMapping_);
  35854. } // only update main if we have a new main
  35855. this.mainPlaylistLoader_.main = newMain ? newMain : oldMain;
  35856. const location = this.mainPlaylistLoader_.main.locations && this.mainPlaylistLoader_.main.locations[0];
  35857. if (location && location !== this.mainPlaylistLoader_.srcUrl) {
  35858. this.mainPlaylistLoader_.srcUrl = location;
  35859. }
  35860. if (!oldMain || newMain && newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  35861. this.updateMinimumUpdatePeriodTimeout_();
  35862. }
  35863. return Boolean(newMain);
  35864. }
  35865. updateMinimumUpdatePeriodTimeout_() {
  35866. const mpl = this.mainPlaylistLoader_; // cancel any pending creation of mup on media
  35867. // a new one will be added if needed.
  35868. if (mpl.createMupOnMedia_) {
  35869. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  35870. mpl.createMupOnMedia_ = null;
  35871. } // clear any pending timeouts
  35872. if (mpl.minimumUpdatePeriodTimeout_) {
  35873. window.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  35874. mpl.minimumUpdatePeriodTimeout_ = null;
  35875. }
  35876. let mup = mpl.main && mpl.main.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  35877. // MPD has no future validity, so a new one will need to be acquired when new
  35878. // media segments are to be made available. Thus, we use the target duration
  35879. // in this case
  35880. if (mup === 0) {
  35881. if (mpl.media()) {
  35882. mup = mpl.media().targetDuration * 1000;
  35883. } else {
  35884. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  35885. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  35886. }
  35887. } // if minimumUpdatePeriod is invalid or <= zero, which
  35888. // can happen when a live video becomes VOD. skip timeout
  35889. // creation.
  35890. if (typeof mup !== 'number' || mup <= 0) {
  35891. if (mup < 0) {
  35892. this.logger_(`found invalid minimumUpdatePeriod of ${mup}, not setting a timeout`);
  35893. }
  35894. return;
  35895. }
  35896. this.createMUPTimeout_(mup);
  35897. }
  35898. createMUPTimeout_(mup) {
  35899. const mpl = this.mainPlaylistLoader_;
  35900. mpl.minimumUpdatePeriodTimeout_ = window.setTimeout(() => {
  35901. mpl.minimumUpdatePeriodTimeout_ = null;
  35902. mpl.trigger('minimumUpdatePeriod');
  35903. mpl.createMUPTimeout_(mup);
  35904. }, mup);
  35905. }
  35906. /**
  35907. * Sends request to refresh the main xml and updates the parsed main manifest
  35908. */
  35909. refreshXml_() {
  35910. this.requestMain_((req, mainChanged) => {
  35911. if (!mainChanged) {
  35912. return;
  35913. }
  35914. if (this.media_) {
  35915. this.media_ = this.mainPlaylistLoader_.main.playlists[this.media_.id];
  35916. } // This will filter out updated sidx info from the mapping
  35917. this.mainPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.sidxMapping_);
  35918. this.addSidxSegments_(this.media(), this.state, sidxChanged => {
  35919. // TODO: do we need to reload the current playlist?
  35920. this.refreshMedia_(this.media().id);
  35921. });
  35922. });
  35923. }
  35924. /**
  35925. * Refreshes the media playlist by re-parsing the main xml and updating playlist
  35926. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  35927. * from the main loader.
  35928. */
  35929. refreshMedia_(mediaID) {
  35930. if (!mediaID) {
  35931. throw new Error('refreshMedia_ must take a media id');
  35932. } // for main we have to reparse the main xml
  35933. // to re-create segments based on current timing values
  35934. // which may change media. We only skip updating the main manifest
  35935. // if this is the first time this.media_ is being set.
  35936. // as main was just parsed in that case.
  35937. if (this.media_ && this.isMain_) {
  35938. this.handleMain_();
  35939. }
  35940. const playlists = this.mainPlaylistLoader_.main.playlists;
  35941. const mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  35942. if (mediaChanged) {
  35943. this.media_ = playlists[mediaID];
  35944. } else {
  35945. this.trigger('playlistunchanged');
  35946. }
  35947. if (!this.mediaUpdateTimeout) {
  35948. const createMediaUpdateTimeout = () => {
  35949. if (this.media().endList) {
  35950. return;
  35951. }
  35952. this.mediaUpdateTimeout = window.setTimeout(() => {
  35953. this.trigger('mediaupdatetimeout');
  35954. createMediaUpdateTimeout();
  35955. }, refreshDelay(this.media(), Boolean(mediaChanged)));
  35956. };
  35957. createMediaUpdateTimeout();
  35958. }
  35959. this.trigger('loadedplaylist');
  35960. }
  35961. }
  35962. var Config = {
  35963. GOAL_BUFFER_LENGTH: 30,
  35964. MAX_GOAL_BUFFER_LENGTH: 60,
  35965. BACK_BUFFER_LENGTH: 30,
  35966. GOAL_BUFFER_LENGTH_RATE: 1,
  35967. // 0.5 MB/s
  35968. INITIAL_BANDWIDTH: 4194304,
  35969. // A fudge factor to apply to advertised playlist bitrates to account for
  35970. // temporary flucations in client bandwidth
  35971. BANDWIDTH_VARIANCE: 1.2,
  35972. // How much of the buffer must be filled before we consider upswitching
  35973. BUFFER_LOW_WATER_LINE: 0,
  35974. MAX_BUFFER_LOW_WATER_LINE: 30,
  35975. // TODO: Remove this when experimentalBufferBasedABR is removed
  35976. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  35977. BUFFER_LOW_WATER_LINE_RATE: 1,
  35978. // If the buffer is greater than the high water line, we won't switch down
  35979. BUFFER_HIGH_WATER_LINE: 30
  35980. };
  35981. const stringToArrayBuffer = string => {
  35982. const view = new Uint8Array(new ArrayBuffer(string.length));
  35983. for (let i = 0; i < string.length; i++) {
  35984. view[i] = string.charCodeAt(i);
  35985. }
  35986. return view.buffer;
  35987. };
  35988. /* global Blob, BlobBuilder, Worker */
  35989. // unify worker interface
  35990. const browserWorkerPolyFill = function (workerObj) {
  35991. // node only supports on/off
  35992. workerObj.on = workerObj.addEventListener;
  35993. workerObj.off = workerObj.removeEventListener;
  35994. return workerObj;
  35995. };
  35996. const createObjectURL = function (str) {
  35997. try {
  35998. return URL.createObjectURL(new Blob([str], {
  35999. type: 'application/javascript'
  36000. }));
  36001. } catch (e) {
  36002. const blob = new BlobBuilder();
  36003. blob.append(str);
  36004. return URL.createObjectURL(blob.getBlob());
  36005. }
  36006. };
  36007. const factory = function (code) {
  36008. return function () {
  36009. const objectUrl = createObjectURL(code);
  36010. const worker = browserWorkerPolyFill(new Worker(objectUrl));
  36011. worker.objURL = objectUrl;
  36012. const terminate = worker.terminate;
  36013. worker.on = worker.addEventListener;
  36014. worker.off = worker.removeEventListener;
  36015. worker.terminate = function () {
  36016. URL.revokeObjectURL(objectUrl);
  36017. return terminate.call(this);
  36018. };
  36019. return worker;
  36020. };
  36021. };
  36022. const transform = function (code) {
  36023. return `var browserWorkerPolyFill = ${browserWorkerPolyFill.toString()};\n` + 'browserWorkerPolyFill(self);\n' + code;
  36024. };
  36025. const getWorkerString = function (fn) {
  36026. return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
  36027. };
  36028. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  36029. const workerCode$1 = transform(getWorkerString(function () {
  36030. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  36031. /**
  36032. * mux.js
  36033. *
  36034. * Copyright (c) Brightcove
  36035. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  36036. *
  36037. * A lightweight readable stream implemention that handles event dispatching.
  36038. * Objects that inherit from streams should call init in their constructors.
  36039. */
  36040. var Stream$8 = function () {
  36041. this.init = function () {
  36042. var listeners = {};
  36043. /**
  36044. * Add a listener for a specified event type.
  36045. * @param type {string} the event name
  36046. * @param listener {function} the callback to be invoked when an event of
  36047. * the specified type occurs
  36048. */
  36049. this.on = function (type, listener) {
  36050. if (!listeners[type]) {
  36051. listeners[type] = [];
  36052. }
  36053. listeners[type] = listeners[type].concat(listener);
  36054. };
  36055. /**
  36056. * Remove a listener for a specified event type.
  36057. * @param type {string} the event name
  36058. * @param listener {function} a function previously registered for this
  36059. * type of event through `on`
  36060. */
  36061. this.off = function (type, listener) {
  36062. var index;
  36063. if (!listeners[type]) {
  36064. return false;
  36065. }
  36066. index = listeners[type].indexOf(listener);
  36067. listeners[type] = listeners[type].slice();
  36068. listeners[type].splice(index, 1);
  36069. return index > -1;
  36070. };
  36071. /**
  36072. * Trigger an event of the specified type on this stream. Any additional
  36073. * arguments to this function are passed as parameters to event listeners.
  36074. * @param type {string} the event name
  36075. */
  36076. this.trigger = function (type) {
  36077. var callbacks, i, length, args;
  36078. callbacks = listeners[type];
  36079. if (!callbacks) {
  36080. return;
  36081. } // Slicing the arguments on every invocation of this method
  36082. // can add a significant amount of overhead. Avoid the
  36083. // intermediate object creation for the common case of a
  36084. // single callback argument
  36085. if (arguments.length === 2) {
  36086. length = callbacks.length;
  36087. for (i = 0; i < length; ++i) {
  36088. callbacks[i].call(this, arguments[1]);
  36089. }
  36090. } else {
  36091. args = [];
  36092. i = arguments.length;
  36093. for (i = 1; i < arguments.length; ++i) {
  36094. args.push(arguments[i]);
  36095. }
  36096. length = callbacks.length;
  36097. for (i = 0; i < length; ++i) {
  36098. callbacks[i].apply(this, args);
  36099. }
  36100. }
  36101. };
  36102. /**
  36103. * Destroys the stream and cleans up.
  36104. */
  36105. this.dispose = function () {
  36106. listeners = {};
  36107. };
  36108. };
  36109. };
  36110. /**
  36111. * Forwards all `data` events on this stream to the destination stream. The
  36112. * destination stream should provide a method `push` to receive the data
  36113. * events as they arrive.
  36114. * @param destination {stream} the stream that will receive all `data` events
  36115. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  36116. * when the current stream emits a 'done' event
  36117. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  36118. */
  36119. Stream$8.prototype.pipe = function (destination) {
  36120. this.on('data', function (data) {
  36121. destination.push(data);
  36122. });
  36123. this.on('done', function (flushSource) {
  36124. destination.flush(flushSource);
  36125. });
  36126. this.on('partialdone', function (flushSource) {
  36127. destination.partialFlush(flushSource);
  36128. });
  36129. this.on('endedtimeline', function (flushSource) {
  36130. destination.endTimeline(flushSource);
  36131. });
  36132. this.on('reset', function (flushSource) {
  36133. destination.reset(flushSource);
  36134. });
  36135. return destination;
  36136. }; // Default stream functions that are expected to be overridden to perform
  36137. // actual work. These are provided by the prototype as a sort of no-op
  36138. // implementation so that we don't have to check for their existence in the
  36139. // `pipe` function above.
  36140. Stream$8.prototype.push = function (data) {
  36141. this.trigger('data', data);
  36142. };
  36143. Stream$8.prototype.flush = function (flushSource) {
  36144. this.trigger('done', flushSource);
  36145. };
  36146. Stream$8.prototype.partialFlush = function (flushSource) {
  36147. this.trigger('partialdone', flushSource);
  36148. };
  36149. Stream$8.prototype.endTimeline = function (flushSource) {
  36150. this.trigger('endedtimeline', flushSource);
  36151. };
  36152. Stream$8.prototype.reset = function (flushSource) {
  36153. this.trigger('reset', flushSource);
  36154. };
  36155. var stream = Stream$8;
  36156. var MAX_UINT32$1 = Math.pow(2, 32);
  36157. var getUint64$3 = function (uint8) {
  36158. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  36159. var value;
  36160. if (dv.getBigUint64) {
  36161. value = dv.getBigUint64(0);
  36162. if (value < Number.MAX_SAFE_INTEGER) {
  36163. return Number(value);
  36164. }
  36165. return value;
  36166. }
  36167. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  36168. };
  36169. var numbers = {
  36170. getUint64: getUint64$3,
  36171. MAX_UINT32: MAX_UINT32$1
  36172. };
  36173. /**
  36174. * mux.js
  36175. *
  36176. * Copyright (c) Brightcove
  36177. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  36178. *
  36179. * Functions that generate fragmented MP4s suitable for use with Media
  36180. * Source Extensions.
  36181. */
  36182. var MAX_UINT32 = numbers.MAX_UINT32;
  36183. 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
  36184. (function () {
  36185. var i;
  36186. types = {
  36187. avc1: [],
  36188. // codingname
  36189. avcC: [],
  36190. btrt: [],
  36191. dinf: [],
  36192. dref: [],
  36193. esds: [],
  36194. ftyp: [],
  36195. hdlr: [],
  36196. mdat: [],
  36197. mdhd: [],
  36198. mdia: [],
  36199. mfhd: [],
  36200. minf: [],
  36201. moof: [],
  36202. moov: [],
  36203. mp4a: [],
  36204. // codingname
  36205. mvex: [],
  36206. mvhd: [],
  36207. pasp: [],
  36208. sdtp: [],
  36209. smhd: [],
  36210. stbl: [],
  36211. stco: [],
  36212. stsc: [],
  36213. stsd: [],
  36214. stsz: [],
  36215. stts: [],
  36216. styp: [],
  36217. tfdt: [],
  36218. tfhd: [],
  36219. traf: [],
  36220. trak: [],
  36221. trun: [],
  36222. trex: [],
  36223. tkhd: [],
  36224. vmhd: []
  36225. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  36226. // don't throw an error
  36227. if (typeof Uint8Array === 'undefined') {
  36228. return;
  36229. }
  36230. for (i in types) {
  36231. if (types.hasOwnProperty(i)) {
  36232. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  36233. }
  36234. }
  36235. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  36236. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  36237. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  36238. VIDEO_HDLR = new Uint8Array([0x00,
  36239. // version 0
  36240. 0x00, 0x00, 0x00,
  36241. // flags
  36242. 0x00, 0x00, 0x00, 0x00,
  36243. // pre_defined
  36244. 0x76, 0x69, 0x64, 0x65,
  36245. // handler_type: 'vide'
  36246. 0x00, 0x00, 0x00, 0x00,
  36247. // reserved
  36248. 0x00, 0x00, 0x00, 0x00,
  36249. // reserved
  36250. 0x00, 0x00, 0x00, 0x00,
  36251. // reserved
  36252. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  36253. ]);
  36254. AUDIO_HDLR = new Uint8Array([0x00,
  36255. // version 0
  36256. 0x00, 0x00, 0x00,
  36257. // flags
  36258. 0x00, 0x00, 0x00, 0x00,
  36259. // pre_defined
  36260. 0x73, 0x6f, 0x75, 0x6e,
  36261. // handler_type: 'soun'
  36262. 0x00, 0x00, 0x00, 0x00,
  36263. // reserved
  36264. 0x00, 0x00, 0x00, 0x00,
  36265. // reserved
  36266. 0x00, 0x00, 0x00, 0x00,
  36267. // reserved
  36268. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  36269. ]);
  36270. HDLR_TYPES = {
  36271. video: VIDEO_HDLR,
  36272. audio: AUDIO_HDLR
  36273. };
  36274. DREF = new Uint8Array([0x00,
  36275. // version 0
  36276. 0x00, 0x00, 0x00,
  36277. // flags
  36278. 0x00, 0x00, 0x00, 0x01,
  36279. // entry_count
  36280. 0x00, 0x00, 0x00, 0x0c,
  36281. // entry_size
  36282. 0x75, 0x72, 0x6c, 0x20,
  36283. // 'url' type
  36284. 0x00,
  36285. // version 0
  36286. 0x00, 0x00, 0x01 // entry_flags
  36287. ]);
  36288. SMHD = new Uint8Array([0x00,
  36289. // version
  36290. 0x00, 0x00, 0x00,
  36291. // flags
  36292. 0x00, 0x00,
  36293. // balance, 0 means centered
  36294. 0x00, 0x00 // reserved
  36295. ]);
  36296. STCO = new Uint8Array([0x00,
  36297. // version
  36298. 0x00, 0x00, 0x00,
  36299. // flags
  36300. 0x00, 0x00, 0x00, 0x00 // entry_count
  36301. ]);
  36302. STSC = STCO;
  36303. STSZ = new Uint8Array([0x00,
  36304. // version
  36305. 0x00, 0x00, 0x00,
  36306. // flags
  36307. 0x00, 0x00, 0x00, 0x00,
  36308. // sample_size
  36309. 0x00, 0x00, 0x00, 0x00 // sample_count
  36310. ]);
  36311. STTS = STCO;
  36312. VMHD = new Uint8Array([0x00,
  36313. // version
  36314. 0x00, 0x00, 0x01,
  36315. // flags
  36316. 0x00, 0x00,
  36317. // graphicsmode
  36318. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  36319. ]);
  36320. })();
  36321. box = function (type) {
  36322. var payload = [],
  36323. size = 0,
  36324. i,
  36325. result,
  36326. view;
  36327. for (i = 1; i < arguments.length; i++) {
  36328. payload.push(arguments[i]);
  36329. }
  36330. i = payload.length; // calculate the total size we need to allocate
  36331. while (i--) {
  36332. size += payload[i].byteLength;
  36333. }
  36334. result = new Uint8Array(size + 8);
  36335. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  36336. view.setUint32(0, result.byteLength);
  36337. result.set(type, 4); // copy the payload into the result
  36338. for (i = 0, size = 8; i < payload.length; i++) {
  36339. result.set(payload[i], size);
  36340. size += payload[i].byteLength;
  36341. }
  36342. return result;
  36343. };
  36344. dinf = function () {
  36345. return box(types.dinf, box(types.dref, DREF));
  36346. };
  36347. esds = function (track) {
  36348. return box(types.esds, new Uint8Array([0x00,
  36349. // version
  36350. 0x00, 0x00, 0x00,
  36351. // flags
  36352. // ES_Descriptor
  36353. 0x03,
  36354. // tag, ES_DescrTag
  36355. 0x19,
  36356. // length
  36357. 0x00, 0x00,
  36358. // ES_ID
  36359. 0x00,
  36360. // streamDependenceFlag, URL_flag, reserved, streamPriority
  36361. // DecoderConfigDescriptor
  36362. 0x04,
  36363. // tag, DecoderConfigDescrTag
  36364. 0x11,
  36365. // length
  36366. 0x40,
  36367. // object type
  36368. 0x15,
  36369. // streamType
  36370. 0x00, 0x06, 0x00,
  36371. // bufferSizeDB
  36372. 0x00, 0x00, 0xda, 0xc0,
  36373. // maxBitrate
  36374. 0x00, 0x00, 0xda, 0xc0,
  36375. // avgBitrate
  36376. // DecoderSpecificInfo
  36377. 0x05,
  36378. // tag, DecoderSpecificInfoTag
  36379. 0x02,
  36380. // length
  36381. // ISO/IEC 14496-3, AudioSpecificConfig
  36382. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  36383. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  36384. ]));
  36385. };
  36386. ftyp = function () {
  36387. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  36388. };
  36389. hdlr = function (type) {
  36390. return box(types.hdlr, HDLR_TYPES[type]);
  36391. };
  36392. mdat = function (data) {
  36393. return box(types.mdat, data);
  36394. };
  36395. mdhd = function (track) {
  36396. var result = new Uint8Array([0x00,
  36397. // version 0
  36398. 0x00, 0x00, 0x00,
  36399. // flags
  36400. 0x00, 0x00, 0x00, 0x02,
  36401. // creation_time
  36402. 0x00, 0x00, 0x00, 0x03,
  36403. // modification_time
  36404. 0x00, 0x01, 0x5f, 0x90,
  36405. // timescale, 90,000 "ticks" per second
  36406. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF,
  36407. // duration
  36408. 0x55, 0xc4,
  36409. // 'und' language (undetermined)
  36410. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  36411. // defined. The sample rate can be parsed out of an ADTS header, for
  36412. // instance.
  36413. if (track.samplerate) {
  36414. result[12] = track.samplerate >>> 24 & 0xFF;
  36415. result[13] = track.samplerate >>> 16 & 0xFF;
  36416. result[14] = track.samplerate >>> 8 & 0xFF;
  36417. result[15] = track.samplerate & 0xFF;
  36418. }
  36419. return box(types.mdhd, result);
  36420. };
  36421. mdia = function (track) {
  36422. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  36423. };
  36424. mfhd = function (sequenceNumber) {
  36425. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  36426. // flags
  36427. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  36428. ]));
  36429. };
  36430. minf = function (track) {
  36431. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  36432. };
  36433. moof = function (sequenceNumber, tracks) {
  36434. var trackFragments = [],
  36435. i = tracks.length; // build traf boxes for each track fragment
  36436. while (i--) {
  36437. trackFragments[i] = traf(tracks[i]);
  36438. }
  36439. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  36440. };
  36441. /**
  36442. * Returns a movie box.
  36443. * @param tracks {array} the tracks associated with this movie
  36444. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  36445. */
  36446. moov = function (tracks) {
  36447. var i = tracks.length,
  36448. boxes = [];
  36449. while (i--) {
  36450. boxes[i] = trak(tracks[i]);
  36451. }
  36452. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  36453. };
  36454. mvex = function (tracks) {
  36455. var i = tracks.length,
  36456. boxes = [];
  36457. while (i--) {
  36458. boxes[i] = trex(tracks[i]);
  36459. }
  36460. return box.apply(null, [types.mvex].concat(boxes));
  36461. };
  36462. mvhd = function (duration) {
  36463. var bytes = new Uint8Array([0x00,
  36464. // version 0
  36465. 0x00, 0x00, 0x00,
  36466. // flags
  36467. 0x00, 0x00, 0x00, 0x01,
  36468. // creation_time
  36469. 0x00, 0x00, 0x00, 0x02,
  36470. // modification_time
  36471. 0x00, 0x01, 0x5f, 0x90,
  36472. // timescale, 90,000 "ticks" per second
  36473. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF,
  36474. // duration
  36475. 0x00, 0x01, 0x00, 0x00,
  36476. // 1.0 rate
  36477. 0x01, 0x00,
  36478. // 1.0 volume
  36479. 0x00, 0x00,
  36480. // reserved
  36481. 0x00, 0x00, 0x00, 0x00,
  36482. // reserved
  36483. 0x00, 0x00, 0x00, 0x00,
  36484. // reserved
  36485. 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,
  36486. // transformation: unity matrix
  36487. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  36488. // pre_defined
  36489. 0xff, 0xff, 0xff, 0xff // next_track_ID
  36490. ]);
  36491. return box(types.mvhd, bytes);
  36492. };
  36493. sdtp = function (track) {
  36494. var samples = track.samples || [],
  36495. bytes = new Uint8Array(4 + samples.length),
  36496. flags,
  36497. i; // leave the full box header (4 bytes) all zero
  36498. // write the sample table
  36499. for (i = 0; i < samples.length; i++) {
  36500. flags = samples[i].flags;
  36501. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  36502. }
  36503. return box(types.sdtp, bytes);
  36504. };
  36505. stbl = function (track) {
  36506. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  36507. };
  36508. (function () {
  36509. var videoSample, audioSample;
  36510. stsd = function (track) {
  36511. return box(types.stsd, new Uint8Array([0x00,
  36512. // version 0
  36513. 0x00, 0x00, 0x00,
  36514. // flags
  36515. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  36516. };
  36517. videoSample = function (track) {
  36518. var sps = track.sps || [],
  36519. pps = track.pps || [],
  36520. sequenceParameterSets = [],
  36521. pictureParameterSets = [],
  36522. i,
  36523. avc1Box; // assemble the SPSs
  36524. for (i = 0; i < sps.length; i++) {
  36525. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  36526. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  36527. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  36528. } // assemble the PPSs
  36529. for (i = 0; i < pps.length; i++) {
  36530. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  36531. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  36532. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  36533. }
  36534. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  36535. // reserved
  36536. 0x00, 0x01,
  36537. // data_reference_index
  36538. 0x00, 0x00,
  36539. // pre_defined
  36540. 0x00, 0x00,
  36541. // reserved
  36542. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  36543. // pre_defined
  36544. (track.width & 0xff00) >> 8, track.width & 0xff,
  36545. // width
  36546. (track.height & 0xff00) >> 8, track.height & 0xff,
  36547. // height
  36548. 0x00, 0x48, 0x00, 0x00,
  36549. // horizresolution
  36550. 0x00, 0x48, 0x00, 0x00,
  36551. // vertresolution
  36552. 0x00, 0x00, 0x00, 0x00,
  36553. // reserved
  36554. 0x00, 0x01,
  36555. // frame_count
  36556. 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,
  36557. // compressorname
  36558. 0x00, 0x18,
  36559. // depth = 24
  36560. 0x11, 0x11 // pre_defined = -1
  36561. ]), box(types.avcC, new Uint8Array([0x01,
  36562. // configurationVersion
  36563. track.profileIdc,
  36564. // AVCProfileIndication
  36565. track.profileCompatibility,
  36566. // profile_compatibility
  36567. track.levelIdc,
  36568. // AVCLevelIndication
  36569. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  36570. ].concat([sps.length],
  36571. // numOfSequenceParameterSets
  36572. sequenceParameterSets,
  36573. // "SPS"
  36574. [pps.length],
  36575. // numOfPictureParameterSets
  36576. pictureParameterSets // "PPS"
  36577. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  36578. // bufferSizeDB
  36579. 0x00, 0x2d, 0xc6, 0xc0,
  36580. // maxBitrate
  36581. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  36582. ]))];
  36583. if (track.sarRatio) {
  36584. var hSpacing = track.sarRatio[0],
  36585. vSpacing = track.sarRatio[1];
  36586. 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])));
  36587. }
  36588. return box.apply(null, avc1Box);
  36589. };
  36590. audioSample = function (track) {
  36591. return box(types.mp4a, new Uint8Array([
  36592. // SampleEntry, ISO/IEC 14496-12
  36593. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  36594. // reserved
  36595. 0x00, 0x01,
  36596. // data_reference_index
  36597. // AudioSampleEntry, ISO/IEC 14496-12
  36598. 0x00, 0x00, 0x00, 0x00,
  36599. // reserved
  36600. 0x00, 0x00, 0x00, 0x00,
  36601. // reserved
  36602. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff,
  36603. // channelcount
  36604. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff,
  36605. // samplesize
  36606. 0x00, 0x00,
  36607. // pre_defined
  36608. 0x00, 0x00,
  36609. // reserved
  36610. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  36611. // MP4AudioSampleEntry, ISO/IEC 14496-14
  36612. ]), esds(track));
  36613. };
  36614. })();
  36615. tkhd = function (track) {
  36616. var result = new Uint8Array([0x00,
  36617. // version 0
  36618. 0x00, 0x00, 0x07,
  36619. // flags
  36620. 0x00, 0x00, 0x00, 0x00,
  36621. // creation_time
  36622. 0x00, 0x00, 0x00, 0x00,
  36623. // modification_time
  36624. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,
  36625. // track_ID
  36626. 0x00, 0x00, 0x00, 0x00,
  36627. // reserved
  36628. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF,
  36629. // duration
  36630. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  36631. // reserved
  36632. 0x00, 0x00,
  36633. // layer
  36634. 0x00, 0x00,
  36635. // alternate_group
  36636. 0x01, 0x00,
  36637. // non-audio track volume
  36638. 0x00, 0x00,
  36639. // reserved
  36640. 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,
  36641. // transformation: unity matrix
  36642. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00,
  36643. // width
  36644. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  36645. ]);
  36646. return box(types.tkhd, result);
  36647. };
  36648. /**
  36649. * Generate a track fragment (traf) box. A traf box collects metadata
  36650. * about tracks in a movie fragment (moof) box.
  36651. */
  36652. traf = function (track) {
  36653. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  36654. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00,
  36655. // version 0
  36656. 0x00, 0x00, 0x3a,
  36657. // flags
  36658. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,
  36659. // track_ID
  36660. 0x00, 0x00, 0x00, 0x01,
  36661. // sample_description_index
  36662. 0x00, 0x00, 0x00, 0x00,
  36663. // default_sample_duration
  36664. 0x00, 0x00, 0x00, 0x00,
  36665. // default_sample_size
  36666. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  36667. ]));
  36668. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  36669. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  36670. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01,
  36671. // version 1
  36672. 0x00, 0x00, 0x00,
  36673. // flags
  36674. // baseMediaDecodeTime
  36675. 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
  36676. // the containing moof to the first payload byte of the associated
  36677. // mdat
  36678. dataOffset = 32 +
  36679. // tfhd
  36680. 20 +
  36681. // tfdt
  36682. 8 +
  36683. // traf header
  36684. 16 +
  36685. // mfhd
  36686. 8 +
  36687. // moof header
  36688. 8; // mdat header
  36689. // audio tracks require less metadata
  36690. if (track.type === 'audio') {
  36691. trackFragmentRun = trun$1(track, dataOffset);
  36692. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  36693. } // video tracks should contain an independent and disposable samples
  36694. // box (sdtp)
  36695. // generate one and adjust offsets to match
  36696. sampleDependencyTable = sdtp(track);
  36697. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  36698. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  36699. };
  36700. /**
  36701. * Generate a track box.
  36702. * @param track {object} a track definition
  36703. * @return {Uint8Array} the track box
  36704. */
  36705. trak = function (track) {
  36706. track.duration = track.duration || 0xffffffff;
  36707. return box(types.trak, tkhd(track), mdia(track));
  36708. };
  36709. trex = function (track) {
  36710. var result = new Uint8Array([0x00,
  36711. // version 0
  36712. 0x00, 0x00, 0x00,
  36713. // flags
  36714. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,
  36715. // track_ID
  36716. 0x00, 0x00, 0x00, 0x01,
  36717. // default_sample_description_index
  36718. 0x00, 0x00, 0x00, 0x00,
  36719. // default_sample_duration
  36720. 0x00, 0x00, 0x00, 0x00,
  36721. // default_sample_size
  36722. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  36723. ]); // the last two bytes of default_sample_flags is the sample
  36724. // degradation priority, a hint about the importance of this sample
  36725. // relative to others. Lower the degradation priority for all sample
  36726. // types other than video.
  36727. if (track.type !== 'video') {
  36728. result[result.length - 1] = 0x00;
  36729. }
  36730. return box(types.trex, result);
  36731. };
  36732. (function () {
  36733. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  36734. // duration is present for the first sample, it will be present for
  36735. // all subsequent samples.
  36736. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  36737. trunHeader = function (samples, offset) {
  36738. var durationPresent = 0,
  36739. sizePresent = 0,
  36740. flagsPresent = 0,
  36741. compositionTimeOffset = 0; // trun flag constants
  36742. if (samples.length) {
  36743. if (samples[0].duration !== undefined) {
  36744. durationPresent = 0x1;
  36745. }
  36746. if (samples[0].size !== undefined) {
  36747. sizePresent = 0x2;
  36748. }
  36749. if (samples[0].flags !== undefined) {
  36750. flagsPresent = 0x4;
  36751. }
  36752. if (samples[0].compositionTimeOffset !== undefined) {
  36753. compositionTimeOffset = 0x8;
  36754. }
  36755. }
  36756. return [0x00,
  36757. // version 0
  36758. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01,
  36759. // flags
  36760. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF,
  36761. // sample_count
  36762. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  36763. ];
  36764. };
  36765. videoTrun = function (track, offset) {
  36766. var bytesOffest, bytes, header, samples, sample, i;
  36767. samples = track.samples || [];
  36768. offset += 8 + 12 + 16 * samples.length;
  36769. header = trunHeader(samples, offset);
  36770. bytes = new Uint8Array(header.length + samples.length * 16);
  36771. bytes.set(header);
  36772. bytesOffest = header.length;
  36773. for (i = 0; i < samples.length; i++) {
  36774. sample = samples[i];
  36775. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  36776. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  36777. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  36778. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  36779. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  36780. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  36781. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  36782. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  36783. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  36784. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  36785. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  36786. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  36787. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  36788. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  36789. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  36790. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  36791. }
  36792. return box(types.trun, bytes);
  36793. };
  36794. audioTrun = function (track, offset) {
  36795. var bytes, bytesOffest, header, samples, sample, i;
  36796. samples = track.samples || [];
  36797. offset += 8 + 12 + 8 * samples.length;
  36798. header = trunHeader(samples, offset);
  36799. bytes = new Uint8Array(header.length + samples.length * 8);
  36800. bytes.set(header);
  36801. bytesOffest = header.length;
  36802. for (i = 0; i < samples.length; i++) {
  36803. sample = samples[i];
  36804. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  36805. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  36806. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  36807. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  36808. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  36809. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  36810. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  36811. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  36812. }
  36813. return box(types.trun, bytes);
  36814. };
  36815. trun$1 = function (track, offset) {
  36816. if (track.type === 'audio') {
  36817. return audioTrun(track, offset);
  36818. }
  36819. return videoTrun(track, offset);
  36820. };
  36821. })();
  36822. var mp4Generator = {
  36823. ftyp: ftyp,
  36824. mdat: mdat,
  36825. moof: moof,
  36826. moov: moov,
  36827. initSegment: function (tracks) {
  36828. var fileType = ftyp(),
  36829. movie = moov(tracks),
  36830. result;
  36831. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  36832. result.set(fileType);
  36833. result.set(movie, fileType.byteLength);
  36834. return result;
  36835. }
  36836. };
  36837. /**
  36838. * mux.js
  36839. *
  36840. * Copyright (c) Brightcove
  36841. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  36842. */
  36843. // composed of the nal units that make up that frame
  36844. // Also keep track of cummulative data about the frame from the nal units such
  36845. // as the frame duration, starting pts, etc.
  36846. var groupNalsIntoFrames = function (nalUnits) {
  36847. var i,
  36848. currentNal,
  36849. currentFrame = [],
  36850. frames = []; // TODO added for LHLS, make sure this is OK
  36851. frames.byteLength = 0;
  36852. frames.nalCount = 0;
  36853. frames.duration = 0;
  36854. currentFrame.byteLength = 0;
  36855. for (i = 0; i < nalUnits.length; i++) {
  36856. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  36857. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  36858. // Since the very first nal unit is expected to be an AUD
  36859. // only push to the frames array when currentFrame is not empty
  36860. if (currentFrame.length) {
  36861. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  36862. frames.byteLength += currentFrame.byteLength;
  36863. frames.nalCount += currentFrame.length;
  36864. frames.duration += currentFrame.duration;
  36865. frames.push(currentFrame);
  36866. }
  36867. currentFrame = [currentNal];
  36868. currentFrame.byteLength = currentNal.data.byteLength;
  36869. currentFrame.pts = currentNal.pts;
  36870. currentFrame.dts = currentNal.dts;
  36871. } else {
  36872. // Specifically flag key frames for ease of use later
  36873. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  36874. currentFrame.keyFrame = true;
  36875. }
  36876. currentFrame.duration = currentNal.dts - currentFrame.dts;
  36877. currentFrame.byteLength += currentNal.data.byteLength;
  36878. currentFrame.push(currentNal);
  36879. }
  36880. } // For the last frame, use the duration of the previous frame if we
  36881. // have nothing better to go on
  36882. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  36883. currentFrame.duration = frames[frames.length - 1].duration;
  36884. } // Push the final frame
  36885. // TODO added for LHLS, make sure this is OK
  36886. frames.byteLength += currentFrame.byteLength;
  36887. frames.nalCount += currentFrame.length;
  36888. frames.duration += currentFrame.duration;
  36889. frames.push(currentFrame);
  36890. return frames;
  36891. }; // Convert an array of frames into an array of Gop with each Gop being composed
  36892. // of the frames that make up that Gop
  36893. // Also keep track of cummulative data about the Gop from the frames such as the
  36894. // Gop duration, starting pts, etc.
  36895. var groupFramesIntoGops = function (frames) {
  36896. var i,
  36897. currentFrame,
  36898. currentGop = [],
  36899. gops = []; // We must pre-set some of the values on the Gop since we
  36900. // keep running totals of these values
  36901. currentGop.byteLength = 0;
  36902. currentGop.nalCount = 0;
  36903. currentGop.duration = 0;
  36904. currentGop.pts = frames[0].pts;
  36905. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  36906. gops.byteLength = 0;
  36907. gops.nalCount = 0;
  36908. gops.duration = 0;
  36909. gops.pts = frames[0].pts;
  36910. gops.dts = frames[0].dts;
  36911. for (i = 0; i < frames.length; i++) {
  36912. currentFrame = frames[i];
  36913. if (currentFrame.keyFrame) {
  36914. // Since the very first frame is expected to be an keyframe
  36915. // only push to the gops array when currentGop is not empty
  36916. if (currentGop.length) {
  36917. gops.push(currentGop);
  36918. gops.byteLength += currentGop.byteLength;
  36919. gops.nalCount += currentGop.nalCount;
  36920. gops.duration += currentGop.duration;
  36921. }
  36922. currentGop = [currentFrame];
  36923. currentGop.nalCount = currentFrame.length;
  36924. currentGop.byteLength = currentFrame.byteLength;
  36925. currentGop.pts = currentFrame.pts;
  36926. currentGop.dts = currentFrame.dts;
  36927. currentGop.duration = currentFrame.duration;
  36928. } else {
  36929. currentGop.duration += currentFrame.duration;
  36930. currentGop.nalCount += currentFrame.length;
  36931. currentGop.byteLength += currentFrame.byteLength;
  36932. currentGop.push(currentFrame);
  36933. }
  36934. }
  36935. if (gops.length && currentGop.duration <= 0) {
  36936. currentGop.duration = gops[gops.length - 1].duration;
  36937. }
  36938. gops.byteLength += currentGop.byteLength;
  36939. gops.nalCount += currentGop.nalCount;
  36940. gops.duration += currentGop.duration; // push the final Gop
  36941. gops.push(currentGop);
  36942. return gops;
  36943. };
  36944. /*
  36945. * Search for the first keyframe in the GOPs and throw away all frames
  36946. * until that keyframe. Then extend the duration of the pulled keyframe
  36947. * and pull the PTS and DTS of the keyframe so that it covers the time
  36948. * range of the frames that were disposed.
  36949. *
  36950. * @param {Array} gops video GOPs
  36951. * @returns {Array} modified video GOPs
  36952. */
  36953. var extendFirstKeyFrame = function (gops) {
  36954. var currentGop;
  36955. if (!gops[0][0].keyFrame && gops.length > 1) {
  36956. // Remove the first GOP
  36957. currentGop = gops.shift();
  36958. gops.byteLength -= currentGop.byteLength;
  36959. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  36960. // first gop to cover the time period of the
  36961. // frames we just removed
  36962. gops[0][0].dts = currentGop.dts;
  36963. gops[0][0].pts = currentGop.pts;
  36964. gops[0][0].duration += currentGop.duration;
  36965. }
  36966. return gops;
  36967. };
  36968. /**
  36969. * Default sample object
  36970. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  36971. */
  36972. var createDefaultSample = function () {
  36973. return {
  36974. size: 0,
  36975. flags: {
  36976. isLeading: 0,
  36977. dependsOn: 1,
  36978. isDependedOn: 0,
  36979. hasRedundancy: 0,
  36980. degradationPriority: 0,
  36981. isNonSyncSample: 1
  36982. }
  36983. };
  36984. };
  36985. /*
  36986. * Collates information from a video frame into an object for eventual
  36987. * entry into an MP4 sample table.
  36988. *
  36989. * @param {Object} frame the video frame
  36990. * @param {Number} dataOffset the byte offset to position the sample
  36991. * @return {Object} object containing sample table info for a frame
  36992. */
  36993. var sampleForFrame = function (frame, dataOffset) {
  36994. var sample = createDefaultSample();
  36995. sample.dataOffset = dataOffset;
  36996. sample.compositionTimeOffset = frame.pts - frame.dts;
  36997. sample.duration = frame.duration;
  36998. sample.size = 4 * frame.length; // Space for nal unit size
  36999. sample.size += frame.byteLength;
  37000. if (frame.keyFrame) {
  37001. sample.flags.dependsOn = 2;
  37002. sample.flags.isNonSyncSample = 0;
  37003. }
  37004. return sample;
  37005. }; // generate the track's sample table from an array of gops
  37006. var generateSampleTable$1 = function (gops, baseDataOffset) {
  37007. var h,
  37008. i,
  37009. sample,
  37010. currentGop,
  37011. currentFrame,
  37012. dataOffset = baseDataOffset || 0,
  37013. samples = [];
  37014. for (h = 0; h < gops.length; h++) {
  37015. currentGop = gops[h];
  37016. for (i = 0; i < currentGop.length; i++) {
  37017. currentFrame = currentGop[i];
  37018. sample = sampleForFrame(currentFrame, dataOffset);
  37019. dataOffset += sample.size;
  37020. samples.push(sample);
  37021. }
  37022. }
  37023. return samples;
  37024. }; // generate the track's raw mdat data from an array of gops
  37025. var concatenateNalData = function (gops) {
  37026. var h,
  37027. i,
  37028. j,
  37029. currentGop,
  37030. currentFrame,
  37031. currentNal,
  37032. dataOffset = 0,
  37033. nalsByteLength = gops.byteLength,
  37034. numberOfNals = gops.nalCount,
  37035. totalByteLength = nalsByteLength + 4 * numberOfNals,
  37036. data = new Uint8Array(totalByteLength),
  37037. view = new DataView(data.buffer); // For each Gop..
  37038. for (h = 0; h < gops.length; h++) {
  37039. currentGop = gops[h]; // For each Frame..
  37040. for (i = 0; i < currentGop.length; i++) {
  37041. currentFrame = currentGop[i]; // For each NAL..
  37042. for (j = 0; j < currentFrame.length; j++) {
  37043. currentNal = currentFrame[j];
  37044. view.setUint32(dataOffset, currentNal.data.byteLength);
  37045. dataOffset += 4;
  37046. data.set(currentNal.data, dataOffset);
  37047. dataOffset += currentNal.data.byteLength;
  37048. }
  37049. }
  37050. }
  37051. return data;
  37052. }; // generate the track's sample table from a frame
  37053. var generateSampleTableForFrame = function (frame, baseDataOffset) {
  37054. var sample,
  37055. dataOffset = baseDataOffset || 0,
  37056. samples = [];
  37057. sample = sampleForFrame(frame, dataOffset);
  37058. samples.push(sample);
  37059. return samples;
  37060. }; // generate the track's raw mdat data from a frame
  37061. var concatenateNalDataForFrame = function (frame) {
  37062. var i,
  37063. currentNal,
  37064. dataOffset = 0,
  37065. nalsByteLength = frame.byteLength,
  37066. numberOfNals = frame.length,
  37067. totalByteLength = nalsByteLength + 4 * numberOfNals,
  37068. data = new Uint8Array(totalByteLength),
  37069. view = new DataView(data.buffer); // For each NAL..
  37070. for (i = 0; i < frame.length; i++) {
  37071. currentNal = frame[i];
  37072. view.setUint32(dataOffset, currentNal.data.byteLength);
  37073. dataOffset += 4;
  37074. data.set(currentNal.data, dataOffset);
  37075. dataOffset += currentNal.data.byteLength;
  37076. }
  37077. return data;
  37078. };
  37079. var frameUtils$1 = {
  37080. groupNalsIntoFrames: groupNalsIntoFrames,
  37081. groupFramesIntoGops: groupFramesIntoGops,
  37082. extendFirstKeyFrame: extendFirstKeyFrame,
  37083. generateSampleTable: generateSampleTable$1,
  37084. concatenateNalData: concatenateNalData,
  37085. generateSampleTableForFrame: generateSampleTableForFrame,
  37086. concatenateNalDataForFrame: concatenateNalDataForFrame
  37087. };
  37088. /**
  37089. * mux.js
  37090. *
  37091. * Copyright (c) Brightcove
  37092. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37093. */
  37094. var highPrefix = [33, 16, 5, 32, 164, 27];
  37095. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  37096. var zeroFill = function (count) {
  37097. var a = [];
  37098. while (count--) {
  37099. a.push(0);
  37100. }
  37101. return a;
  37102. };
  37103. var makeTable = function (metaTable) {
  37104. return Object.keys(metaTable).reduce(function (obj, key) {
  37105. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  37106. return arr.concat(part);
  37107. }, []));
  37108. return obj;
  37109. }, {});
  37110. };
  37111. var silence;
  37112. var silence_1 = function () {
  37113. if (!silence) {
  37114. // Frames-of-silence to use for filling in missing AAC frames
  37115. var coneOfSilence = {
  37116. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  37117. 88200: [highPrefix, [231], zeroFill(170), [56]],
  37118. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  37119. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  37120. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  37121. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  37122. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  37123. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  37124. 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]],
  37125. 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]],
  37126. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  37127. };
  37128. silence = makeTable(coneOfSilence);
  37129. }
  37130. return silence;
  37131. };
  37132. /**
  37133. * mux.js
  37134. *
  37135. * Copyright (c) Brightcove
  37136. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37137. */
  37138. var ONE_SECOND_IN_TS$4 = 90000,
  37139. // 90kHz clock
  37140. secondsToVideoTs,
  37141. secondsToAudioTs,
  37142. videoTsToSeconds,
  37143. audioTsToSeconds,
  37144. audioTsToVideoTs,
  37145. videoTsToAudioTs,
  37146. metadataTsToSeconds;
  37147. secondsToVideoTs = function (seconds) {
  37148. return seconds * ONE_SECOND_IN_TS$4;
  37149. };
  37150. secondsToAudioTs = function (seconds, sampleRate) {
  37151. return seconds * sampleRate;
  37152. };
  37153. videoTsToSeconds = function (timestamp) {
  37154. return timestamp / ONE_SECOND_IN_TS$4;
  37155. };
  37156. audioTsToSeconds = function (timestamp, sampleRate) {
  37157. return timestamp / sampleRate;
  37158. };
  37159. audioTsToVideoTs = function (timestamp, sampleRate) {
  37160. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  37161. };
  37162. videoTsToAudioTs = function (timestamp, sampleRate) {
  37163. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  37164. };
  37165. /**
  37166. * Adjust ID3 tag or caption timing information by the timeline pts values
  37167. * (if keepOriginalTimestamps is false) and convert to seconds
  37168. */
  37169. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  37170. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  37171. };
  37172. var clock$2 = {
  37173. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  37174. secondsToVideoTs: secondsToVideoTs,
  37175. secondsToAudioTs: secondsToAudioTs,
  37176. videoTsToSeconds: videoTsToSeconds,
  37177. audioTsToSeconds: audioTsToSeconds,
  37178. audioTsToVideoTs: audioTsToVideoTs,
  37179. videoTsToAudioTs: videoTsToAudioTs,
  37180. metadataTsToSeconds: metadataTsToSeconds
  37181. };
  37182. /**
  37183. * mux.js
  37184. *
  37185. * Copyright (c) Brightcove
  37186. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37187. */
  37188. var coneOfSilence = silence_1;
  37189. var clock$1 = clock$2;
  37190. /**
  37191. * Sum the `byteLength` properties of the data in each AAC frame
  37192. */
  37193. var sumFrameByteLengths = function (array) {
  37194. var i,
  37195. currentObj,
  37196. sum = 0; // sum the byteLength's all each nal unit in the frame
  37197. for (i = 0; i < array.length; i++) {
  37198. currentObj = array[i];
  37199. sum += currentObj.data.byteLength;
  37200. }
  37201. return sum;
  37202. }; // Possibly pad (prefix) the audio track with silence if appending this track
  37203. // would lead to the introduction of a gap in the audio buffer
  37204. var prefixWithSilence = function (track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  37205. var baseMediaDecodeTimeTs,
  37206. frameDuration = 0,
  37207. audioGapDuration = 0,
  37208. audioFillFrameCount = 0,
  37209. audioFillDuration = 0,
  37210. silentFrame,
  37211. i,
  37212. firstFrame;
  37213. if (!frames.length) {
  37214. return;
  37215. }
  37216. baseMediaDecodeTimeTs = clock$1.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  37217. frameDuration = Math.ceil(clock$1.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  37218. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  37219. // insert the shortest possible amount (audio gap or audio to video gap)
  37220. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  37221. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  37222. audioFillDuration = audioFillFrameCount * frameDuration;
  37223. } // don't attempt to fill gaps smaller than a single frame or larger
  37224. // than a half second
  37225. if (audioFillFrameCount < 1 || audioFillDuration > clock$1.ONE_SECOND_IN_TS / 2) {
  37226. return;
  37227. }
  37228. silentFrame = coneOfSilence()[track.samplerate];
  37229. if (!silentFrame) {
  37230. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  37231. // from the content instead
  37232. silentFrame = frames[0].data;
  37233. }
  37234. for (i = 0; i < audioFillFrameCount; i++) {
  37235. firstFrame = frames[0];
  37236. frames.splice(0, 0, {
  37237. data: silentFrame,
  37238. dts: firstFrame.dts - frameDuration,
  37239. pts: firstFrame.pts - frameDuration
  37240. });
  37241. }
  37242. track.baseMediaDecodeTime -= Math.floor(clock$1.videoTsToAudioTs(audioFillDuration, track.samplerate));
  37243. return audioFillDuration;
  37244. }; // If the audio segment extends before the earliest allowed dts
  37245. // value, remove AAC frames until starts at or after the earliest
  37246. // allowed DTS so that we don't end up with a negative baseMedia-
  37247. // DecodeTime for the audio track
  37248. var trimAdtsFramesByEarliestDts = function (adtsFrames, track, earliestAllowedDts) {
  37249. if (track.minSegmentDts >= earliestAllowedDts) {
  37250. return adtsFrames;
  37251. } // We will need to recalculate the earliest segment Dts
  37252. track.minSegmentDts = Infinity;
  37253. return adtsFrames.filter(function (currentFrame) {
  37254. // If this is an allowed frame, keep it and record it's Dts
  37255. if (currentFrame.dts >= earliestAllowedDts) {
  37256. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  37257. track.minSegmentPts = track.minSegmentDts;
  37258. return true;
  37259. } // Otherwise, discard it
  37260. return false;
  37261. });
  37262. }; // generate the track's raw mdat data from an array of frames
  37263. var generateSampleTable = function (frames) {
  37264. var i,
  37265. currentFrame,
  37266. samples = [];
  37267. for (i = 0; i < frames.length; i++) {
  37268. currentFrame = frames[i];
  37269. samples.push({
  37270. size: currentFrame.data.byteLength,
  37271. duration: 1024 // For AAC audio, all samples contain 1024 samples
  37272. });
  37273. }
  37274. return samples;
  37275. }; // generate the track's sample table from an array of frames
  37276. var concatenateFrameData = function (frames) {
  37277. var i,
  37278. currentFrame,
  37279. dataOffset = 0,
  37280. data = new Uint8Array(sumFrameByteLengths(frames));
  37281. for (i = 0; i < frames.length; i++) {
  37282. currentFrame = frames[i];
  37283. data.set(currentFrame.data, dataOffset);
  37284. dataOffset += currentFrame.data.byteLength;
  37285. }
  37286. return data;
  37287. };
  37288. var audioFrameUtils$1 = {
  37289. prefixWithSilence: prefixWithSilence,
  37290. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  37291. generateSampleTable: generateSampleTable,
  37292. concatenateFrameData: concatenateFrameData
  37293. };
  37294. /**
  37295. * mux.js
  37296. *
  37297. * Copyright (c) Brightcove
  37298. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37299. */
  37300. var ONE_SECOND_IN_TS$3 = clock$2.ONE_SECOND_IN_TS;
  37301. /**
  37302. * Store information about the start and end of the track and the
  37303. * duration for each frame/sample we process in order to calculate
  37304. * the baseMediaDecodeTime
  37305. */
  37306. var collectDtsInfo = function (track, data) {
  37307. if (typeof data.pts === 'number') {
  37308. if (track.timelineStartInfo.pts === undefined) {
  37309. track.timelineStartInfo.pts = data.pts;
  37310. }
  37311. if (track.minSegmentPts === undefined) {
  37312. track.minSegmentPts = data.pts;
  37313. } else {
  37314. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  37315. }
  37316. if (track.maxSegmentPts === undefined) {
  37317. track.maxSegmentPts = data.pts;
  37318. } else {
  37319. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  37320. }
  37321. }
  37322. if (typeof data.dts === 'number') {
  37323. if (track.timelineStartInfo.dts === undefined) {
  37324. track.timelineStartInfo.dts = data.dts;
  37325. }
  37326. if (track.minSegmentDts === undefined) {
  37327. track.minSegmentDts = data.dts;
  37328. } else {
  37329. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  37330. }
  37331. if (track.maxSegmentDts === undefined) {
  37332. track.maxSegmentDts = data.dts;
  37333. } else {
  37334. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  37335. }
  37336. }
  37337. };
  37338. /**
  37339. * Clear values used to calculate the baseMediaDecodeTime between
  37340. * tracks
  37341. */
  37342. var clearDtsInfo = function (track) {
  37343. delete track.minSegmentDts;
  37344. delete track.maxSegmentDts;
  37345. delete track.minSegmentPts;
  37346. delete track.maxSegmentPts;
  37347. };
  37348. /**
  37349. * Calculate the track's baseMediaDecodeTime based on the earliest
  37350. * DTS the transmuxer has ever seen and the minimum DTS for the
  37351. * current track
  37352. * @param track {object} track metadata configuration
  37353. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  37354. * in the source; false to adjust the first segment to start at 0.
  37355. */
  37356. var calculateTrackBaseMediaDecodeTime = function (track, keepOriginalTimestamps) {
  37357. var baseMediaDecodeTime,
  37358. scale,
  37359. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  37360. if (!keepOriginalTimestamps) {
  37361. minSegmentDts -= track.timelineStartInfo.dts;
  37362. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  37363. // we want the start of the first segment to be placed
  37364. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  37365. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  37366. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  37367. if (track.type === 'audio') {
  37368. // Audio has a different clock equal to the sampling_rate so we need to
  37369. // scale the PTS values into the clock rate of the track
  37370. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  37371. baseMediaDecodeTime *= scale;
  37372. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  37373. }
  37374. return baseMediaDecodeTime;
  37375. };
  37376. var trackDecodeInfo$1 = {
  37377. clearDtsInfo: clearDtsInfo,
  37378. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  37379. collectDtsInfo: collectDtsInfo
  37380. };
  37381. /**
  37382. * mux.js
  37383. *
  37384. * Copyright (c) Brightcove
  37385. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37386. *
  37387. * Reads in-band caption information from a video elementary
  37388. * stream. Captions must follow the CEA-708 standard for injection
  37389. * into an MPEG-2 transport streams.
  37390. * @see https://en.wikipedia.org/wiki/CEA-708
  37391. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  37392. */
  37393. // payload type field to indicate how they are to be
  37394. // interpreted. CEAS-708 caption content is always transmitted with
  37395. // payload type 0x04.
  37396. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  37397. RBSP_TRAILING_BITS = 128;
  37398. /**
  37399. * Parse a supplemental enhancement information (SEI) NAL unit.
  37400. * Stops parsing once a message of type ITU T T35 has been found.
  37401. *
  37402. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  37403. * @return {object} the parsed SEI payload
  37404. * @see Rec. ITU-T H.264, 7.3.2.3.1
  37405. */
  37406. var parseSei = function (bytes) {
  37407. var i = 0,
  37408. result = {
  37409. payloadType: -1,
  37410. payloadSize: 0
  37411. },
  37412. payloadType = 0,
  37413. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  37414. while (i < bytes.byteLength) {
  37415. // stop once we have hit the end of the sei_rbsp
  37416. if (bytes[i] === RBSP_TRAILING_BITS) {
  37417. break;
  37418. } // Parse payload type
  37419. while (bytes[i] === 0xFF) {
  37420. payloadType += 255;
  37421. i++;
  37422. }
  37423. payloadType += bytes[i++]; // Parse payload size
  37424. while (bytes[i] === 0xFF) {
  37425. payloadSize += 255;
  37426. i++;
  37427. }
  37428. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  37429. // there can only ever be one caption message in a frame's sei
  37430. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  37431. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  37432. if (userIdentifier === 'GA94') {
  37433. result.payloadType = payloadType;
  37434. result.payloadSize = payloadSize;
  37435. result.payload = bytes.subarray(i, i + payloadSize);
  37436. break;
  37437. } else {
  37438. result.payload = void 0;
  37439. }
  37440. } // skip the payload and parse the next message
  37441. i += payloadSize;
  37442. payloadType = 0;
  37443. payloadSize = 0;
  37444. }
  37445. return result;
  37446. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  37447. var parseUserData = function (sei) {
  37448. // itu_t_t35_contry_code must be 181 (United States) for
  37449. // captions
  37450. if (sei.payload[0] !== 181) {
  37451. return null;
  37452. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  37453. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  37454. return null;
  37455. } // the user_identifier should be "GA94" to indicate ATSC1 data
  37456. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  37457. return null;
  37458. } // finally, user_data_type_code should be 0x03 for caption data
  37459. if (sei.payload[7] !== 0x03) {
  37460. return null;
  37461. } // return the user_data_type_structure and strip the trailing
  37462. // marker bits
  37463. return sei.payload.subarray(8, sei.payload.length - 1);
  37464. }; // see CEA-708-D, section 4.4
  37465. var parseCaptionPackets = function (pts, userData) {
  37466. var results = [],
  37467. i,
  37468. count,
  37469. offset,
  37470. data; // if this is just filler, return immediately
  37471. if (!(userData[0] & 0x40)) {
  37472. return results;
  37473. } // parse out the cc_data_1 and cc_data_2 fields
  37474. count = userData[0] & 0x1f;
  37475. for (i = 0; i < count; i++) {
  37476. offset = i * 3;
  37477. data = {
  37478. type: userData[offset + 2] & 0x03,
  37479. pts: pts
  37480. }; // capture cc data when cc_valid is 1
  37481. if (userData[offset + 2] & 0x04) {
  37482. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  37483. results.push(data);
  37484. }
  37485. }
  37486. return results;
  37487. };
  37488. var discardEmulationPreventionBytes$1 = function (data) {
  37489. var length = data.byteLength,
  37490. emulationPreventionBytesPositions = [],
  37491. i = 1,
  37492. newLength,
  37493. newData; // Find all `Emulation Prevention Bytes`
  37494. while (i < length - 2) {
  37495. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  37496. emulationPreventionBytesPositions.push(i + 2);
  37497. i += 2;
  37498. } else {
  37499. i++;
  37500. }
  37501. } // If no Emulation Prevention Bytes were found just return the original
  37502. // array
  37503. if (emulationPreventionBytesPositions.length === 0) {
  37504. return data;
  37505. } // Create a new array to hold the NAL unit data
  37506. newLength = length - emulationPreventionBytesPositions.length;
  37507. newData = new Uint8Array(newLength);
  37508. var sourceIndex = 0;
  37509. for (i = 0; i < newLength; sourceIndex++, i++) {
  37510. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  37511. // Skip this byte
  37512. sourceIndex++; // Remove this position index
  37513. emulationPreventionBytesPositions.shift();
  37514. }
  37515. newData[i] = data[sourceIndex];
  37516. }
  37517. return newData;
  37518. }; // exports
  37519. var captionPacketParser = {
  37520. parseSei: parseSei,
  37521. parseUserData: parseUserData,
  37522. parseCaptionPackets: parseCaptionPackets,
  37523. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  37524. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  37525. };
  37526. /**
  37527. * mux.js
  37528. *
  37529. * Copyright (c) Brightcove
  37530. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37531. *
  37532. * Reads in-band caption information from a video elementary
  37533. * stream. Captions must follow the CEA-708 standard for injection
  37534. * into an MPEG-2 transport streams.
  37535. * @see https://en.wikipedia.org/wiki/CEA-708
  37536. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  37537. */
  37538. // Link To Transport
  37539. // -----------------
  37540. var Stream$7 = stream;
  37541. var cea708Parser = captionPacketParser;
  37542. var CaptionStream$2 = function (options) {
  37543. options = options || {};
  37544. CaptionStream$2.prototype.init.call(this); // parse708captions flag, default to true
  37545. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  37546. this.captionPackets_ = [];
  37547. this.ccStreams_ = [new Cea608Stream(0, 0),
  37548. // eslint-disable-line no-use-before-define
  37549. new Cea608Stream(0, 1),
  37550. // eslint-disable-line no-use-before-define
  37551. new Cea608Stream(1, 0),
  37552. // eslint-disable-line no-use-before-define
  37553. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  37554. ];
  37555. if (this.parse708captions_) {
  37556. this.cc708Stream_ = new Cea708Stream({
  37557. captionServices: options.captionServices
  37558. }); // eslint-disable-line no-use-before-define
  37559. }
  37560. this.reset(); // forward data and done events from CCs to this CaptionStream
  37561. this.ccStreams_.forEach(function (cc) {
  37562. cc.on('data', this.trigger.bind(this, 'data'));
  37563. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  37564. cc.on('done', this.trigger.bind(this, 'done'));
  37565. }, this);
  37566. if (this.parse708captions_) {
  37567. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  37568. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  37569. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  37570. }
  37571. };
  37572. CaptionStream$2.prototype = new Stream$7();
  37573. CaptionStream$2.prototype.push = function (event) {
  37574. var sei, userData, newCaptionPackets; // only examine SEI NALs
  37575. if (event.nalUnitType !== 'sei_rbsp') {
  37576. return;
  37577. } // parse the sei
  37578. sei = cea708Parser.parseSei(event.escapedRBSP); // no payload data, skip
  37579. if (!sei.payload) {
  37580. return;
  37581. } // ignore everything but user_data_registered_itu_t_t35
  37582. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  37583. return;
  37584. } // parse out the user data payload
  37585. userData = cea708Parser.parseUserData(sei); // ignore unrecognized userData
  37586. if (!userData) {
  37587. return;
  37588. } // Sometimes, the same segment # will be downloaded twice. To stop the
  37589. // caption data from being processed twice, we track the latest dts we've
  37590. // received and ignore everything with a dts before that. However, since
  37591. // data for a specific dts can be split across packets on either side of
  37592. // a segment boundary, we need to make sure we *don't* ignore the packets
  37593. // from the *next* segment that have dts === this.latestDts_. By constantly
  37594. // tracking the number of packets received with dts === this.latestDts_, we
  37595. // know how many should be ignored once we start receiving duplicates.
  37596. if (event.dts < this.latestDts_) {
  37597. // We've started getting older data, so set the flag.
  37598. this.ignoreNextEqualDts_ = true;
  37599. return;
  37600. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  37601. this.numSameDts_--;
  37602. if (!this.numSameDts_) {
  37603. // We've received the last duplicate packet, time to start processing again
  37604. this.ignoreNextEqualDts_ = false;
  37605. }
  37606. return;
  37607. } // parse out CC data packets and save them for later
  37608. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  37609. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  37610. if (this.latestDts_ !== event.dts) {
  37611. this.numSameDts_ = 0;
  37612. }
  37613. this.numSameDts_++;
  37614. this.latestDts_ = event.dts;
  37615. };
  37616. CaptionStream$2.prototype.flushCCStreams = function (flushType) {
  37617. this.ccStreams_.forEach(function (cc) {
  37618. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  37619. }, this);
  37620. };
  37621. CaptionStream$2.prototype.flushStream = function (flushType) {
  37622. // make sure we actually parsed captions before proceeding
  37623. if (!this.captionPackets_.length) {
  37624. this.flushCCStreams(flushType);
  37625. return;
  37626. } // In Chrome, the Array#sort function is not stable so add a
  37627. // presortIndex that we can use to ensure we get a stable-sort
  37628. this.captionPackets_.forEach(function (elem, idx) {
  37629. elem.presortIndex = idx;
  37630. }); // sort caption byte-pairs based on their PTS values
  37631. this.captionPackets_.sort(function (a, b) {
  37632. if (a.pts === b.pts) {
  37633. return a.presortIndex - b.presortIndex;
  37634. }
  37635. return a.pts - b.pts;
  37636. });
  37637. this.captionPackets_.forEach(function (packet) {
  37638. if (packet.type < 2) {
  37639. // Dispatch packet to the right Cea608Stream
  37640. this.dispatchCea608Packet(packet);
  37641. } else {
  37642. // Dispatch packet to the Cea708Stream
  37643. this.dispatchCea708Packet(packet);
  37644. }
  37645. }, this);
  37646. this.captionPackets_.length = 0;
  37647. this.flushCCStreams(flushType);
  37648. };
  37649. CaptionStream$2.prototype.flush = function () {
  37650. return this.flushStream('flush');
  37651. }; // Only called if handling partial data
  37652. CaptionStream$2.prototype.partialFlush = function () {
  37653. return this.flushStream('partialFlush');
  37654. };
  37655. CaptionStream$2.prototype.reset = function () {
  37656. this.latestDts_ = null;
  37657. this.ignoreNextEqualDts_ = false;
  37658. this.numSameDts_ = 0;
  37659. this.activeCea608Channel_ = [null, null];
  37660. this.ccStreams_.forEach(function (ccStream) {
  37661. ccStream.reset();
  37662. });
  37663. }; // From the CEA-608 spec:
  37664. /*
  37665. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  37666. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  37667. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  37668. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  37669. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  37670. * to switch to captioning or Text.
  37671. */
  37672. // With that in mind, we ignore any data between an XDS control code and a
  37673. // subsequent closed-captioning control code.
  37674. CaptionStream$2.prototype.dispatchCea608Packet = function (packet) {
  37675. // NOTE: packet.type is the CEA608 field
  37676. if (this.setsTextOrXDSActive(packet)) {
  37677. this.activeCea608Channel_[packet.type] = null;
  37678. } else if (this.setsChannel1Active(packet)) {
  37679. this.activeCea608Channel_[packet.type] = 0;
  37680. } else if (this.setsChannel2Active(packet)) {
  37681. this.activeCea608Channel_[packet.type] = 1;
  37682. }
  37683. if (this.activeCea608Channel_[packet.type] === null) {
  37684. // If we haven't received anything to set the active channel, or the
  37685. // packets are Text/XDS data, discard the data; we don't want jumbled
  37686. // captions
  37687. return;
  37688. }
  37689. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  37690. };
  37691. CaptionStream$2.prototype.setsChannel1Active = function (packet) {
  37692. return (packet.ccData & 0x7800) === 0x1000;
  37693. };
  37694. CaptionStream$2.prototype.setsChannel2Active = function (packet) {
  37695. return (packet.ccData & 0x7800) === 0x1800;
  37696. };
  37697. CaptionStream$2.prototype.setsTextOrXDSActive = function (packet) {
  37698. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  37699. };
  37700. CaptionStream$2.prototype.dispatchCea708Packet = function (packet) {
  37701. if (this.parse708captions_) {
  37702. this.cc708Stream_.push(packet);
  37703. }
  37704. }; // ----------------------
  37705. // Session to Application
  37706. // ----------------------
  37707. // This hash maps special and extended character codes to their
  37708. // proper Unicode equivalent. The first one-byte key is just a
  37709. // non-standard character code. The two-byte keys that follow are
  37710. // the extended CEA708 character codes, along with the preceding
  37711. // 0x10 extended character byte to distinguish these codes from
  37712. // non-extended character codes. Every CEA708 character code that
  37713. // is not in this object maps directly to a standard unicode
  37714. // character code.
  37715. // The transparent space and non-breaking transparent space are
  37716. // technically not fully supported since there is no code to
  37717. // make them transparent, so they have normal non-transparent
  37718. // stand-ins.
  37719. // The special closed caption (CC) character isn't a standard
  37720. // unicode character, so a fairly similar unicode character was
  37721. // chosen in it's place.
  37722. var CHARACTER_TRANSLATION_708 = {
  37723. 0x7f: 0x266a,
  37724. // ♪
  37725. 0x1020: 0x20,
  37726. // Transparent Space
  37727. 0x1021: 0xa0,
  37728. // Nob-breaking Transparent Space
  37729. 0x1025: 0x2026,
  37730. // …
  37731. 0x102a: 0x0160,
  37732. // Š
  37733. 0x102c: 0x0152,
  37734. // Œ
  37735. 0x1030: 0x2588,
  37736. // █
  37737. 0x1031: 0x2018,
  37738. // ‘
  37739. 0x1032: 0x2019,
  37740. // ’
  37741. 0x1033: 0x201c,
  37742. // “
  37743. 0x1034: 0x201d,
  37744. // ”
  37745. 0x1035: 0x2022,
  37746. // •
  37747. 0x1039: 0x2122,
  37748. // ™
  37749. 0x103a: 0x0161,
  37750. // š
  37751. 0x103c: 0x0153,
  37752. // œ
  37753. 0x103d: 0x2120,
  37754. // ℠
  37755. 0x103f: 0x0178,
  37756. // Ÿ
  37757. 0x1076: 0x215b,
  37758. // ⅛
  37759. 0x1077: 0x215c,
  37760. // ⅜
  37761. 0x1078: 0x215d,
  37762. // ⅝
  37763. 0x1079: 0x215e,
  37764. // ⅞
  37765. 0x107a: 0x23d0,
  37766. // ⏐
  37767. 0x107b: 0x23a4,
  37768. // ⎤
  37769. 0x107c: 0x23a3,
  37770. // ⎣
  37771. 0x107d: 0x23af,
  37772. // ⎯
  37773. 0x107e: 0x23a6,
  37774. // ⎦
  37775. 0x107f: 0x23a1,
  37776. // ⎡
  37777. 0x10a0: 0x3138 // ㄸ (CC char)
  37778. };
  37779. var get708CharFromCode = function (code) {
  37780. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  37781. if (code & 0x1000 && code === newCode) {
  37782. // Invalid extended code
  37783. return '';
  37784. }
  37785. return String.fromCharCode(newCode);
  37786. };
  37787. var within708TextBlock = function (b) {
  37788. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  37789. };
  37790. var Cea708Window = function (windowNum) {
  37791. this.windowNum = windowNum;
  37792. this.reset();
  37793. };
  37794. Cea708Window.prototype.reset = function () {
  37795. this.clearText();
  37796. this.pendingNewLine = false;
  37797. this.winAttr = {};
  37798. this.penAttr = {};
  37799. this.penLoc = {};
  37800. this.penColor = {}; // These default values are arbitrary,
  37801. // defineWindow will usually override them
  37802. this.visible = 0;
  37803. this.rowLock = 0;
  37804. this.columnLock = 0;
  37805. this.priority = 0;
  37806. this.relativePositioning = 0;
  37807. this.anchorVertical = 0;
  37808. this.anchorHorizontal = 0;
  37809. this.anchorPoint = 0;
  37810. this.rowCount = 1;
  37811. this.virtualRowCount = this.rowCount + 1;
  37812. this.columnCount = 41;
  37813. this.windowStyle = 0;
  37814. this.penStyle = 0;
  37815. };
  37816. Cea708Window.prototype.getText = function () {
  37817. return this.rows.join('\n');
  37818. };
  37819. Cea708Window.prototype.clearText = function () {
  37820. this.rows = [''];
  37821. this.rowIdx = 0;
  37822. };
  37823. Cea708Window.prototype.newLine = function (pts) {
  37824. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  37825. this.beforeRowOverflow(pts);
  37826. }
  37827. if (this.rows.length > 0) {
  37828. this.rows.push('');
  37829. this.rowIdx++;
  37830. } // Show all virtual rows since there's no visible scrolling
  37831. while (this.rows.length > this.virtualRowCount) {
  37832. this.rows.shift();
  37833. this.rowIdx--;
  37834. }
  37835. };
  37836. Cea708Window.prototype.isEmpty = function () {
  37837. if (this.rows.length === 0) {
  37838. return true;
  37839. } else if (this.rows.length === 1) {
  37840. return this.rows[0] === '';
  37841. }
  37842. return false;
  37843. };
  37844. Cea708Window.prototype.addText = function (text) {
  37845. this.rows[this.rowIdx] += text;
  37846. };
  37847. Cea708Window.prototype.backspace = function () {
  37848. if (!this.isEmpty()) {
  37849. var row = this.rows[this.rowIdx];
  37850. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  37851. }
  37852. };
  37853. var Cea708Service = function (serviceNum, encoding, stream) {
  37854. this.serviceNum = serviceNum;
  37855. this.text = '';
  37856. this.currentWindow = new Cea708Window(-1);
  37857. this.windows = [];
  37858. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  37859. if (typeof encoding === 'string') {
  37860. this.createTextDecoder(encoding);
  37861. }
  37862. };
  37863. /**
  37864. * Initialize service windows
  37865. * Must be run before service use
  37866. *
  37867. * @param {Integer} pts PTS value
  37868. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  37869. */
  37870. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  37871. this.startPts = pts;
  37872. for (var win = 0; win < 8; win++) {
  37873. this.windows[win] = new Cea708Window(win);
  37874. if (typeof beforeRowOverflow === 'function') {
  37875. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  37876. }
  37877. }
  37878. };
  37879. /**
  37880. * Set current window of service to be affected by commands
  37881. *
  37882. * @param {Integer} windowNum Window number
  37883. */
  37884. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  37885. this.currentWindow = this.windows[windowNum];
  37886. };
  37887. /**
  37888. * Try to create a TextDecoder if it is natively supported
  37889. */
  37890. Cea708Service.prototype.createTextDecoder = function (encoding) {
  37891. if (typeof TextDecoder === 'undefined') {
  37892. this.stream.trigger('log', {
  37893. level: 'warn',
  37894. message: 'The `encoding` option is unsupported without TextDecoder support'
  37895. });
  37896. } else {
  37897. try {
  37898. this.textDecoder_ = new TextDecoder(encoding);
  37899. } catch (error) {
  37900. this.stream.trigger('log', {
  37901. level: 'warn',
  37902. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  37903. });
  37904. }
  37905. }
  37906. };
  37907. var Cea708Stream = function (options) {
  37908. options = options || {};
  37909. Cea708Stream.prototype.init.call(this);
  37910. var self = this;
  37911. var captionServices = options.captionServices || {};
  37912. var captionServiceEncodings = {};
  37913. var serviceProps; // Get service encodings from captionServices option block
  37914. Object.keys(captionServices).forEach(serviceName => {
  37915. serviceProps = captionServices[serviceName];
  37916. if (/^SERVICE/.test(serviceName)) {
  37917. captionServiceEncodings[serviceName] = serviceProps.encoding;
  37918. }
  37919. });
  37920. this.serviceEncodings = captionServiceEncodings;
  37921. this.current708Packet = null;
  37922. this.services = {};
  37923. this.push = function (packet) {
  37924. if (packet.type === 3) {
  37925. // 708 packet start
  37926. self.new708Packet();
  37927. self.add708Bytes(packet);
  37928. } else {
  37929. if (self.current708Packet === null) {
  37930. // This should only happen at the start of a file if there's no packet start.
  37931. self.new708Packet();
  37932. }
  37933. self.add708Bytes(packet);
  37934. }
  37935. };
  37936. };
  37937. Cea708Stream.prototype = new Stream$7();
  37938. /**
  37939. * Push current 708 packet, create new 708 packet.
  37940. */
  37941. Cea708Stream.prototype.new708Packet = function () {
  37942. if (this.current708Packet !== null) {
  37943. this.push708Packet();
  37944. }
  37945. this.current708Packet = {
  37946. data: [],
  37947. ptsVals: []
  37948. };
  37949. };
  37950. /**
  37951. * Add pts and both bytes from packet into current 708 packet.
  37952. */
  37953. Cea708Stream.prototype.add708Bytes = function (packet) {
  37954. var data = packet.ccData;
  37955. var byte0 = data >>> 8;
  37956. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  37957. // that service blocks will always line up with byte pairs.
  37958. this.current708Packet.ptsVals.push(packet.pts);
  37959. this.current708Packet.data.push(byte0);
  37960. this.current708Packet.data.push(byte1);
  37961. };
  37962. /**
  37963. * Parse completed 708 packet into service blocks and push each service block.
  37964. */
  37965. Cea708Stream.prototype.push708Packet = function () {
  37966. var packet708 = this.current708Packet;
  37967. var packetData = packet708.data;
  37968. var serviceNum = null;
  37969. var blockSize = null;
  37970. var i = 0;
  37971. var b = packetData[i++];
  37972. packet708.seq = b >> 6;
  37973. packet708.sizeCode = b & 0x3f; // 0b00111111;
  37974. for (; i < packetData.length; i++) {
  37975. b = packetData[i++];
  37976. serviceNum = b >> 5;
  37977. blockSize = b & 0x1f; // 0b00011111
  37978. if (serviceNum === 7 && blockSize > 0) {
  37979. // Extended service num
  37980. b = packetData[i++];
  37981. serviceNum = b;
  37982. }
  37983. this.pushServiceBlock(serviceNum, i, blockSize);
  37984. if (blockSize > 0) {
  37985. i += blockSize - 1;
  37986. }
  37987. }
  37988. };
  37989. /**
  37990. * Parse service block, execute commands, read text.
  37991. *
  37992. * Note: While many of these commands serve important purposes,
  37993. * many others just parse out the parameters or attributes, but
  37994. * nothing is done with them because this is not a full and complete
  37995. * implementation of the entire 708 spec.
  37996. *
  37997. * @param {Integer} serviceNum Service number
  37998. * @param {Integer} start Start index of the 708 packet data
  37999. * @param {Integer} size Block size
  38000. */
  38001. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  38002. var b;
  38003. var i = start;
  38004. var packetData = this.current708Packet.data;
  38005. var service = this.services[serviceNum];
  38006. if (!service) {
  38007. service = this.initService(serviceNum, i);
  38008. }
  38009. for (; i < start + size && i < packetData.length; i++) {
  38010. b = packetData[i];
  38011. if (within708TextBlock(b)) {
  38012. i = this.handleText(i, service);
  38013. } else if (b === 0x18) {
  38014. i = this.multiByteCharacter(i, service);
  38015. } else if (b === 0x10) {
  38016. i = this.extendedCommands(i, service);
  38017. } else if (0x80 <= b && b <= 0x87) {
  38018. i = this.setCurrentWindow(i, service);
  38019. } else if (0x98 <= b && b <= 0x9f) {
  38020. i = this.defineWindow(i, service);
  38021. } else if (b === 0x88) {
  38022. i = this.clearWindows(i, service);
  38023. } else if (b === 0x8c) {
  38024. i = this.deleteWindows(i, service);
  38025. } else if (b === 0x89) {
  38026. i = this.displayWindows(i, service);
  38027. } else if (b === 0x8a) {
  38028. i = this.hideWindows(i, service);
  38029. } else if (b === 0x8b) {
  38030. i = this.toggleWindows(i, service);
  38031. } else if (b === 0x97) {
  38032. i = this.setWindowAttributes(i, service);
  38033. } else if (b === 0x90) {
  38034. i = this.setPenAttributes(i, service);
  38035. } else if (b === 0x91) {
  38036. i = this.setPenColor(i, service);
  38037. } else if (b === 0x92) {
  38038. i = this.setPenLocation(i, service);
  38039. } else if (b === 0x8f) {
  38040. service = this.reset(i, service);
  38041. } else if (b === 0x08) {
  38042. // BS: Backspace
  38043. service.currentWindow.backspace();
  38044. } else if (b === 0x0c) {
  38045. // FF: Form feed
  38046. service.currentWindow.clearText();
  38047. } else if (b === 0x0d) {
  38048. // CR: Carriage return
  38049. service.currentWindow.pendingNewLine = true;
  38050. } else if (b === 0x0e) {
  38051. // HCR: Horizontal carriage return
  38052. service.currentWindow.clearText();
  38053. } else if (b === 0x8d) {
  38054. // DLY: Delay, nothing to do
  38055. i++;
  38056. } else ;
  38057. }
  38058. };
  38059. /**
  38060. * Execute an extended command
  38061. *
  38062. * @param {Integer} i Current index in the 708 packet
  38063. * @param {Service} service The service object to be affected
  38064. * @return {Integer} New index after parsing
  38065. */
  38066. Cea708Stream.prototype.extendedCommands = function (i, service) {
  38067. var packetData = this.current708Packet.data;
  38068. var b = packetData[++i];
  38069. if (within708TextBlock(b)) {
  38070. i = this.handleText(i, service, {
  38071. isExtended: true
  38072. });
  38073. }
  38074. return i;
  38075. };
  38076. /**
  38077. * Get PTS value of a given byte index
  38078. *
  38079. * @param {Integer} byteIndex Index of the byte
  38080. * @return {Integer} PTS
  38081. */
  38082. Cea708Stream.prototype.getPts = function (byteIndex) {
  38083. // There's 1 pts value per 2 bytes
  38084. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  38085. };
  38086. /**
  38087. * Initializes a service
  38088. *
  38089. * @param {Integer} serviceNum Service number
  38090. * @return {Service} Initialized service object
  38091. */
  38092. Cea708Stream.prototype.initService = function (serviceNum, i) {
  38093. var serviceName = 'SERVICE' + serviceNum;
  38094. var self = this;
  38095. var serviceName;
  38096. var encoding;
  38097. if (serviceName in this.serviceEncodings) {
  38098. encoding = this.serviceEncodings[serviceName];
  38099. }
  38100. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  38101. this.services[serviceNum].init(this.getPts(i), function (pts) {
  38102. self.flushDisplayed(pts, self.services[serviceNum]);
  38103. });
  38104. return this.services[serviceNum];
  38105. };
  38106. /**
  38107. * Execute text writing to current window
  38108. *
  38109. * @param {Integer} i Current index in the 708 packet
  38110. * @param {Service} service The service object to be affected
  38111. * @return {Integer} New index after parsing
  38112. */
  38113. Cea708Stream.prototype.handleText = function (i, service, options) {
  38114. var isExtended = options && options.isExtended;
  38115. var isMultiByte = options && options.isMultiByte;
  38116. var packetData = this.current708Packet.data;
  38117. var extended = isExtended ? 0x1000 : 0x0000;
  38118. var currentByte = packetData[i];
  38119. var nextByte = packetData[i + 1];
  38120. var win = service.currentWindow;
  38121. var char;
  38122. var charCodeArray; // Use the TextDecoder if one was created for this service
  38123. if (service.textDecoder_ && !isExtended) {
  38124. if (isMultiByte) {
  38125. charCodeArray = [currentByte, nextByte];
  38126. i++;
  38127. } else {
  38128. charCodeArray = [currentByte];
  38129. }
  38130. char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  38131. } else {
  38132. char = get708CharFromCode(extended | currentByte);
  38133. }
  38134. if (win.pendingNewLine && !win.isEmpty()) {
  38135. win.newLine(this.getPts(i));
  38136. }
  38137. win.pendingNewLine = false;
  38138. win.addText(char);
  38139. return i;
  38140. };
  38141. /**
  38142. * Handle decoding of multibyte character
  38143. *
  38144. * @param {Integer} i Current index in the 708 packet
  38145. * @param {Service} service The service object to be affected
  38146. * @return {Integer} New index after parsing
  38147. */
  38148. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  38149. var packetData = this.current708Packet.data;
  38150. var firstByte = packetData[i + 1];
  38151. var secondByte = packetData[i + 2];
  38152. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  38153. i = this.handleText(++i, service, {
  38154. isMultiByte: true
  38155. });
  38156. }
  38157. return i;
  38158. };
  38159. /**
  38160. * Parse and execute the CW# command.
  38161. *
  38162. * Set the current window.
  38163. *
  38164. * @param {Integer} i Current index in the 708 packet
  38165. * @param {Service} service The service object to be affected
  38166. * @return {Integer} New index after parsing
  38167. */
  38168. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  38169. var packetData = this.current708Packet.data;
  38170. var b = packetData[i];
  38171. var windowNum = b & 0x07;
  38172. service.setCurrentWindow(windowNum);
  38173. return i;
  38174. };
  38175. /**
  38176. * Parse and execute the DF# command.
  38177. *
  38178. * Define a window and set it as the current window.
  38179. *
  38180. * @param {Integer} i Current index in the 708 packet
  38181. * @param {Service} service The service object to be affected
  38182. * @return {Integer} New index after parsing
  38183. */
  38184. Cea708Stream.prototype.defineWindow = function (i, service) {
  38185. var packetData = this.current708Packet.data;
  38186. var b = packetData[i];
  38187. var windowNum = b & 0x07;
  38188. service.setCurrentWindow(windowNum);
  38189. var win = service.currentWindow;
  38190. b = packetData[++i];
  38191. win.visible = (b & 0x20) >> 5; // v
  38192. win.rowLock = (b & 0x10) >> 4; // rl
  38193. win.columnLock = (b & 0x08) >> 3; // cl
  38194. win.priority = b & 0x07; // p
  38195. b = packetData[++i];
  38196. win.relativePositioning = (b & 0x80) >> 7; // rp
  38197. win.anchorVertical = b & 0x7f; // av
  38198. b = packetData[++i];
  38199. win.anchorHorizontal = b; // ah
  38200. b = packetData[++i];
  38201. win.anchorPoint = (b & 0xf0) >> 4; // ap
  38202. win.rowCount = b & 0x0f; // rc
  38203. b = packetData[++i];
  38204. win.columnCount = b & 0x3f; // cc
  38205. b = packetData[++i];
  38206. win.windowStyle = (b & 0x38) >> 3; // ws
  38207. win.penStyle = b & 0x07; // ps
  38208. // The spec says there are (rowCount+1) "virtual rows"
  38209. win.virtualRowCount = win.rowCount + 1;
  38210. return i;
  38211. };
  38212. /**
  38213. * Parse and execute the SWA command.
  38214. *
  38215. * Set attributes of the current window.
  38216. *
  38217. * @param {Integer} i Current index in the 708 packet
  38218. * @param {Service} service The service object to be affected
  38219. * @return {Integer} New index after parsing
  38220. */
  38221. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  38222. var packetData = this.current708Packet.data;
  38223. var b = packetData[i];
  38224. var winAttr = service.currentWindow.winAttr;
  38225. b = packetData[++i];
  38226. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  38227. winAttr.fillRed = (b & 0x30) >> 4; // fr
  38228. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  38229. winAttr.fillBlue = b & 0x03; // fb
  38230. b = packetData[++i];
  38231. winAttr.borderType = (b & 0xc0) >> 6; // bt
  38232. winAttr.borderRed = (b & 0x30) >> 4; // br
  38233. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  38234. winAttr.borderBlue = b & 0x03; // bb
  38235. b = packetData[++i];
  38236. winAttr.borderType += (b & 0x80) >> 5; // bt
  38237. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  38238. winAttr.printDirection = (b & 0x30) >> 4; // pd
  38239. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  38240. winAttr.justify = b & 0x03; // j
  38241. b = packetData[++i];
  38242. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  38243. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  38244. winAttr.displayEffect = b & 0x03; // de
  38245. return i;
  38246. };
  38247. /**
  38248. * Gather text from all displayed windows and push a caption to output.
  38249. *
  38250. * @param {Integer} i Current index in the 708 packet
  38251. * @param {Service} service The service object to be affected
  38252. */
  38253. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  38254. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  38255. // display text in the correct order, but sample files so far have not shown any issue.
  38256. for (var winId = 0; winId < 8; winId++) {
  38257. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  38258. displayedText.push(service.windows[winId].getText());
  38259. }
  38260. }
  38261. service.endPts = pts;
  38262. service.text = displayedText.join('\n\n');
  38263. this.pushCaption(service);
  38264. service.startPts = pts;
  38265. };
  38266. /**
  38267. * Push a caption to output if the caption contains text.
  38268. *
  38269. * @param {Service} service The service object to be affected
  38270. */
  38271. Cea708Stream.prototype.pushCaption = function (service) {
  38272. if (service.text !== '') {
  38273. this.trigger('data', {
  38274. startPts: service.startPts,
  38275. endPts: service.endPts,
  38276. text: service.text,
  38277. stream: 'cc708_' + service.serviceNum
  38278. });
  38279. service.text = '';
  38280. service.startPts = service.endPts;
  38281. }
  38282. };
  38283. /**
  38284. * Parse and execute the DSW command.
  38285. *
  38286. * Set visible property of windows based on the parsed bitmask.
  38287. *
  38288. * @param {Integer} i Current index in the 708 packet
  38289. * @param {Service} service The service object to be affected
  38290. * @return {Integer} New index after parsing
  38291. */
  38292. Cea708Stream.prototype.displayWindows = function (i, service) {
  38293. var packetData = this.current708Packet.data;
  38294. var b = packetData[++i];
  38295. var pts = this.getPts(i);
  38296. this.flushDisplayed(pts, service);
  38297. for (var winId = 0; winId < 8; winId++) {
  38298. if (b & 0x01 << winId) {
  38299. service.windows[winId].visible = 1;
  38300. }
  38301. }
  38302. return i;
  38303. };
  38304. /**
  38305. * Parse and execute the HDW command.
  38306. *
  38307. * Set visible property of windows based on the parsed bitmask.
  38308. *
  38309. * @param {Integer} i Current index in the 708 packet
  38310. * @param {Service} service The service object to be affected
  38311. * @return {Integer} New index after parsing
  38312. */
  38313. Cea708Stream.prototype.hideWindows = function (i, service) {
  38314. var packetData = this.current708Packet.data;
  38315. var b = packetData[++i];
  38316. var pts = this.getPts(i);
  38317. this.flushDisplayed(pts, service);
  38318. for (var winId = 0; winId < 8; winId++) {
  38319. if (b & 0x01 << winId) {
  38320. service.windows[winId].visible = 0;
  38321. }
  38322. }
  38323. return i;
  38324. };
  38325. /**
  38326. * Parse and execute the TGW command.
  38327. *
  38328. * Set visible property of windows based on the parsed bitmask.
  38329. *
  38330. * @param {Integer} i Current index in the 708 packet
  38331. * @param {Service} service The service object to be affected
  38332. * @return {Integer} New index after parsing
  38333. */
  38334. Cea708Stream.prototype.toggleWindows = function (i, service) {
  38335. var packetData = this.current708Packet.data;
  38336. var b = packetData[++i];
  38337. var pts = this.getPts(i);
  38338. this.flushDisplayed(pts, service);
  38339. for (var winId = 0; winId < 8; winId++) {
  38340. if (b & 0x01 << winId) {
  38341. service.windows[winId].visible ^= 1;
  38342. }
  38343. }
  38344. return i;
  38345. };
  38346. /**
  38347. * Parse and execute the CLW command.
  38348. *
  38349. * Clear text of windows based on the parsed bitmask.
  38350. *
  38351. * @param {Integer} i Current index in the 708 packet
  38352. * @param {Service} service The service object to be affected
  38353. * @return {Integer} New index after parsing
  38354. */
  38355. Cea708Stream.prototype.clearWindows = function (i, service) {
  38356. var packetData = this.current708Packet.data;
  38357. var b = packetData[++i];
  38358. var pts = this.getPts(i);
  38359. this.flushDisplayed(pts, service);
  38360. for (var winId = 0; winId < 8; winId++) {
  38361. if (b & 0x01 << winId) {
  38362. service.windows[winId].clearText();
  38363. }
  38364. }
  38365. return i;
  38366. };
  38367. /**
  38368. * Parse and execute the DLW command.
  38369. *
  38370. * Re-initialize windows based on the parsed bitmask.
  38371. *
  38372. * @param {Integer} i Current index in the 708 packet
  38373. * @param {Service} service The service object to be affected
  38374. * @return {Integer} New index after parsing
  38375. */
  38376. Cea708Stream.prototype.deleteWindows = function (i, service) {
  38377. var packetData = this.current708Packet.data;
  38378. var b = packetData[++i];
  38379. var pts = this.getPts(i);
  38380. this.flushDisplayed(pts, service);
  38381. for (var winId = 0; winId < 8; winId++) {
  38382. if (b & 0x01 << winId) {
  38383. service.windows[winId].reset();
  38384. }
  38385. }
  38386. return i;
  38387. };
  38388. /**
  38389. * Parse and execute the SPA command.
  38390. *
  38391. * Set pen attributes of the current window.
  38392. *
  38393. * @param {Integer} i Current index in the 708 packet
  38394. * @param {Service} service The service object to be affected
  38395. * @return {Integer} New index after parsing
  38396. */
  38397. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  38398. var packetData = this.current708Packet.data;
  38399. var b = packetData[i];
  38400. var penAttr = service.currentWindow.penAttr;
  38401. b = packetData[++i];
  38402. penAttr.textTag = (b & 0xf0) >> 4; // tt
  38403. penAttr.offset = (b & 0x0c) >> 2; // o
  38404. penAttr.penSize = b & 0x03; // s
  38405. b = packetData[++i];
  38406. penAttr.italics = (b & 0x80) >> 7; // i
  38407. penAttr.underline = (b & 0x40) >> 6; // u
  38408. penAttr.edgeType = (b & 0x38) >> 3; // et
  38409. penAttr.fontStyle = b & 0x07; // fs
  38410. return i;
  38411. };
  38412. /**
  38413. * Parse and execute the SPC command.
  38414. *
  38415. * Set pen color of the current window.
  38416. *
  38417. * @param {Integer} i Current index in the 708 packet
  38418. * @param {Service} service The service object to be affected
  38419. * @return {Integer} New index after parsing
  38420. */
  38421. Cea708Stream.prototype.setPenColor = function (i, service) {
  38422. var packetData = this.current708Packet.data;
  38423. var b = packetData[i];
  38424. var penColor = service.currentWindow.penColor;
  38425. b = packetData[++i];
  38426. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  38427. penColor.fgRed = (b & 0x30) >> 4; // fr
  38428. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  38429. penColor.fgBlue = b & 0x03; // fb
  38430. b = packetData[++i];
  38431. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  38432. penColor.bgRed = (b & 0x30) >> 4; // br
  38433. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  38434. penColor.bgBlue = b & 0x03; // bb
  38435. b = packetData[++i];
  38436. penColor.edgeRed = (b & 0x30) >> 4; // er
  38437. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  38438. penColor.edgeBlue = b & 0x03; // eb
  38439. return i;
  38440. };
  38441. /**
  38442. * Parse and execute the SPL command.
  38443. *
  38444. * Set pen location of the current window.
  38445. *
  38446. * @param {Integer} i Current index in the 708 packet
  38447. * @param {Service} service The service object to be affected
  38448. * @return {Integer} New index after parsing
  38449. */
  38450. Cea708Stream.prototype.setPenLocation = function (i, service) {
  38451. var packetData = this.current708Packet.data;
  38452. var b = packetData[i];
  38453. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  38454. service.currentWindow.pendingNewLine = true;
  38455. b = packetData[++i];
  38456. penLoc.row = b & 0x0f; // r
  38457. b = packetData[++i];
  38458. penLoc.column = b & 0x3f; // c
  38459. return i;
  38460. };
  38461. /**
  38462. * Execute the RST command.
  38463. *
  38464. * Reset service to a clean slate. Re-initialize.
  38465. *
  38466. * @param {Integer} i Current index in the 708 packet
  38467. * @param {Service} service The service object to be affected
  38468. * @return {Service} Re-initialized service
  38469. */
  38470. Cea708Stream.prototype.reset = function (i, service) {
  38471. var pts = this.getPts(i);
  38472. this.flushDisplayed(pts, service);
  38473. return this.initService(service.serviceNum, i);
  38474. }; // This hash maps non-ASCII, special, and extended character codes to their
  38475. // proper Unicode equivalent. The first keys that are only a single byte
  38476. // are the non-standard ASCII characters, which simply map the CEA608 byte
  38477. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  38478. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  38479. // can be performed regardless of the field and data channel on which the
  38480. // character code was received.
  38481. var CHARACTER_TRANSLATION = {
  38482. 0x2a: 0xe1,
  38483. // á
  38484. 0x5c: 0xe9,
  38485. // é
  38486. 0x5e: 0xed,
  38487. // í
  38488. 0x5f: 0xf3,
  38489. // ó
  38490. 0x60: 0xfa,
  38491. // ú
  38492. 0x7b: 0xe7,
  38493. // ç
  38494. 0x7c: 0xf7,
  38495. // ÷
  38496. 0x7d: 0xd1,
  38497. // Ñ
  38498. 0x7e: 0xf1,
  38499. // ñ
  38500. 0x7f: 0x2588,
  38501. // █
  38502. 0x0130: 0xae,
  38503. // ®
  38504. 0x0131: 0xb0,
  38505. // °
  38506. 0x0132: 0xbd,
  38507. // ½
  38508. 0x0133: 0xbf,
  38509. // ¿
  38510. 0x0134: 0x2122,
  38511. // ™
  38512. 0x0135: 0xa2,
  38513. // ¢
  38514. 0x0136: 0xa3,
  38515. // £
  38516. 0x0137: 0x266a,
  38517. // ♪
  38518. 0x0138: 0xe0,
  38519. // à
  38520. 0x0139: 0xa0,
  38521. //
  38522. 0x013a: 0xe8,
  38523. // è
  38524. 0x013b: 0xe2,
  38525. // â
  38526. 0x013c: 0xea,
  38527. // ê
  38528. 0x013d: 0xee,
  38529. // î
  38530. 0x013e: 0xf4,
  38531. // ô
  38532. 0x013f: 0xfb,
  38533. // û
  38534. 0x0220: 0xc1,
  38535. // Á
  38536. 0x0221: 0xc9,
  38537. // É
  38538. 0x0222: 0xd3,
  38539. // Ó
  38540. 0x0223: 0xda,
  38541. // Ú
  38542. 0x0224: 0xdc,
  38543. // Ü
  38544. 0x0225: 0xfc,
  38545. // ü
  38546. 0x0226: 0x2018,
  38547. // ‘
  38548. 0x0227: 0xa1,
  38549. // ¡
  38550. 0x0228: 0x2a,
  38551. // *
  38552. 0x0229: 0x27,
  38553. // '
  38554. 0x022a: 0x2014,
  38555. // —
  38556. 0x022b: 0xa9,
  38557. // ©
  38558. 0x022c: 0x2120,
  38559. // ℠
  38560. 0x022d: 0x2022,
  38561. // •
  38562. 0x022e: 0x201c,
  38563. // “
  38564. 0x022f: 0x201d,
  38565. // ”
  38566. 0x0230: 0xc0,
  38567. // À
  38568. 0x0231: 0xc2,
  38569. // Â
  38570. 0x0232: 0xc7,
  38571. // Ç
  38572. 0x0233: 0xc8,
  38573. // È
  38574. 0x0234: 0xca,
  38575. // Ê
  38576. 0x0235: 0xcb,
  38577. // Ë
  38578. 0x0236: 0xeb,
  38579. // ë
  38580. 0x0237: 0xce,
  38581. // Î
  38582. 0x0238: 0xcf,
  38583. // Ï
  38584. 0x0239: 0xef,
  38585. // ï
  38586. 0x023a: 0xd4,
  38587. // Ô
  38588. 0x023b: 0xd9,
  38589. // Ù
  38590. 0x023c: 0xf9,
  38591. // ù
  38592. 0x023d: 0xdb,
  38593. // Û
  38594. 0x023e: 0xab,
  38595. // «
  38596. 0x023f: 0xbb,
  38597. // »
  38598. 0x0320: 0xc3,
  38599. // Ã
  38600. 0x0321: 0xe3,
  38601. // ã
  38602. 0x0322: 0xcd,
  38603. // Í
  38604. 0x0323: 0xcc,
  38605. // Ì
  38606. 0x0324: 0xec,
  38607. // ì
  38608. 0x0325: 0xd2,
  38609. // Ò
  38610. 0x0326: 0xf2,
  38611. // ò
  38612. 0x0327: 0xd5,
  38613. // Õ
  38614. 0x0328: 0xf5,
  38615. // õ
  38616. 0x0329: 0x7b,
  38617. // {
  38618. 0x032a: 0x7d,
  38619. // }
  38620. 0x032b: 0x5c,
  38621. // \
  38622. 0x032c: 0x5e,
  38623. // ^
  38624. 0x032d: 0x5f,
  38625. // _
  38626. 0x032e: 0x7c,
  38627. // |
  38628. 0x032f: 0x7e,
  38629. // ~
  38630. 0x0330: 0xc4,
  38631. // Ä
  38632. 0x0331: 0xe4,
  38633. // ä
  38634. 0x0332: 0xd6,
  38635. // Ö
  38636. 0x0333: 0xf6,
  38637. // ö
  38638. 0x0334: 0xdf,
  38639. // ß
  38640. 0x0335: 0xa5,
  38641. // ¥
  38642. 0x0336: 0xa4,
  38643. // ¤
  38644. 0x0337: 0x2502,
  38645. // │
  38646. 0x0338: 0xc5,
  38647. // Å
  38648. 0x0339: 0xe5,
  38649. // å
  38650. 0x033a: 0xd8,
  38651. // Ø
  38652. 0x033b: 0xf8,
  38653. // ø
  38654. 0x033c: 0x250c,
  38655. // ┌
  38656. 0x033d: 0x2510,
  38657. // ┐
  38658. 0x033e: 0x2514,
  38659. // └
  38660. 0x033f: 0x2518 // ┘
  38661. };
  38662. var getCharFromCode = function (code) {
  38663. if (code === null) {
  38664. return '';
  38665. }
  38666. code = CHARACTER_TRANSLATION[code] || code;
  38667. return String.fromCharCode(code);
  38668. }; // the index of the last row in a CEA-608 display buffer
  38669. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  38670. // getting it through bit logic.
  38671. 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
  38672. // cells. The "bottom" row is the last element in the outer array.
  38673. var createDisplayBuffer = function () {
  38674. var result = [],
  38675. i = BOTTOM_ROW + 1;
  38676. while (i--) {
  38677. result.push('');
  38678. }
  38679. return result;
  38680. };
  38681. var Cea608Stream = function (field, dataChannel) {
  38682. Cea608Stream.prototype.init.call(this);
  38683. this.field_ = field || 0;
  38684. this.dataChannel_ = dataChannel || 0;
  38685. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  38686. this.setConstants();
  38687. this.reset();
  38688. this.push = function (packet) {
  38689. var data, swap, char0, char1, text; // remove the parity bits
  38690. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  38691. if (data === this.lastControlCode_) {
  38692. this.lastControlCode_ = null;
  38693. return;
  38694. } // Store control codes
  38695. if ((data & 0xf000) === 0x1000) {
  38696. this.lastControlCode_ = data;
  38697. } else if (data !== this.PADDING_) {
  38698. this.lastControlCode_ = null;
  38699. }
  38700. char0 = data >>> 8;
  38701. char1 = data & 0xff;
  38702. if (data === this.PADDING_) {
  38703. return;
  38704. } else if (data === this.RESUME_CAPTION_LOADING_) {
  38705. this.mode_ = 'popOn';
  38706. } else if (data === this.END_OF_CAPTION_) {
  38707. // If an EOC is received while in paint-on mode, the displayed caption
  38708. // text should be swapped to non-displayed memory as if it was a pop-on
  38709. // caption. Because of that, we should explicitly switch back to pop-on
  38710. // mode
  38711. this.mode_ = 'popOn';
  38712. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  38713. this.flushDisplayed(packet.pts); // flip memory
  38714. swap = this.displayed_;
  38715. this.displayed_ = this.nonDisplayed_;
  38716. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  38717. this.startPts_ = packet.pts;
  38718. } else if (data === this.ROLL_UP_2_ROWS_) {
  38719. this.rollUpRows_ = 2;
  38720. this.setRollUp(packet.pts);
  38721. } else if (data === this.ROLL_UP_3_ROWS_) {
  38722. this.rollUpRows_ = 3;
  38723. this.setRollUp(packet.pts);
  38724. } else if (data === this.ROLL_UP_4_ROWS_) {
  38725. this.rollUpRows_ = 4;
  38726. this.setRollUp(packet.pts);
  38727. } else if (data === this.CARRIAGE_RETURN_) {
  38728. this.clearFormatting(packet.pts);
  38729. this.flushDisplayed(packet.pts);
  38730. this.shiftRowsUp_();
  38731. this.startPts_ = packet.pts;
  38732. } else if (data === this.BACKSPACE_) {
  38733. if (this.mode_ === 'popOn') {
  38734. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  38735. } else {
  38736. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  38737. }
  38738. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  38739. this.flushDisplayed(packet.pts);
  38740. this.displayed_ = createDisplayBuffer();
  38741. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  38742. this.nonDisplayed_ = createDisplayBuffer();
  38743. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  38744. if (this.mode_ !== 'paintOn') {
  38745. // NOTE: This should be removed when proper caption positioning is
  38746. // implemented
  38747. this.flushDisplayed(packet.pts);
  38748. this.displayed_ = createDisplayBuffer();
  38749. }
  38750. this.mode_ = 'paintOn';
  38751. this.startPts_ = packet.pts; // Append special characters to caption text
  38752. } else if (this.isSpecialCharacter(char0, char1)) {
  38753. // Bitmask char0 so that we can apply character transformations
  38754. // regardless of field and data channel.
  38755. // Then byte-shift to the left and OR with char1 so we can pass the
  38756. // entire character code to `getCharFromCode`.
  38757. char0 = (char0 & 0x03) << 8;
  38758. text = getCharFromCode(char0 | char1);
  38759. this[this.mode_](packet.pts, text);
  38760. this.column_++; // Append extended characters to caption text
  38761. } else if (this.isExtCharacter(char0, char1)) {
  38762. // Extended characters always follow their "non-extended" equivalents.
  38763. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  38764. // decoders are supposed to drop the "è", while compliant decoders
  38765. // backspace the "e" and insert "è".
  38766. // Delete the previous character
  38767. if (this.mode_ === 'popOn') {
  38768. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  38769. } else {
  38770. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  38771. } // Bitmask char0 so that we can apply character transformations
  38772. // regardless of field and data channel.
  38773. // Then byte-shift to the left and OR with char1 so we can pass the
  38774. // entire character code to `getCharFromCode`.
  38775. char0 = (char0 & 0x03) << 8;
  38776. text = getCharFromCode(char0 | char1);
  38777. this[this.mode_](packet.pts, text);
  38778. this.column_++; // Process mid-row codes
  38779. } else if (this.isMidRowCode(char0, char1)) {
  38780. // Attributes are not additive, so clear all formatting
  38781. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  38782. // should be replaced with spaces, so add one now
  38783. this[this.mode_](packet.pts, ' ');
  38784. this.column_++;
  38785. if ((char1 & 0xe) === 0xe) {
  38786. this.addFormatting(packet.pts, ['i']);
  38787. }
  38788. if ((char1 & 0x1) === 0x1) {
  38789. this.addFormatting(packet.pts, ['u']);
  38790. } // Detect offset control codes and adjust cursor
  38791. } else if (this.isOffsetControlCode(char0, char1)) {
  38792. // Cursor position is set by indent PAC (see below) in 4-column
  38793. // increments, with an additional offset code of 1-3 to reach any
  38794. // of the 32 columns specified by CEA-608. So all we need to do
  38795. // here is increment the column cursor by the given offset.
  38796. this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
  38797. } else if (this.isPAC(char0, char1)) {
  38798. // There's no logic for PAC -> row mapping, so we have to just
  38799. // find the row code in an array and use its index :(
  38800. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  38801. if (this.mode_ === 'rollUp') {
  38802. // This implies that the base row is incorrectly set.
  38803. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  38804. // of roll-up rows set.
  38805. if (row - this.rollUpRows_ + 1 < 0) {
  38806. row = this.rollUpRows_ - 1;
  38807. }
  38808. this.setRollUp(packet.pts, row);
  38809. }
  38810. if (row !== this.row_) {
  38811. // formatting is only persistent for current row
  38812. this.clearFormatting(packet.pts);
  38813. this.row_ = row;
  38814. } // All PACs can apply underline, so detect and apply
  38815. // (All odd-numbered second bytes set underline)
  38816. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  38817. this.addFormatting(packet.pts, ['u']);
  38818. }
  38819. if ((data & 0x10) === 0x10) {
  38820. // We've got an indent level code. Each successive even number
  38821. // increments the column cursor by 4, so we can get the desired
  38822. // column position by bit-shifting to the right (to get n/2)
  38823. // and multiplying by 4.
  38824. this.column_ = ((data & 0xe) >> 1) * 4;
  38825. }
  38826. if (this.isColorPAC(char1)) {
  38827. // it's a color code, though we only support white, which
  38828. // can be either normal or italicized. white italics can be
  38829. // either 0x4e or 0x6e depending on the row, so we just
  38830. // bitwise-and with 0xe to see if italics should be turned on
  38831. if ((char1 & 0xe) === 0xe) {
  38832. this.addFormatting(packet.pts, ['i']);
  38833. }
  38834. } // We have a normal character in char0, and possibly one in char1
  38835. } else if (this.isNormalChar(char0)) {
  38836. if (char1 === 0x00) {
  38837. char1 = null;
  38838. }
  38839. text = getCharFromCode(char0);
  38840. text += getCharFromCode(char1);
  38841. this[this.mode_](packet.pts, text);
  38842. this.column_ += text.length;
  38843. } // finish data processing
  38844. };
  38845. };
  38846. Cea608Stream.prototype = new Stream$7(); // Trigger a cue point that captures the current state of the
  38847. // display buffer
  38848. Cea608Stream.prototype.flushDisplayed = function (pts) {
  38849. var content = this.displayed_ // remove spaces from the start and end of the string
  38850. .map(function (row, index) {
  38851. try {
  38852. return row.trim();
  38853. } catch (e) {
  38854. // Ordinarily, this shouldn't happen. However, caption
  38855. // parsing errors should not throw exceptions and
  38856. // break playback.
  38857. this.trigger('log', {
  38858. level: 'warn',
  38859. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  38860. });
  38861. return '';
  38862. }
  38863. }, this) // combine all text rows to display in one cue
  38864. .join('\n') // and remove blank rows from the start and end, but not the middle
  38865. .replace(/^\n+|\n+$/g, '');
  38866. if (content.length) {
  38867. this.trigger('data', {
  38868. startPts: this.startPts_,
  38869. endPts: pts,
  38870. text: content,
  38871. stream: this.name_
  38872. });
  38873. }
  38874. };
  38875. /**
  38876. * Zero out the data, used for startup and on seek
  38877. */
  38878. Cea608Stream.prototype.reset = function () {
  38879. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  38880. // actually display captions. If a caption is shifted to a row
  38881. // with a lower index than this, it is cleared from the display
  38882. // buffer
  38883. this.topRow_ = 0;
  38884. this.startPts_ = 0;
  38885. this.displayed_ = createDisplayBuffer();
  38886. this.nonDisplayed_ = createDisplayBuffer();
  38887. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  38888. this.column_ = 0;
  38889. this.row_ = BOTTOM_ROW;
  38890. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  38891. this.formatting_ = [];
  38892. };
  38893. /**
  38894. * Sets up control code and related constants for this instance
  38895. */
  38896. Cea608Stream.prototype.setConstants = function () {
  38897. // The following attributes have these uses:
  38898. // ext_ : char0 for mid-row codes, and the base for extended
  38899. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  38900. // extended codes)
  38901. // control_: char0 for control codes, except byte-shifted to the
  38902. // left so that we can do this.control_ | CONTROL_CODE
  38903. // offset_: char0 for tab offset codes
  38904. //
  38905. // It's also worth noting that control codes, and _only_ control codes,
  38906. // differ between field 1 and field2. Field 2 control codes are always
  38907. // their field 1 value plus 1. That's why there's the "| field" on the
  38908. // control value.
  38909. if (this.dataChannel_ === 0) {
  38910. this.BASE_ = 0x10;
  38911. this.EXT_ = 0x11;
  38912. this.CONTROL_ = (0x14 | this.field_) << 8;
  38913. this.OFFSET_ = 0x17;
  38914. } else if (this.dataChannel_ === 1) {
  38915. this.BASE_ = 0x18;
  38916. this.EXT_ = 0x19;
  38917. this.CONTROL_ = (0x1c | this.field_) << 8;
  38918. this.OFFSET_ = 0x1f;
  38919. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  38920. // list is not exhaustive. For a more comprehensive listing and semantics see
  38921. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  38922. // Padding
  38923. this.PADDING_ = 0x0000; // Pop-on Mode
  38924. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  38925. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  38926. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  38927. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  38928. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  38929. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  38930. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  38931. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  38932. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  38933. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  38934. };
  38935. /**
  38936. * Detects if the 2-byte packet data is a special character
  38937. *
  38938. * Special characters have a second byte in the range 0x30 to 0x3f,
  38939. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  38940. * data channel 2).
  38941. *
  38942. * @param {Integer} char0 The first byte
  38943. * @param {Integer} char1 The second byte
  38944. * @return {Boolean} Whether the 2 bytes are an special character
  38945. */
  38946. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  38947. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  38948. };
  38949. /**
  38950. * Detects if the 2-byte packet data is an extended character
  38951. *
  38952. * Extended characters have a second byte in the range 0x20 to 0x3f,
  38953. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  38954. * 0x1a or 0x1b (for data channel 2).
  38955. *
  38956. * @param {Integer} char0 The first byte
  38957. * @param {Integer} char1 The second byte
  38958. * @return {Boolean} Whether the 2 bytes are an extended character
  38959. */
  38960. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  38961. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  38962. };
  38963. /**
  38964. * Detects if the 2-byte packet is a mid-row code
  38965. *
  38966. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  38967. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  38968. * channel 2).
  38969. *
  38970. * @param {Integer} char0 The first byte
  38971. * @param {Integer} char1 The second byte
  38972. * @return {Boolean} Whether the 2 bytes are a mid-row code
  38973. */
  38974. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  38975. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  38976. };
  38977. /**
  38978. * Detects if the 2-byte packet is an offset control code
  38979. *
  38980. * Offset control codes have a second byte in the range 0x21 to 0x23,
  38981. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  38982. * data channel 2).
  38983. *
  38984. * @param {Integer} char0 The first byte
  38985. * @param {Integer} char1 The second byte
  38986. * @return {Boolean} Whether the 2 bytes are an offset control code
  38987. */
  38988. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  38989. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  38990. };
  38991. /**
  38992. * Detects if the 2-byte packet is a Preamble Address Code
  38993. *
  38994. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  38995. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  38996. * range 0x40 to 0x7f.
  38997. *
  38998. * @param {Integer} char0 The first byte
  38999. * @param {Integer} char1 The second byte
  39000. * @return {Boolean} Whether the 2 bytes are a PAC
  39001. */
  39002. Cea608Stream.prototype.isPAC = function (char0, char1) {
  39003. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  39004. };
  39005. /**
  39006. * Detects if a packet's second byte is in the range of a PAC color code
  39007. *
  39008. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  39009. * 0x60 to 0x6f.
  39010. *
  39011. * @param {Integer} char1 The second byte
  39012. * @return {Boolean} Whether the byte is a color PAC
  39013. */
  39014. Cea608Stream.prototype.isColorPAC = function (char1) {
  39015. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  39016. };
  39017. /**
  39018. * Detects if a single byte is in the range of a normal character
  39019. *
  39020. * Normal text bytes are in the range 0x20 to 0x7f.
  39021. *
  39022. * @param {Integer} char The byte
  39023. * @return {Boolean} Whether the byte is a normal character
  39024. */
  39025. Cea608Stream.prototype.isNormalChar = function (char) {
  39026. return char >= 0x20 && char <= 0x7f;
  39027. };
  39028. /**
  39029. * Configures roll-up
  39030. *
  39031. * @param {Integer} pts Current PTS
  39032. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  39033. * a new position
  39034. */
  39035. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  39036. // Reset the base row to the bottom row when switching modes
  39037. if (this.mode_ !== 'rollUp') {
  39038. this.row_ = BOTTOM_ROW;
  39039. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  39040. this.flushDisplayed(pts);
  39041. this.nonDisplayed_ = createDisplayBuffer();
  39042. this.displayed_ = createDisplayBuffer();
  39043. }
  39044. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  39045. // move currently displayed captions (up or down) to the new base row
  39046. for (var i = 0; i < this.rollUpRows_; i++) {
  39047. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  39048. this.displayed_[this.row_ - i] = '';
  39049. }
  39050. }
  39051. if (newBaseRow === undefined) {
  39052. newBaseRow = this.row_;
  39053. }
  39054. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  39055. }; // Adds the opening HTML tag for the passed character to the caption text,
  39056. // and keeps track of it for later closing
  39057. Cea608Stream.prototype.addFormatting = function (pts, format) {
  39058. this.formatting_ = this.formatting_.concat(format);
  39059. var text = format.reduce(function (text, format) {
  39060. return text + '<' + format + '>';
  39061. }, '');
  39062. this[this.mode_](pts, text);
  39063. }; // Adds HTML closing tags for current formatting to caption text and
  39064. // clears remembered formatting
  39065. Cea608Stream.prototype.clearFormatting = function (pts) {
  39066. if (!this.formatting_.length) {
  39067. return;
  39068. }
  39069. var text = this.formatting_.reverse().reduce(function (text, format) {
  39070. return text + '</' + format + '>';
  39071. }, '');
  39072. this.formatting_ = [];
  39073. this[this.mode_](pts, text);
  39074. }; // Mode Implementations
  39075. Cea608Stream.prototype.popOn = function (pts, text) {
  39076. var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
  39077. baseRow += text;
  39078. this.nonDisplayed_[this.row_] = baseRow;
  39079. };
  39080. Cea608Stream.prototype.rollUp = function (pts, text) {
  39081. var baseRow = this.displayed_[this.row_];
  39082. baseRow += text;
  39083. this.displayed_[this.row_] = baseRow;
  39084. };
  39085. Cea608Stream.prototype.shiftRowsUp_ = function () {
  39086. var i; // clear out inactive rows
  39087. for (i = 0; i < this.topRow_; i++) {
  39088. this.displayed_[i] = '';
  39089. }
  39090. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  39091. this.displayed_[i] = '';
  39092. } // shift displayed rows up
  39093. for (i = this.topRow_; i < this.row_; i++) {
  39094. this.displayed_[i] = this.displayed_[i + 1];
  39095. } // clear out the bottom row
  39096. this.displayed_[this.row_] = '';
  39097. };
  39098. Cea608Stream.prototype.paintOn = function (pts, text) {
  39099. var baseRow = this.displayed_[this.row_];
  39100. baseRow += text;
  39101. this.displayed_[this.row_] = baseRow;
  39102. }; // exports
  39103. var captionStream = {
  39104. CaptionStream: CaptionStream$2,
  39105. Cea608Stream: Cea608Stream,
  39106. Cea708Stream: Cea708Stream
  39107. };
  39108. /**
  39109. * mux.js
  39110. *
  39111. * Copyright (c) Brightcove
  39112. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  39113. */
  39114. var streamTypes = {
  39115. H264_STREAM_TYPE: 0x1B,
  39116. ADTS_STREAM_TYPE: 0x0F,
  39117. METADATA_STREAM_TYPE: 0x15
  39118. };
  39119. /**
  39120. * mux.js
  39121. *
  39122. * Copyright (c) Brightcove
  39123. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  39124. *
  39125. * Accepts program elementary stream (PES) data events and corrects
  39126. * decode and presentation time stamps to account for a rollover
  39127. * of the 33 bit value.
  39128. */
  39129. var Stream$6 = stream;
  39130. var MAX_TS = 8589934592;
  39131. var RO_THRESH = 4294967296;
  39132. var TYPE_SHARED = 'shared';
  39133. var handleRollover$1 = function (value, reference) {
  39134. var direction = 1;
  39135. if (value > reference) {
  39136. // If the current timestamp value is greater than our reference timestamp and we detect a
  39137. // timestamp rollover, this means the roll over is happening in the opposite direction.
  39138. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  39139. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  39140. // rollover point. In loading this segment, the timestamp values will be very large,
  39141. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  39142. // the time stamp to be `value - 2^33`.
  39143. direction = -1;
  39144. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  39145. // cause an incorrect adjustment.
  39146. while (Math.abs(reference - value) > RO_THRESH) {
  39147. value += direction * MAX_TS;
  39148. }
  39149. return value;
  39150. };
  39151. var TimestampRolloverStream$1 = function (type) {
  39152. var lastDTS, referenceDTS;
  39153. TimestampRolloverStream$1.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  39154. // video and audio. We could use `undefined` here, but having a string
  39155. // makes debugging a little clearer.
  39156. this.type_ = type || TYPE_SHARED;
  39157. this.push = function (data) {
  39158. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  39159. // streams will only accept data that matches their type.
  39160. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  39161. return;
  39162. }
  39163. if (referenceDTS === undefined) {
  39164. referenceDTS = data.dts;
  39165. }
  39166. data.dts = handleRollover$1(data.dts, referenceDTS);
  39167. data.pts = handleRollover$1(data.pts, referenceDTS);
  39168. lastDTS = data.dts;
  39169. this.trigger('data', data);
  39170. };
  39171. this.flush = function () {
  39172. referenceDTS = lastDTS;
  39173. this.trigger('done');
  39174. };
  39175. this.endTimeline = function () {
  39176. this.flush();
  39177. this.trigger('endedtimeline');
  39178. };
  39179. this.discontinuity = function () {
  39180. referenceDTS = void 0;
  39181. lastDTS = void 0;
  39182. };
  39183. this.reset = function () {
  39184. this.discontinuity();
  39185. this.trigger('reset');
  39186. };
  39187. };
  39188. TimestampRolloverStream$1.prototype = new Stream$6();
  39189. var timestampRolloverStream = {
  39190. TimestampRolloverStream: TimestampRolloverStream$1,
  39191. handleRollover: handleRollover$1
  39192. }; // Once IE11 support is dropped, this function should be removed.
  39193. var typedArrayIndexOf$1 = (typedArray, element, fromIndex) => {
  39194. if (!typedArray) {
  39195. return -1;
  39196. }
  39197. var currentIndex = fromIndex;
  39198. for (; currentIndex < typedArray.length; currentIndex++) {
  39199. if (typedArray[currentIndex] === element) {
  39200. return currentIndex;
  39201. }
  39202. }
  39203. return -1;
  39204. };
  39205. var typedArray = {
  39206. typedArrayIndexOf: typedArrayIndexOf$1
  39207. };
  39208. /**
  39209. * mux.js
  39210. *
  39211. * Copyright (c) Brightcove
  39212. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  39213. *
  39214. * Tools for parsing ID3 frame data
  39215. * @see http://id3.org/id3v2.3.0
  39216. */
  39217. var typedArrayIndexOf = typedArray.typedArrayIndexOf,
  39218. // Frames that allow different types of text encoding contain a text
  39219. // encoding description byte [ID3v2.4.0 section 4.]
  39220. textEncodingDescriptionByte = {
  39221. Iso88591: 0x00,
  39222. // ISO-8859-1, terminated with \0.
  39223. Utf16: 0x01,
  39224. // UTF-16 encoded Unicode BOM, terminated with \0\0
  39225. Utf16be: 0x02,
  39226. // UTF-16BE encoded Unicode, without BOM, terminated with \0\0
  39227. Utf8: 0x03 // UTF-8 encoded Unicode, terminated with \0
  39228. },
  39229. // return a percent-encoded representation of the specified byte range
  39230. // @see http://en.wikipedia.org/wiki/Percent-encoding
  39231. percentEncode$1 = function (bytes, start, end) {
  39232. var i,
  39233. result = '';
  39234. for (i = start; i < end; i++) {
  39235. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  39236. }
  39237. return result;
  39238. },
  39239. // return the string representation of the specified byte range,
  39240. // interpreted as UTf-8.
  39241. parseUtf8 = function (bytes, start, end) {
  39242. return decodeURIComponent(percentEncode$1(bytes, start, end));
  39243. },
  39244. // return the string representation of the specified byte range,
  39245. // interpreted as ISO-8859-1.
  39246. parseIso88591$1 = function (bytes, start, end) {
  39247. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  39248. },
  39249. parseSyncSafeInteger$1 = function (data) {
  39250. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  39251. },
  39252. frameParsers = {
  39253. 'APIC': function (frame) {
  39254. var i = 1,
  39255. mimeTypeEndIndex,
  39256. descriptionEndIndex,
  39257. LINK_MIME_TYPE = '-->';
  39258. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  39259. // ignore frames with unrecognized character encodings
  39260. return;
  39261. } // parsing fields [ID3v2.4.0 section 4.14.]
  39262. mimeTypeEndIndex = typedArrayIndexOf(frame.data, 0, i);
  39263. if (mimeTypeEndIndex < 0) {
  39264. // malformed frame
  39265. return;
  39266. } // parsing Mime type field (terminated with \0)
  39267. frame.mimeType = parseIso88591$1(frame.data, i, mimeTypeEndIndex);
  39268. i = mimeTypeEndIndex + 1; // parsing 1-byte Picture Type field
  39269. frame.pictureType = frame.data[i];
  39270. i++;
  39271. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, i);
  39272. if (descriptionEndIndex < 0) {
  39273. // malformed frame
  39274. return;
  39275. } // parsing Description field (terminated with \0)
  39276. frame.description = parseUtf8(frame.data, i, descriptionEndIndex);
  39277. i = descriptionEndIndex + 1;
  39278. if (frame.mimeType === LINK_MIME_TYPE) {
  39279. // parsing Picture Data field as URL (always represented as ISO-8859-1 [ID3v2.4.0 section 4.])
  39280. frame.url = parseIso88591$1(frame.data, i, frame.data.length);
  39281. } else {
  39282. // parsing Picture Data field as binary data
  39283. frame.pictureData = frame.data.subarray(i, frame.data.length);
  39284. }
  39285. },
  39286. 'T*': function (frame) {
  39287. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  39288. // ignore frames with unrecognized character encodings
  39289. return;
  39290. } // parse text field, do not include null terminator in the frame value
  39291. // frames that allow different types of encoding contain terminated text [ID3v2.4.0 section 4.]
  39292. frame.value = parseUtf8(frame.data, 1, frame.data.length).replace(/\0*$/, ''); // text information frames supports multiple strings, stored as a terminator separated list [ID3v2.4.0 section 4.2.]
  39293. frame.values = frame.value.split('\0');
  39294. },
  39295. 'TXXX': function (frame) {
  39296. var descriptionEndIndex;
  39297. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  39298. // ignore frames with unrecognized character encodings
  39299. return;
  39300. }
  39301. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  39302. if (descriptionEndIndex === -1) {
  39303. return;
  39304. } // parse the text fields
  39305. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // do not include the null terminator in the tag value
  39306. // frames that allow different types of encoding contain terminated text
  39307. // [ID3v2.4.0 section 4.]
  39308. frame.value = parseUtf8(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0*$/, '');
  39309. frame.data = frame.value;
  39310. },
  39311. 'W*': function (frame) {
  39312. // parse URL field; URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  39313. // if the value is followed by a string termination all the following information should be ignored [ID3v2.4.0 section 4.3]
  39314. frame.url = parseIso88591$1(frame.data, 0, frame.data.length).replace(/\0.*$/, '');
  39315. },
  39316. 'WXXX': function (frame) {
  39317. var descriptionEndIndex;
  39318. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  39319. // ignore frames with unrecognized character encodings
  39320. return;
  39321. }
  39322. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  39323. if (descriptionEndIndex === -1) {
  39324. return;
  39325. } // parse the description and URL fields
  39326. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  39327. // if the value is followed by a string termination all the following information
  39328. // should be ignored [ID3v2.4.0 section 4.3]
  39329. frame.url = parseIso88591$1(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0.*$/, '');
  39330. },
  39331. 'PRIV': function (frame) {
  39332. var i;
  39333. for (i = 0; i < frame.data.length; i++) {
  39334. if (frame.data[i] === 0) {
  39335. // parse the description and URL fields
  39336. frame.owner = parseIso88591$1(frame.data, 0, i);
  39337. break;
  39338. }
  39339. }
  39340. frame.privateData = frame.data.subarray(i + 1);
  39341. frame.data = frame.privateData;
  39342. }
  39343. };
  39344. var parseId3Frames$1 = function (data) {
  39345. var frameSize,
  39346. frameHeader,
  39347. frameStart = 10,
  39348. tagSize = 0,
  39349. frames = []; // If we don't have enough data for a header, 10 bytes,
  39350. // or 'ID3' in the first 3 bytes this is not a valid ID3 tag.
  39351. if (data.length < 10 || data[0] !== 'I'.charCodeAt(0) || data[1] !== 'D'.charCodeAt(0) || data[2] !== '3'.charCodeAt(0)) {
  39352. return;
  39353. } // the frame size is transmitted as a 28-bit integer in the
  39354. // last four bytes of the ID3 header.
  39355. // The most significant bit of each byte is dropped and the
  39356. // results concatenated to recover the actual value.
  39357. tagSize = parseSyncSafeInteger$1(data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  39358. // convenient for our comparisons to include it
  39359. tagSize += 10; // check bit 6 of byte 5 for the extended header flag.
  39360. var hasExtendedHeader = data[5] & 0x40;
  39361. if (hasExtendedHeader) {
  39362. // advance the frame start past the extended header
  39363. frameStart += 4; // header size field
  39364. frameStart += parseSyncSafeInteger$1(data.subarray(10, 14));
  39365. tagSize -= parseSyncSafeInteger$1(data.subarray(16, 20)); // clip any padding off the end
  39366. } // parse one or more ID3 frames
  39367. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  39368. do {
  39369. // determine the number of bytes in this frame
  39370. frameSize = parseSyncSafeInteger$1(data.subarray(frameStart + 4, frameStart + 8));
  39371. if (frameSize < 1) {
  39372. break;
  39373. }
  39374. frameHeader = String.fromCharCode(data[frameStart], data[frameStart + 1], data[frameStart + 2], data[frameStart + 3]);
  39375. var frame = {
  39376. id: frameHeader,
  39377. data: data.subarray(frameStart + 10, frameStart + frameSize + 10)
  39378. };
  39379. frame.key = frame.id; // parse frame values
  39380. if (frameParsers[frame.id]) {
  39381. // use frame specific parser
  39382. frameParsers[frame.id](frame);
  39383. } else if (frame.id[0] === 'T') {
  39384. // use text frame generic parser
  39385. frameParsers['T*'](frame);
  39386. } else if (frame.id[0] === 'W') {
  39387. // use URL link frame generic parser
  39388. frameParsers['W*'](frame);
  39389. }
  39390. frames.push(frame);
  39391. frameStart += 10; // advance past the frame header
  39392. frameStart += frameSize; // advance past the frame body
  39393. } while (frameStart < tagSize);
  39394. return frames;
  39395. };
  39396. var parseId3 = {
  39397. parseId3Frames: parseId3Frames$1,
  39398. parseSyncSafeInteger: parseSyncSafeInteger$1,
  39399. frameParsers: frameParsers
  39400. };
  39401. /**
  39402. * mux.js
  39403. *
  39404. * Copyright (c) Brightcove
  39405. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  39406. *
  39407. * Accepts program elementary stream (PES) data events and parses out
  39408. * ID3 metadata from them, if present.
  39409. * @see http://id3.org/id3v2.3.0
  39410. */
  39411. var Stream$5 = stream,
  39412. StreamTypes$3 = streamTypes,
  39413. id3 = parseId3,
  39414. MetadataStream;
  39415. MetadataStream = function (options) {
  39416. var settings = {
  39417. // the bytes of the program-level descriptor field in MP2T
  39418. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  39419. // program element descriptors"
  39420. descriptor: options && options.descriptor
  39421. },
  39422. // the total size in bytes of the ID3 tag being parsed
  39423. tagSize = 0,
  39424. // tag data that is not complete enough to be parsed
  39425. buffer = [],
  39426. // the total number of bytes currently in the buffer
  39427. bufferSize = 0,
  39428. i;
  39429. MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  39430. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  39431. this.dispatchType = StreamTypes$3.METADATA_STREAM_TYPE.toString(16);
  39432. if (settings.descriptor) {
  39433. for (i = 0; i < settings.descriptor.length; i++) {
  39434. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  39435. }
  39436. }
  39437. this.push = function (chunk) {
  39438. var tag, frameStart, frameSize, frame, i, frameHeader;
  39439. if (chunk.type !== 'timed-metadata') {
  39440. return;
  39441. } // if data_alignment_indicator is set in the PES header,
  39442. // we must have the start of a new ID3 tag. Assume anything
  39443. // remaining in the buffer was malformed and throw it out
  39444. if (chunk.dataAlignmentIndicator) {
  39445. bufferSize = 0;
  39446. buffer.length = 0;
  39447. } // ignore events that don't look like ID3 data
  39448. 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))) {
  39449. this.trigger('log', {
  39450. level: 'warn',
  39451. message: 'Skipping unrecognized metadata packet'
  39452. });
  39453. return;
  39454. } // add this chunk to the data we've collected so far
  39455. buffer.push(chunk);
  39456. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  39457. if (buffer.length === 1) {
  39458. // the frame size is transmitted as a 28-bit integer in the
  39459. // last four bytes of the ID3 header.
  39460. // The most significant bit of each byte is dropped and the
  39461. // results concatenated to recover the actual value.
  39462. tagSize = id3.parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  39463. // convenient for our comparisons to include it
  39464. tagSize += 10;
  39465. } // if the entire frame has not arrived, wait for more data
  39466. if (bufferSize < tagSize) {
  39467. return;
  39468. } // collect the entire frame so it can be parsed
  39469. tag = {
  39470. data: new Uint8Array(tagSize),
  39471. frames: [],
  39472. pts: buffer[0].pts,
  39473. dts: buffer[0].dts
  39474. };
  39475. for (i = 0; i < tagSize;) {
  39476. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  39477. i += buffer[0].data.byteLength;
  39478. bufferSize -= buffer[0].data.byteLength;
  39479. buffer.shift();
  39480. } // find the start of the first frame and the end of the tag
  39481. frameStart = 10;
  39482. if (tag.data[5] & 0x40) {
  39483. // advance the frame start past the extended header
  39484. frameStart += 4; // header size field
  39485. frameStart += id3.parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end
  39486. tagSize -= id3.parseSyncSafeInteger(tag.data.subarray(16, 20));
  39487. } // parse one or more ID3 frames
  39488. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  39489. do {
  39490. // determine the number of bytes in this frame
  39491. frameSize = id3.parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  39492. if (frameSize < 1) {
  39493. this.trigger('log', {
  39494. level: 'warn',
  39495. message: 'Malformed ID3 frame encountered. Skipping remaining metadata parsing.'
  39496. }); // If the frame is malformed, don't parse any further frames but allow previous valid parsed frames
  39497. // to be sent along.
  39498. break;
  39499. }
  39500. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  39501. frame = {
  39502. id: frameHeader,
  39503. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  39504. };
  39505. frame.key = frame.id; // parse frame values
  39506. if (id3.frameParsers[frame.id]) {
  39507. // use frame specific parser
  39508. id3.frameParsers[frame.id](frame);
  39509. } else if (frame.id[0] === 'T') {
  39510. // use text frame generic parser
  39511. id3.frameParsers['T*'](frame);
  39512. } else if (frame.id[0] === 'W') {
  39513. // use URL link frame generic parser
  39514. id3.frameParsers['W*'](frame);
  39515. } // handle the special PRIV frame used to indicate the start
  39516. // time for raw AAC data
  39517. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  39518. var d = frame.data,
  39519. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  39520. size *= 4;
  39521. size += d[7] & 0x03;
  39522. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  39523. // on the value of this frame
  39524. // we couldn't have known the appropriate pts and dts before
  39525. // parsing this ID3 tag so set those values now
  39526. if (tag.pts === undefined && tag.dts === undefined) {
  39527. tag.pts = frame.timeStamp;
  39528. tag.dts = frame.timeStamp;
  39529. }
  39530. this.trigger('timestamp', frame);
  39531. }
  39532. tag.frames.push(frame);
  39533. frameStart += 10; // advance past the frame header
  39534. frameStart += frameSize; // advance past the frame body
  39535. } while (frameStart < tagSize);
  39536. this.trigger('data', tag);
  39537. };
  39538. };
  39539. MetadataStream.prototype = new Stream$5();
  39540. var metadataStream = MetadataStream;
  39541. /**
  39542. * mux.js
  39543. *
  39544. * Copyright (c) Brightcove
  39545. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  39546. *
  39547. * A stream-based mp2t to mp4 converter. This utility can be used to
  39548. * deliver mp4s to a SourceBuffer on platforms that support native
  39549. * Media Source Extensions.
  39550. */
  39551. var Stream$4 = stream,
  39552. CaptionStream$1 = captionStream,
  39553. StreamTypes$2 = streamTypes,
  39554. TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  39555. var TransportPacketStream, TransportParseStream, ElementaryStream; // constants
  39556. var MP2T_PACKET_LENGTH$1 = 188,
  39557. // bytes
  39558. SYNC_BYTE$1 = 0x47;
  39559. /**
  39560. * Splits an incoming stream of binary data into MPEG-2 Transport
  39561. * Stream packets.
  39562. */
  39563. TransportPacketStream = function () {
  39564. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  39565. bytesInBuffer = 0;
  39566. TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  39567. /**
  39568. * Split a stream of data into M2TS packets
  39569. **/
  39570. this.push = function (bytes) {
  39571. var startIndex = 0,
  39572. endIndex = MP2T_PACKET_LENGTH$1,
  39573. everything; // If there are bytes remaining from the last segment, prepend them to the
  39574. // bytes that were pushed in
  39575. if (bytesInBuffer) {
  39576. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  39577. everything.set(buffer.subarray(0, bytesInBuffer));
  39578. everything.set(bytes, bytesInBuffer);
  39579. bytesInBuffer = 0;
  39580. } else {
  39581. everything = bytes;
  39582. } // While we have enough data for a packet
  39583. while (endIndex < everything.byteLength) {
  39584. // Look for a pair of start and end sync bytes in the data..
  39585. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  39586. // We found a packet so emit it and jump one whole packet forward in
  39587. // the stream
  39588. this.trigger('data', everything.subarray(startIndex, endIndex));
  39589. startIndex += MP2T_PACKET_LENGTH$1;
  39590. endIndex += MP2T_PACKET_LENGTH$1;
  39591. continue;
  39592. } // If we get here, we have somehow become de-synchronized and we need to step
  39593. // forward one byte at a time until we find a pair of sync bytes that denote
  39594. // a packet
  39595. startIndex++;
  39596. endIndex++;
  39597. } // If there was some data left over at the end of the segment that couldn't
  39598. // possibly be a whole packet, keep it because it might be the start of a packet
  39599. // that continues in the next segment
  39600. if (startIndex < everything.byteLength) {
  39601. buffer.set(everything.subarray(startIndex), 0);
  39602. bytesInBuffer = everything.byteLength - startIndex;
  39603. }
  39604. };
  39605. /**
  39606. * Passes identified M2TS packets to the TransportParseStream to be parsed
  39607. **/
  39608. this.flush = function () {
  39609. // If the buffer contains a whole packet when we are being flushed, emit it
  39610. // and empty the buffer. Otherwise hold onto the data because it may be
  39611. // important for decoding the next segment
  39612. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  39613. this.trigger('data', buffer);
  39614. bytesInBuffer = 0;
  39615. }
  39616. this.trigger('done');
  39617. };
  39618. this.endTimeline = function () {
  39619. this.flush();
  39620. this.trigger('endedtimeline');
  39621. };
  39622. this.reset = function () {
  39623. bytesInBuffer = 0;
  39624. this.trigger('reset');
  39625. };
  39626. };
  39627. TransportPacketStream.prototype = new Stream$4();
  39628. /**
  39629. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  39630. * forms of the individual transport stream packets.
  39631. */
  39632. TransportParseStream = function () {
  39633. var parsePsi, parsePat, parsePmt, self;
  39634. TransportParseStream.prototype.init.call(this);
  39635. self = this;
  39636. this.packetsWaitingForPmt = [];
  39637. this.programMapTable = undefined;
  39638. parsePsi = function (payload, psi) {
  39639. var offset = 0; // PSI packets may be split into multiple sections and those
  39640. // sections may be split into multiple packets. If a PSI
  39641. // section starts in this packet, the payload_unit_start_indicator
  39642. // will be true and the first byte of the payload will indicate
  39643. // the offset from the current position to the start of the
  39644. // section.
  39645. if (psi.payloadUnitStartIndicator) {
  39646. offset += payload[offset] + 1;
  39647. }
  39648. if (psi.type === 'pat') {
  39649. parsePat(payload.subarray(offset), psi);
  39650. } else {
  39651. parsePmt(payload.subarray(offset), psi);
  39652. }
  39653. };
  39654. parsePat = function (payload, pat) {
  39655. pat.section_number = payload[7]; // eslint-disable-line camelcase
  39656. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  39657. // skip the PSI header and parse the first PMT entry
  39658. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  39659. pat.pmtPid = self.pmtPid;
  39660. };
  39661. /**
  39662. * Parse out the relevant fields of a Program Map Table (PMT).
  39663. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  39664. * packet. The first byte in this array should be the table_id
  39665. * field.
  39666. * @param pmt {object} the object that should be decorated with
  39667. * fields parsed from the PMT.
  39668. */
  39669. parsePmt = function (payload, pmt) {
  39670. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  39671. // take effect. We don't believe this should ever be the case
  39672. // for HLS but we'll ignore "forward" PMT declarations if we see
  39673. // them. Future PMT declarations have the current_next_indicator
  39674. // set to zero.
  39675. if (!(payload[5] & 0x01)) {
  39676. return;
  39677. } // overwrite any existing program map table
  39678. self.programMapTable = {
  39679. video: null,
  39680. audio: null,
  39681. 'timed-metadata': {}
  39682. }; // the mapping table ends at the end of the current section
  39683. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  39684. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  39685. // long the program info descriptors are
  39686. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  39687. offset = 12 + programInfoLength;
  39688. while (offset < tableEnd) {
  39689. var streamType = payload[offset];
  39690. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  39691. // TODO: should this be done for metadata too? for now maintain behavior of
  39692. // multiple metadata streams
  39693. if (streamType === StreamTypes$2.H264_STREAM_TYPE && self.programMapTable.video === null) {
  39694. self.programMapTable.video = pid;
  39695. } else if (streamType === StreamTypes$2.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  39696. self.programMapTable.audio = pid;
  39697. } else if (streamType === StreamTypes$2.METADATA_STREAM_TYPE) {
  39698. // map pid to stream type for metadata streams
  39699. self.programMapTable['timed-metadata'][pid] = streamType;
  39700. } // move to the next table entry
  39701. // skip past the elementary stream descriptors, if present
  39702. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  39703. } // record the map on the packet as well
  39704. pmt.programMapTable = self.programMapTable;
  39705. };
  39706. /**
  39707. * Deliver a new MP2T packet to the next stream in the pipeline.
  39708. */
  39709. this.push = function (packet) {
  39710. var result = {},
  39711. offset = 4;
  39712. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  39713. result.pid = packet[1] & 0x1f;
  39714. result.pid <<= 8;
  39715. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  39716. // fifth byte of the TS packet header. The adaptation field is
  39717. // used to add stuffing to PES packets that don't fill a complete
  39718. // TS packet, and to specify some forms of timing and control data
  39719. // that we do not currently use.
  39720. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  39721. offset += packet[offset] + 1;
  39722. } // parse the rest of the packet based on the type
  39723. if (result.pid === 0) {
  39724. result.type = 'pat';
  39725. parsePsi(packet.subarray(offset), result);
  39726. this.trigger('data', result);
  39727. } else if (result.pid === this.pmtPid) {
  39728. result.type = 'pmt';
  39729. parsePsi(packet.subarray(offset), result);
  39730. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  39731. while (this.packetsWaitingForPmt.length) {
  39732. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  39733. }
  39734. } else if (this.programMapTable === undefined) {
  39735. // When we have not seen a PMT yet, defer further processing of
  39736. // PES packets until one has been parsed
  39737. this.packetsWaitingForPmt.push([packet, offset, result]);
  39738. } else {
  39739. this.processPes_(packet, offset, result);
  39740. }
  39741. };
  39742. this.processPes_ = function (packet, offset, result) {
  39743. // set the appropriate stream type
  39744. if (result.pid === this.programMapTable.video) {
  39745. result.streamType = StreamTypes$2.H264_STREAM_TYPE;
  39746. } else if (result.pid === this.programMapTable.audio) {
  39747. result.streamType = StreamTypes$2.ADTS_STREAM_TYPE;
  39748. } else {
  39749. // if not video or audio, it is timed-metadata or unknown
  39750. // if unknown, streamType will be undefined
  39751. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  39752. }
  39753. result.type = 'pes';
  39754. result.data = packet.subarray(offset);
  39755. this.trigger('data', result);
  39756. };
  39757. };
  39758. TransportParseStream.prototype = new Stream$4();
  39759. TransportParseStream.STREAM_TYPES = {
  39760. h264: 0x1b,
  39761. adts: 0x0f
  39762. };
  39763. /**
  39764. * Reconsistutes program elementary stream (PES) packets from parsed
  39765. * transport stream packets. That is, if you pipe an
  39766. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  39767. * events will be events which capture the bytes for individual PES
  39768. * packets plus relevant metadata that has been extracted from the
  39769. * container.
  39770. */
  39771. ElementaryStream = function () {
  39772. var self = this,
  39773. segmentHadPmt = false,
  39774. // PES packet fragments
  39775. video = {
  39776. data: [],
  39777. size: 0
  39778. },
  39779. audio = {
  39780. data: [],
  39781. size: 0
  39782. },
  39783. timedMetadata = {
  39784. data: [],
  39785. size: 0
  39786. },
  39787. programMapTable,
  39788. parsePes = function (payload, pes) {
  39789. var ptsDtsFlags;
  39790. const startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  39791. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  39792. // that are frame data that is continuing from the previous fragment. This
  39793. // is to check that the pes data is the start of a new pes payload
  39794. if (startPrefix !== 1) {
  39795. return;
  39796. } // get the packet length, this will be 0 for video
  39797. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  39798. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  39799. // and a DTS value. Determine what combination of values is
  39800. // available to work with.
  39801. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  39802. // performs all bitwise operations on 32-bit integers but javascript
  39803. // supports a much greater range (52-bits) of integer using standard
  39804. // mathematical operations.
  39805. // We construct a 31-bit value using bitwise operators over the 31
  39806. // most significant bits and then multiply by 4 (equal to a left-shift
  39807. // of 2) before we add the final 2 least significant bits of the
  39808. // timestamp (equal to an OR.)
  39809. if (ptsDtsFlags & 0xC0) {
  39810. // the PTS and DTS are not written out directly. For information
  39811. // on how they are encoded, see
  39812. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  39813. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  39814. pes.pts *= 4; // Left shift by 2
  39815. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  39816. pes.dts = pes.pts;
  39817. if (ptsDtsFlags & 0x40) {
  39818. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  39819. pes.dts *= 4; // Left shift by 2
  39820. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  39821. }
  39822. } // the data section starts immediately after the PES header.
  39823. // pes_header_data_length specifies the number of header bytes
  39824. // that follow the last byte of the field.
  39825. pes.data = payload.subarray(9 + payload[8]);
  39826. },
  39827. /**
  39828. * Pass completely parsed PES packets to the next stream in the pipeline
  39829. **/
  39830. flushStream = function (stream, type, forceFlush) {
  39831. var packetData = new Uint8Array(stream.size),
  39832. event = {
  39833. type: type
  39834. },
  39835. i = 0,
  39836. offset = 0,
  39837. packetFlushable = false,
  39838. fragment; // do nothing if there is not enough buffered data for a complete
  39839. // PES header
  39840. if (!stream.data.length || stream.size < 9) {
  39841. return;
  39842. }
  39843. event.trackId = stream.data[0].pid; // reassemble the packet
  39844. for (i = 0; i < stream.data.length; i++) {
  39845. fragment = stream.data[i];
  39846. packetData.set(fragment.data, offset);
  39847. offset += fragment.data.byteLength;
  39848. } // parse assembled packet's PES header
  39849. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  39850. // check that there is enough stream data to fill the packet
  39851. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  39852. if (forceFlush || packetFlushable) {
  39853. stream.size = 0;
  39854. stream.data.length = 0;
  39855. } // only emit packets that are complete. this is to avoid assembling
  39856. // incomplete PES packets due to poor segmentation
  39857. if (packetFlushable) {
  39858. self.trigger('data', event);
  39859. }
  39860. };
  39861. ElementaryStream.prototype.init.call(this);
  39862. /**
  39863. * Identifies M2TS packet types and parses PES packets using metadata
  39864. * parsed from the PMT
  39865. **/
  39866. this.push = function (data) {
  39867. ({
  39868. pat: function () {// we have to wait for the PMT to arrive as well before we
  39869. // have any meaningful metadata
  39870. },
  39871. pes: function () {
  39872. var stream, streamType;
  39873. switch (data.streamType) {
  39874. case StreamTypes$2.H264_STREAM_TYPE:
  39875. stream = video;
  39876. streamType = 'video';
  39877. break;
  39878. case StreamTypes$2.ADTS_STREAM_TYPE:
  39879. stream = audio;
  39880. streamType = 'audio';
  39881. break;
  39882. case StreamTypes$2.METADATA_STREAM_TYPE:
  39883. stream = timedMetadata;
  39884. streamType = 'timed-metadata';
  39885. break;
  39886. default:
  39887. // ignore unknown stream types
  39888. return;
  39889. } // if a new packet is starting, we can flush the completed
  39890. // packet
  39891. if (data.payloadUnitStartIndicator) {
  39892. flushStream(stream, streamType, true);
  39893. } // buffer this fragment until we are sure we've received the
  39894. // complete payload
  39895. stream.data.push(data);
  39896. stream.size += data.data.byteLength;
  39897. },
  39898. pmt: function () {
  39899. var event = {
  39900. type: 'metadata',
  39901. tracks: []
  39902. };
  39903. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  39904. if (programMapTable.video !== null) {
  39905. event.tracks.push({
  39906. timelineStartInfo: {
  39907. baseMediaDecodeTime: 0
  39908. },
  39909. id: +programMapTable.video,
  39910. codec: 'avc',
  39911. type: 'video'
  39912. });
  39913. }
  39914. if (programMapTable.audio !== null) {
  39915. event.tracks.push({
  39916. timelineStartInfo: {
  39917. baseMediaDecodeTime: 0
  39918. },
  39919. id: +programMapTable.audio,
  39920. codec: 'adts',
  39921. type: 'audio'
  39922. });
  39923. }
  39924. segmentHadPmt = true;
  39925. self.trigger('data', event);
  39926. }
  39927. })[data.type]();
  39928. };
  39929. this.reset = function () {
  39930. video.size = 0;
  39931. video.data.length = 0;
  39932. audio.size = 0;
  39933. audio.data.length = 0;
  39934. this.trigger('reset');
  39935. };
  39936. /**
  39937. * Flush any remaining input. Video PES packets may be of variable
  39938. * length. Normally, the start of a new video packet can trigger the
  39939. * finalization of the previous packet. That is not possible if no
  39940. * more video is forthcoming, however. In that case, some other
  39941. * mechanism (like the end of the file) has to be employed. When it is
  39942. * clear that no additional data is forthcoming, calling this method
  39943. * will flush the buffered packets.
  39944. */
  39945. this.flushStreams_ = function () {
  39946. // !!THIS ORDER IS IMPORTANT!!
  39947. // video first then audio
  39948. flushStream(video, 'video');
  39949. flushStream(audio, 'audio');
  39950. flushStream(timedMetadata, 'timed-metadata');
  39951. };
  39952. this.flush = function () {
  39953. // if on flush we haven't had a pmt emitted
  39954. // and we have a pmt to emit. emit the pmt
  39955. // so that we trigger a trackinfo downstream.
  39956. if (!segmentHadPmt && programMapTable) {
  39957. var pmt = {
  39958. type: 'metadata',
  39959. tracks: []
  39960. }; // translate audio and video streams to tracks
  39961. if (programMapTable.video !== null) {
  39962. pmt.tracks.push({
  39963. timelineStartInfo: {
  39964. baseMediaDecodeTime: 0
  39965. },
  39966. id: +programMapTable.video,
  39967. codec: 'avc',
  39968. type: 'video'
  39969. });
  39970. }
  39971. if (programMapTable.audio !== null) {
  39972. pmt.tracks.push({
  39973. timelineStartInfo: {
  39974. baseMediaDecodeTime: 0
  39975. },
  39976. id: +programMapTable.audio,
  39977. codec: 'adts',
  39978. type: 'audio'
  39979. });
  39980. }
  39981. self.trigger('data', pmt);
  39982. }
  39983. segmentHadPmt = false;
  39984. this.flushStreams_();
  39985. this.trigger('done');
  39986. };
  39987. };
  39988. ElementaryStream.prototype = new Stream$4();
  39989. var m2ts$1 = {
  39990. PAT_PID: 0x0000,
  39991. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  39992. TransportPacketStream: TransportPacketStream,
  39993. TransportParseStream: TransportParseStream,
  39994. ElementaryStream: ElementaryStream,
  39995. TimestampRolloverStream: TimestampRolloverStream,
  39996. CaptionStream: CaptionStream$1.CaptionStream,
  39997. Cea608Stream: CaptionStream$1.Cea608Stream,
  39998. Cea708Stream: CaptionStream$1.Cea708Stream,
  39999. MetadataStream: metadataStream
  40000. };
  40001. for (var type in StreamTypes$2) {
  40002. if (StreamTypes$2.hasOwnProperty(type)) {
  40003. m2ts$1[type] = StreamTypes$2[type];
  40004. }
  40005. }
  40006. var m2ts_1 = m2ts$1;
  40007. /**
  40008. * mux.js
  40009. *
  40010. * Copyright (c) Brightcove
  40011. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  40012. */
  40013. var Stream$3 = stream;
  40014. var ONE_SECOND_IN_TS$2 = clock$2.ONE_SECOND_IN_TS;
  40015. var AdtsStream$1;
  40016. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  40017. /*
  40018. * Accepts a ElementaryStream and emits data events with parsed
  40019. * AAC Audio Frames of the individual packets. Input audio in ADTS
  40020. * format is unpacked and re-emitted as AAC frames.
  40021. *
  40022. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  40023. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  40024. */
  40025. AdtsStream$1 = function (handlePartialSegments) {
  40026. var buffer,
  40027. frameNum = 0;
  40028. AdtsStream$1.prototype.init.call(this);
  40029. this.skipWarn_ = function (start, end) {
  40030. this.trigger('log', {
  40031. level: 'warn',
  40032. message: `adts skiping bytes ${start} to ${end} in frame ${frameNum} outside syncword`
  40033. });
  40034. };
  40035. this.push = function (packet) {
  40036. var i = 0,
  40037. frameLength,
  40038. protectionSkipBytes,
  40039. oldBuffer,
  40040. sampleCount,
  40041. adtsFrameDuration;
  40042. if (!handlePartialSegments) {
  40043. frameNum = 0;
  40044. }
  40045. if (packet.type !== 'audio') {
  40046. // ignore non-audio data
  40047. return;
  40048. } // Prepend any data in the buffer to the input data so that we can parse
  40049. // aac frames the cross a PES packet boundary
  40050. if (buffer && buffer.length) {
  40051. oldBuffer = buffer;
  40052. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  40053. buffer.set(oldBuffer);
  40054. buffer.set(packet.data, oldBuffer.byteLength);
  40055. } else {
  40056. buffer = packet.data;
  40057. } // unpack any ADTS frames which have been fully received
  40058. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  40059. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  40060. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  40061. while (i + 7 < buffer.length) {
  40062. // Look for the start of an ADTS header..
  40063. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  40064. if (typeof skip !== 'number') {
  40065. skip = i;
  40066. } // If a valid header was not found, jump one forward and attempt to
  40067. // find a valid ADTS header starting at the next byte
  40068. i++;
  40069. continue;
  40070. }
  40071. if (typeof skip === 'number') {
  40072. this.skipWarn_(skip, i);
  40073. skip = null;
  40074. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  40075. // end of the ADTS header
  40076. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  40077. // end of the sync sequence
  40078. // NOTE: frame length includes the size of the header
  40079. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  40080. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  40081. 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,
  40082. // then we have to wait for more data
  40083. if (buffer.byteLength - i < frameLength) {
  40084. break;
  40085. } // Otherwise, deliver the complete AAC frame
  40086. this.trigger('data', {
  40087. pts: packet.pts + frameNum * adtsFrameDuration,
  40088. dts: packet.dts + frameNum * adtsFrameDuration,
  40089. sampleCount: sampleCount,
  40090. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  40091. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  40092. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  40093. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  40094. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  40095. samplesize: 16,
  40096. // data is the frame without it's header
  40097. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  40098. });
  40099. frameNum++;
  40100. i += frameLength;
  40101. }
  40102. if (typeof skip === 'number') {
  40103. this.skipWarn_(skip, i);
  40104. skip = null;
  40105. } // remove processed bytes from the buffer.
  40106. buffer = buffer.subarray(i);
  40107. };
  40108. this.flush = function () {
  40109. frameNum = 0;
  40110. this.trigger('done');
  40111. };
  40112. this.reset = function () {
  40113. buffer = void 0;
  40114. this.trigger('reset');
  40115. };
  40116. this.endTimeline = function () {
  40117. buffer = void 0;
  40118. this.trigger('endedtimeline');
  40119. };
  40120. };
  40121. AdtsStream$1.prototype = new Stream$3();
  40122. var adts = AdtsStream$1;
  40123. /**
  40124. * mux.js
  40125. *
  40126. * Copyright (c) Brightcove
  40127. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  40128. */
  40129. var ExpGolomb$1;
  40130. /**
  40131. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  40132. * scheme used by h264.
  40133. */
  40134. ExpGolomb$1 = function (workingData) {
  40135. var
  40136. // the number of bytes left to examine in workingData
  40137. workingBytesAvailable = workingData.byteLength,
  40138. // the current word being examined
  40139. workingWord = 0,
  40140. // :uint
  40141. // the number of bits left to examine in the current word
  40142. workingBitsAvailable = 0; // :uint;
  40143. // ():uint
  40144. this.length = function () {
  40145. return 8 * workingBytesAvailable;
  40146. }; // ():uint
  40147. this.bitsAvailable = function () {
  40148. return 8 * workingBytesAvailable + workingBitsAvailable;
  40149. }; // ():void
  40150. this.loadWord = function () {
  40151. var position = workingData.byteLength - workingBytesAvailable,
  40152. workingBytes = new Uint8Array(4),
  40153. availableBytes = Math.min(4, workingBytesAvailable);
  40154. if (availableBytes === 0) {
  40155. throw new Error('no bytes available');
  40156. }
  40157. workingBytes.set(workingData.subarray(position, position + availableBytes));
  40158. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  40159. workingBitsAvailable = availableBytes * 8;
  40160. workingBytesAvailable -= availableBytes;
  40161. }; // (count:int):void
  40162. this.skipBits = function (count) {
  40163. var skipBytes; // :int
  40164. if (workingBitsAvailable > count) {
  40165. workingWord <<= count;
  40166. workingBitsAvailable -= count;
  40167. } else {
  40168. count -= workingBitsAvailable;
  40169. skipBytes = Math.floor(count / 8);
  40170. count -= skipBytes * 8;
  40171. workingBytesAvailable -= skipBytes;
  40172. this.loadWord();
  40173. workingWord <<= count;
  40174. workingBitsAvailable -= count;
  40175. }
  40176. }; // (size:int):uint
  40177. this.readBits = function (size) {
  40178. var bits = Math.min(workingBitsAvailable, size),
  40179. // :uint
  40180. valu = workingWord >>> 32 - bits; // :uint
  40181. // if size > 31, handle error
  40182. workingBitsAvailable -= bits;
  40183. if (workingBitsAvailable > 0) {
  40184. workingWord <<= bits;
  40185. } else if (workingBytesAvailable > 0) {
  40186. this.loadWord();
  40187. }
  40188. bits = size - bits;
  40189. if (bits > 0) {
  40190. return valu << bits | this.readBits(bits);
  40191. }
  40192. return valu;
  40193. }; // ():uint
  40194. this.skipLeadingZeros = function () {
  40195. var leadingZeroCount; // :uint
  40196. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  40197. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  40198. // the first bit of working word is 1
  40199. workingWord <<= leadingZeroCount;
  40200. workingBitsAvailable -= leadingZeroCount;
  40201. return leadingZeroCount;
  40202. }
  40203. } // we exhausted workingWord and still have not found a 1
  40204. this.loadWord();
  40205. return leadingZeroCount + this.skipLeadingZeros();
  40206. }; // ():void
  40207. this.skipUnsignedExpGolomb = function () {
  40208. this.skipBits(1 + this.skipLeadingZeros());
  40209. }; // ():void
  40210. this.skipExpGolomb = function () {
  40211. this.skipBits(1 + this.skipLeadingZeros());
  40212. }; // ():uint
  40213. this.readUnsignedExpGolomb = function () {
  40214. var clz = this.skipLeadingZeros(); // :uint
  40215. return this.readBits(clz + 1) - 1;
  40216. }; // ():int
  40217. this.readExpGolomb = function () {
  40218. var valu = this.readUnsignedExpGolomb(); // :int
  40219. if (0x01 & valu) {
  40220. // the number is odd if the low order bit is set
  40221. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  40222. }
  40223. return -1 * (valu >>> 1); // divide by two then make it negative
  40224. }; // Some convenience functions
  40225. // :Boolean
  40226. this.readBoolean = function () {
  40227. return this.readBits(1) === 1;
  40228. }; // ():int
  40229. this.readUnsignedByte = function () {
  40230. return this.readBits(8);
  40231. };
  40232. this.loadWord();
  40233. };
  40234. var expGolomb = ExpGolomb$1;
  40235. /**
  40236. * mux.js
  40237. *
  40238. * Copyright (c) Brightcove
  40239. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  40240. */
  40241. var Stream$2 = stream;
  40242. var ExpGolomb = expGolomb;
  40243. var H264Stream$1, NalByteStream;
  40244. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  40245. /**
  40246. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  40247. */
  40248. NalByteStream = function () {
  40249. var syncPoint = 0,
  40250. i,
  40251. buffer;
  40252. NalByteStream.prototype.init.call(this);
  40253. /*
  40254. * Scans a byte stream and triggers a data event with the NAL units found.
  40255. * @param {Object} data Event received from H264Stream
  40256. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  40257. *
  40258. * @see H264Stream.push
  40259. */
  40260. this.push = function (data) {
  40261. var swapBuffer;
  40262. if (!buffer) {
  40263. buffer = data.data;
  40264. } else {
  40265. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  40266. swapBuffer.set(buffer);
  40267. swapBuffer.set(data.data, buffer.byteLength);
  40268. buffer = swapBuffer;
  40269. }
  40270. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  40271. // scan for NAL unit boundaries
  40272. // a match looks like this:
  40273. // 0 0 1 .. NAL .. 0 0 1
  40274. // ^ sync point ^ i
  40275. // or this:
  40276. // 0 0 1 .. NAL .. 0 0 0
  40277. // ^ sync point ^ i
  40278. // advance the sync point to a NAL start, if necessary
  40279. for (; syncPoint < len - 3; syncPoint++) {
  40280. if (buffer[syncPoint + 2] === 1) {
  40281. // the sync point is properly aligned
  40282. i = syncPoint + 5;
  40283. break;
  40284. }
  40285. }
  40286. while (i < len) {
  40287. // look at the current byte to determine if we've hit the end of
  40288. // a NAL unit boundary
  40289. switch (buffer[i]) {
  40290. case 0:
  40291. // skip past non-sync sequences
  40292. if (buffer[i - 1] !== 0) {
  40293. i += 2;
  40294. break;
  40295. } else if (buffer[i - 2] !== 0) {
  40296. i++;
  40297. break;
  40298. } // deliver the NAL unit if it isn't empty
  40299. if (syncPoint + 3 !== i - 2) {
  40300. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  40301. } // drop trailing zeroes
  40302. do {
  40303. i++;
  40304. } while (buffer[i] !== 1 && i < len);
  40305. syncPoint = i - 2;
  40306. i += 3;
  40307. break;
  40308. case 1:
  40309. // skip past non-sync sequences
  40310. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  40311. i += 3;
  40312. break;
  40313. } // deliver the NAL unit
  40314. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  40315. syncPoint = i - 2;
  40316. i += 3;
  40317. break;
  40318. default:
  40319. // the current byte isn't a one or zero, so it cannot be part
  40320. // of a sync sequence
  40321. i += 3;
  40322. break;
  40323. }
  40324. } // filter out the NAL units that were delivered
  40325. buffer = buffer.subarray(syncPoint);
  40326. i -= syncPoint;
  40327. syncPoint = 0;
  40328. };
  40329. this.reset = function () {
  40330. buffer = null;
  40331. syncPoint = 0;
  40332. this.trigger('reset');
  40333. };
  40334. this.flush = function () {
  40335. // deliver the last buffered NAL unit
  40336. if (buffer && buffer.byteLength > 3) {
  40337. this.trigger('data', buffer.subarray(syncPoint + 3));
  40338. } // reset the stream state
  40339. buffer = null;
  40340. syncPoint = 0;
  40341. this.trigger('done');
  40342. };
  40343. this.endTimeline = function () {
  40344. this.flush();
  40345. this.trigger('endedtimeline');
  40346. };
  40347. };
  40348. NalByteStream.prototype = new Stream$2(); // values of profile_idc that indicate additional fields are included in the SPS
  40349. // see Recommendation ITU-T H.264 (4/2013),
  40350. // 7.3.2.1.1 Sequence parameter set data syntax
  40351. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  40352. 100: true,
  40353. 110: true,
  40354. 122: true,
  40355. 244: true,
  40356. 44: true,
  40357. 83: true,
  40358. 86: true,
  40359. 118: true,
  40360. 128: true,
  40361. // TODO: the three profiles below don't
  40362. // appear to have sps data in the specificiation anymore?
  40363. 138: true,
  40364. 139: true,
  40365. 134: true
  40366. };
  40367. /**
  40368. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  40369. * events.
  40370. */
  40371. H264Stream$1 = function () {
  40372. var nalByteStream = new NalByteStream(),
  40373. self,
  40374. trackId,
  40375. currentPts,
  40376. currentDts,
  40377. discardEmulationPreventionBytes,
  40378. readSequenceParameterSet,
  40379. skipScalingList;
  40380. H264Stream$1.prototype.init.call(this);
  40381. self = this;
  40382. /*
  40383. * Pushes a packet from a stream onto the NalByteStream
  40384. *
  40385. * @param {Object} packet - A packet received from a stream
  40386. * @param {Uint8Array} packet.data - The raw bytes of the packet
  40387. * @param {Number} packet.dts - Decode timestamp of the packet
  40388. * @param {Number} packet.pts - Presentation timestamp of the packet
  40389. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  40390. * @param {('video'|'audio')} packet.type - The type of packet
  40391. *
  40392. */
  40393. this.push = function (packet) {
  40394. if (packet.type !== 'video') {
  40395. return;
  40396. }
  40397. trackId = packet.trackId;
  40398. currentPts = packet.pts;
  40399. currentDts = packet.dts;
  40400. nalByteStream.push(packet);
  40401. };
  40402. /*
  40403. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  40404. * for the NALUs to the next stream component.
  40405. * Also, preprocess caption and sequence parameter NALUs.
  40406. *
  40407. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  40408. * @see NalByteStream.push
  40409. */
  40410. nalByteStream.on('data', function (data) {
  40411. var event = {
  40412. trackId: trackId,
  40413. pts: currentPts,
  40414. dts: currentDts,
  40415. data: data,
  40416. nalUnitTypeCode: data[0] & 0x1f
  40417. };
  40418. switch (event.nalUnitTypeCode) {
  40419. case 0x05:
  40420. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  40421. break;
  40422. case 0x06:
  40423. event.nalUnitType = 'sei_rbsp';
  40424. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  40425. break;
  40426. case 0x07:
  40427. event.nalUnitType = 'seq_parameter_set_rbsp';
  40428. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  40429. event.config = readSequenceParameterSet(event.escapedRBSP);
  40430. break;
  40431. case 0x08:
  40432. event.nalUnitType = 'pic_parameter_set_rbsp';
  40433. break;
  40434. case 0x09:
  40435. event.nalUnitType = 'access_unit_delimiter_rbsp';
  40436. break;
  40437. } // This triggers data on the H264Stream
  40438. self.trigger('data', event);
  40439. });
  40440. nalByteStream.on('done', function () {
  40441. self.trigger('done');
  40442. });
  40443. nalByteStream.on('partialdone', function () {
  40444. self.trigger('partialdone');
  40445. });
  40446. nalByteStream.on('reset', function () {
  40447. self.trigger('reset');
  40448. });
  40449. nalByteStream.on('endedtimeline', function () {
  40450. self.trigger('endedtimeline');
  40451. });
  40452. this.flush = function () {
  40453. nalByteStream.flush();
  40454. };
  40455. this.partialFlush = function () {
  40456. nalByteStream.partialFlush();
  40457. };
  40458. this.reset = function () {
  40459. nalByteStream.reset();
  40460. };
  40461. this.endTimeline = function () {
  40462. nalByteStream.endTimeline();
  40463. };
  40464. /**
  40465. * Advance the ExpGolomb decoder past a scaling list. The scaling
  40466. * list is optionally transmitted as part of a sequence parameter
  40467. * set and is not relevant to transmuxing.
  40468. * @param count {number} the number of entries in this scaling list
  40469. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  40470. * start of a scaling list
  40471. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  40472. */
  40473. skipScalingList = function (count, expGolombDecoder) {
  40474. var lastScale = 8,
  40475. nextScale = 8,
  40476. j,
  40477. deltaScale;
  40478. for (j = 0; j < count; j++) {
  40479. if (nextScale !== 0) {
  40480. deltaScale = expGolombDecoder.readExpGolomb();
  40481. nextScale = (lastScale + deltaScale + 256) % 256;
  40482. }
  40483. lastScale = nextScale === 0 ? lastScale : nextScale;
  40484. }
  40485. };
  40486. /**
  40487. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  40488. * Sequence Payload"
  40489. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  40490. * unit
  40491. * @return {Uint8Array} the RBSP without any Emulation
  40492. * Prevention Bytes
  40493. */
  40494. discardEmulationPreventionBytes = function (data) {
  40495. var length = data.byteLength,
  40496. emulationPreventionBytesPositions = [],
  40497. i = 1,
  40498. newLength,
  40499. newData; // Find all `Emulation Prevention Bytes`
  40500. while (i < length - 2) {
  40501. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  40502. emulationPreventionBytesPositions.push(i + 2);
  40503. i += 2;
  40504. } else {
  40505. i++;
  40506. }
  40507. } // If no Emulation Prevention Bytes were found just return the original
  40508. // array
  40509. if (emulationPreventionBytesPositions.length === 0) {
  40510. return data;
  40511. } // Create a new array to hold the NAL unit data
  40512. newLength = length - emulationPreventionBytesPositions.length;
  40513. newData = new Uint8Array(newLength);
  40514. var sourceIndex = 0;
  40515. for (i = 0; i < newLength; sourceIndex++, i++) {
  40516. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  40517. // Skip this byte
  40518. sourceIndex++; // Remove this position index
  40519. emulationPreventionBytesPositions.shift();
  40520. }
  40521. newData[i] = data[sourceIndex];
  40522. }
  40523. return newData;
  40524. };
  40525. /**
  40526. * Read a sequence parameter set and return some interesting video
  40527. * properties. A sequence parameter set is the H264 metadata that
  40528. * describes the properties of upcoming video frames.
  40529. * @param data {Uint8Array} the bytes of a sequence parameter set
  40530. * @return {object} an object with configuration parsed from the
  40531. * sequence parameter set, including the dimensions of the
  40532. * associated video frames.
  40533. */
  40534. readSequenceParameterSet = function (data) {
  40535. var frameCropLeftOffset = 0,
  40536. frameCropRightOffset = 0,
  40537. frameCropTopOffset = 0,
  40538. frameCropBottomOffset = 0,
  40539. expGolombDecoder,
  40540. profileIdc,
  40541. levelIdc,
  40542. profileCompatibility,
  40543. chromaFormatIdc,
  40544. picOrderCntType,
  40545. numRefFramesInPicOrderCntCycle,
  40546. picWidthInMbsMinus1,
  40547. picHeightInMapUnitsMinus1,
  40548. frameMbsOnlyFlag,
  40549. scalingListCount,
  40550. sarRatio = [1, 1],
  40551. aspectRatioIdc,
  40552. i;
  40553. expGolombDecoder = new ExpGolomb(data);
  40554. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  40555. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  40556. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  40557. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  40558. // some profiles have more optional data we don't need
  40559. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  40560. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  40561. if (chromaFormatIdc === 3) {
  40562. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  40563. }
  40564. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  40565. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  40566. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  40567. if (expGolombDecoder.readBoolean()) {
  40568. // seq_scaling_matrix_present_flag
  40569. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  40570. for (i = 0; i < scalingListCount; i++) {
  40571. if (expGolombDecoder.readBoolean()) {
  40572. // seq_scaling_list_present_flag[ i ]
  40573. if (i < 6) {
  40574. skipScalingList(16, expGolombDecoder);
  40575. } else {
  40576. skipScalingList(64, expGolombDecoder);
  40577. }
  40578. }
  40579. }
  40580. }
  40581. }
  40582. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  40583. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  40584. if (picOrderCntType === 0) {
  40585. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  40586. } else if (picOrderCntType === 1) {
  40587. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  40588. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  40589. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  40590. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  40591. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  40592. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  40593. }
  40594. }
  40595. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  40596. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  40597. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  40598. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  40599. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  40600. if (frameMbsOnlyFlag === 0) {
  40601. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  40602. }
  40603. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  40604. if (expGolombDecoder.readBoolean()) {
  40605. // frame_cropping_flag
  40606. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  40607. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  40608. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  40609. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  40610. }
  40611. if (expGolombDecoder.readBoolean()) {
  40612. // vui_parameters_present_flag
  40613. if (expGolombDecoder.readBoolean()) {
  40614. // aspect_ratio_info_present_flag
  40615. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  40616. switch (aspectRatioIdc) {
  40617. case 1:
  40618. sarRatio = [1, 1];
  40619. break;
  40620. case 2:
  40621. sarRatio = [12, 11];
  40622. break;
  40623. case 3:
  40624. sarRatio = [10, 11];
  40625. break;
  40626. case 4:
  40627. sarRatio = [16, 11];
  40628. break;
  40629. case 5:
  40630. sarRatio = [40, 33];
  40631. break;
  40632. case 6:
  40633. sarRatio = [24, 11];
  40634. break;
  40635. case 7:
  40636. sarRatio = [20, 11];
  40637. break;
  40638. case 8:
  40639. sarRatio = [32, 11];
  40640. break;
  40641. case 9:
  40642. sarRatio = [80, 33];
  40643. break;
  40644. case 10:
  40645. sarRatio = [18, 11];
  40646. break;
  40647. case 11:
  40648. sarRatio = [15, 11];
  40649. break;
  40650. case 12:
  40651. sarRatio = [64, 33];
  40652. break;
  40653. case 13:
  40654. sarRatio = [160, 99];
  40655. break;
  40656. case 14:
  40657. sarRatio = [4, 3];
  40658. break;
  40659. case 15:
  40660. sarRatio = [3, 2];
  40661. break;
  40662. case 16:
  40663. sarRatio = [2, 1];
  40664. break;
  40665. case 255:
  40666. {
  40667. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  40668. break;
  40669. }
  40670. }
  40671. if (sarRatio) {
  40672. sarRatio[0] / sarRatio[1];
  40673. }
  40674. }
  40675. }
  40676. return {
  40677. profileIdc: profileIdc,
  40678. levelIdc: levelIdc,
  40679. profileCompatibility: profileCompatibility,
  40680. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  40681. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  40682. // sar is sample aspect ratio
  40683. sarRatio: sarRatio
  40684. };
  40685. };
  40686. };
  40687. H264Stream$1.prototype = new Stream$2();
  40688. var h264 = {
  40689. H264Stream: H264Stream$1,
  40690. NalByteStream: NalByteStream
  40691. };
  40692. /**
  40693. * mux.js
  40694. *
  40695. * Copyright (c) Brightcove
  40696. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  40697. *
  40698. * Utilities to detect basic properties and metadata about Aac data.
  40699. */
  40700. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  40701. var parseId3TagSize = function (header, byteIndex) {
  40702. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  40703. flags = header[byteIndex + 5],
  40704. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  40705. returnSize = returnSize >= 0 ? returnSize : 0;
  40706. if (footerPresent) {
  40707. return returnSize + 20;
  40708. }
  40709. return returnSize + 10;
  40710. };
  40711. var getId3Offset = function (data, offset) {
  40712. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  40713. return offset;
  40714. }
  40715. offset += parseId3TagSize(data, offset);
  40716. return getId3Offset(data, offset);
  40717. }; // TODO: use vhs-utils
  40718. var isLikelyAacData$1 = function (data) {
  40719. var offset = getId3Offset(data, 0);
  40720. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 &&
  40721. // verify that the 2 layer bits are 0, aka this
  40722. // is not mp3 data but aac data.
  40723. (data[offset + 1] & 0x16) === 0x10;
  40724. };
  40725. var parseSyncSafeInteger = function (data) {
  40726. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  40727. }; // return a percent-encoded representation of the specified byte range
  40728. // @see http://en.wikipedia.org/wiki/Percent-encoding
  40729. var percentEncode = function (bytes, start, end) {
  40730. var i,
  40731. result = '';
  40732. for (i = start; i < end; i++) {
  40733. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  40734. }
  40735. return result;
  40736. }; // return the string representation of the specified byte range,
  40737. // interpreted as ISO-8859-1.
  40738. var parseIso88591 = function (bytes, start, end) {
  40739. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  40740. };
  40741. var parseAdtsSize = function (header, byteIndex) {
  40742. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  40743. middle = header[byteIndex + 4] << 3,
  40744. highTwo = header[byteIndex + 3] & 0x3 << 11;
  40745. return highTwo | middle | lowThree;
  40746. };
  40747. var parseType$4 = function (header, byteIndex) {
  40748. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  40749. return 'timed-metadata';
  40750. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  40751. return 'audio';
  40752. }
  40753. return null;
  40754. };
  40755. var parseSampleRate = function (packet) {
  40756. var i = 0;
  40757. while (i + 5 < packet.length) {
  40758. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  40759. // If a valid header was not found, jump one forward and attempt to
  40760. // find a valid ADTS header starting at the next byte
  40761. i++;
  40762. continue;
  40763. }
  40764. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  40765. }
  40766. return null;
  40767. };
  40768. var parseAacTimestamp = function (packet) {
  40769. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  40770. frameStart = 10;
  40771. if (packet[5] & 0x40) {
  40772. // advance the frame start past the extended header
  40773. frameStart += 4; // header size field
  40774. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  40775. } // parse one or more ID3 frames
  40776. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  40777. do {
  40778. // determine the number of bytes in this frame
  40779. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  40780. if (frameSize < 1) {
  40781. return null;
  40782. }
  40783. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  40784. if (frameHeader === 'PRIV') {
  40785. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  40786. for (var i = 0; i < frame.byteLength; i++) {
  40787. if (frame[i] === 0) {
  40788. var owner = parseIso88591(frame, 0, i);
  40789. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  40790. var d = frame.subarray(i + 1);
  40791. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  40792. size *= 4;
  40793. size += d[7] & 0x03;
  40794. return size;
  40795. }
  40796. break;
  40797. }
  40798. }
  40799. }
  40800. frameStart += 10; // advance past the frame header
  40801. frameStart += frameSize; // advance past the frame body
  40802. } while (frameStart < packet.byteLength);
  40803. return null;
  40804. };
  40805. var utils = {
  40806. isLikelyAacData: isLikelyAacData$1,
  40807. parseId3TagSize: parseId3TagSize,
  40808. parseAdtsSize: parseAdtsSize,
  40809. parseType: parseType$4,
  40810. parseSampleRate: parseSampleRate,
  40811. parseAacTimestamp: parseAacTimestamp
  40812. };
  40813. /**
  40814. * mux.js
  40815. *
  40816. * Copyright (c) Brightcove
  40817. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  40818. *
  40819. * A stream-based aac to mp4 converter. This utility can be used to
  40820. * deliver mp4s to a SourceBuffer on platforms that support native
  40821. * Media Source Extensions.
  40822. */
  40823. var Stream$1 = stream;
  40824. var aacUtils = utils; // Constants
  40825. var AacStream$1;
  40826. /**
  40827. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  40828. */
  40829. AacStream$1 = function () {
  40830. var everything = new Uint8Array(),
  40831. timeStamp = 0;
  40832. AacStream$1.prototype.init.call(this);
  40833. this.setTimestamp = function (timestamp) {
  40834. timeStamp = timestamp;
  40835. };
  40836. this.push = function (bytes) {
  40837. var frameSize = 0,
  40838. byteIndex = 0,
  40839. bytesLeft,
  40840. chunk,
  40841. packet,
  40842. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  40843. // bytes that were pushed in
  40844. if (everything.length) {
  40845. tempLength = everything.length;
  40846. everything = new Uint8Array(bytes.byteLength + tempLength);
  40847. everything.set(everything.subarray(0, tempLength));
  40848. everything.set(bytes, tempLength);
  40849. } else {
  40850. everything = bytes;
  40851. }
  40852. while (everything.length - byteIndex >= 3) {
  40853. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  40854. // Exit early because we don't have enough to parse
  40855. // the ID3 tag header
  40856. if (everything.length - byteIndex < 10) {
  40857. break;
  40858. } // check framesize
  40859. frameSize = aacUtils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  40860. // to emit a full packet
  40861. // Add to byteIndex to support multiple ID3 tags in sequence
  40862. if (byteIndex + frameSize > everything.length) {
  40863. break;
  40864. }
  40865. chunk = {
  40866. type: 'timed-metadata',
  40867. data: everything.subarray(byteIndex, byteIndex + frameSize)
  40868. };
  40869. this.trigger('data', chunk);
  40870. byteIndex += frameSize;
  40871. continue;
  40872. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  40873. // Exit early because we don't have enough to parse
  40874. // the ADTS frame header
  40875. if (everything.length - byteIndex < 7) {
  40876. break;
  40877. }
  40878. frameSize = aacUtils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  40879. // to emit a full packet
  40880. if (byteIndex + frameSize > everything.length) {
  40881. break;
  40882. }
  40883. packet = {
  40884. type: 'audio',
  40885. data: everything.subarray(byteIndex, byteIndex + frameSize),
  40886. pts: timeStamp,
  40887. dts: timeStamp
  40888. };
  40889. this.trigger('data', packet);
  40890. byteIndex += frameSize;
  40891. continue;
  40892. }
  40893. byteIndex++;
  40894. }
  40895. bytesLeft = everything.length - byteIndex;
  40896. if (bytesLeft > 0) {
  40897. everything = everything.subarray(byteIndex);
  40898. } else {
  40899. everything = new Uint8Array();
  40900. }
  40901. };
  40902. this.reset = function () {
  40903. everything = new Uint8Array();
  40904. this.trigger('reset');
  40905. };
  40906. this.endTimeline = function () {
  40907. everything = new Uint8Array();
  40908. this.trigger('endedtimeline');
  40909. };
  40910. };
  40911. AacStream$1.prototype = new Stream$1();
  40912. var aac = AacStream$1;
  40913. var AUDIO_PROPERTIES$1 = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  40914. var audioProperties = AUDIO_PROPERTIES$1;
  40915. var VIDEO_PROPERTIES$1 = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  40916. var videoProperties = VIDEO_PROPERTIES$1;
  40917. /**
  40918. * mux.js
  40919. *
  40920. * Copyright (c) Brightcove
  40921. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  40922. *
  40923. * A stream-based mp2t to mp4 converter. This utility can be used to
  40924. * deliver mp4s to a SourceBuffer on platforms that support native
  40925. * Media Source Extensions.
  40926. */
  40927. var Stream = stream;
  40928. var mp4 = mp4Generator;
  40929. var frameUtils = frameUtils$1;
  40930. var audioFrameUtils = audioFrameUtils$1;
  40931. var trackDecodeInfo = trackDecodeInfo$1;
  40932. var m2ts = m2ts_1;
  40933. var clock = clock$2;
  40934. var AdtsStream = adts;
  40935. var H264Stream = h264.H264Stream;
  40936. var AacStream = aac;
  40937. var isLikelyAacData = utils.isLikelyAacData;
  40938. var ONE_SECOND_IN_TS$1 = clock$2.ONE_SECOND_IN_TS;
  40939. var AUDIO_PROPERTIES = audioProperties;
  40940. var VIDEO_PROPERTIES = videoProperties; // object types
  40941. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  40942. var retriggerForStream = function (key, event) {
  40943. event.stream = key;
  40944. this.trigger('log', event);
  40945. };
  40946. var addPipelineLogRetriggers = function (transmuxer, pipeline) {
  40947. var keys = Object.keys(pipeline);
  40948. for (var i = 0; i < keys.length; i++) {
  40949. var key = keys[i]; // skip non-stream keys and headOfPipeline
  40950. // which is just a duplicate
  40951. if (key === 'headOfPipeline' || !pipeline[key].on) {
  40952. continue;
  40953. }
  40954. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  40955. }
  40956. };
  40957. /**
  40958. * Compare two arrays (even typed) for same-ness
  40959. */
  40960. var arrayEquals = function (a, b) {
  40961. var i;
  40962. if (a.length !== b.length) {
  40963. return false;
  40964. } // compare the value of each element in the array
  40965. for (i = 0; i < a.length; i++) {
  40966. if (a[i] !== b[i]) {
  40967. return false;
  40968. }
  40969. }
  40970. return true;
  40971. };
  40972. var generateSegmentTimingInfo = function (baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  40973. var ptsOffsetFromDts = startPts - startDts,
  40974. decodeDuration = endDts - startDts,
  40975. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  40976. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  40977. // In order to provide relevant values for the player times, base timing info on the
  40978. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  40979. return {
  40980. start: {
  40981. dts: baseMediaDecodeTime,
  40982. pts: baseMediaDecodeTime + ptsOffsetFromDts
  40983. },
  40984. end: {
  40985. dts: baseMediaDecodeTime + decodeDuration,
  40986. pts: baseMediaDecodeTime + presentationDuration
  40987. },
  40988. prependedContentDuration: prependedContentDuration,
  40989. baseMediaDecodeTime: baseMediaDecodeTime
  40990. };
  40991. };
  40992. /**
  40993. * Constructs a single-track, ISO BMFF media segment from AAC data
  40994. * events. The output of this stream can be fed to a SourceBuffer
  40995. * configured with a suitable initialization segment.
  40996. * @param track {object} track metadata configuration
  40997. * @param options {object} transmuxer options object
  40998. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  40999. * in the source; false to adjust the first segment to start at 0.
  41000. */
  41001. AudioSegmentStream = function (track, options) {
  41002. var adtsFrames = [],
  41003. sequenceNumber,
  41004. earliestAllowedDts = 0,
  41005. audioAppendStartTs = 0,
  41006. videoBaseMediaDecodeTime = Infinity;
  41007. options = options || {};
  41008. sequenceNumber = options.firstSequenceNumber || 0;
  41009. AudioSegmentStream.prototype.init.call(this);
  41010. this.push = function (data) {
  41011. trackDecodeInfo.collectDtsInfo(track, data);
  41012. if (track) {
  41013. AUDIO_PROPERTIES.forEach(function (prop) {
  41014. track[prop] = data[prop];
  41015. });
  41016. } // buffer audio data until end() is called
  41017. adtsFrames.push(data);
  41018. };
  41019. this.setEarliestDts = function (earliestDts) {
  41020. earliestAllowedDts = earliestDts;
  41021. };
  41022. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  41023. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  41024. };
  41025. this.setAudioAppendStart = function (timestamp) {
  41026. audioAppendStartTs = timestamp;
  41027. };
  41028. this.flush = function () {
  41029. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  41030. if (adtsFrames.length === 0) {
  41031. this.trigger('done', 'AudioSegmentStream');
  41032. return;
  41033. }
  41034. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  41035. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  41036. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  41037. // samples (that is, adts frames) in the audio data
  41038. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  41039. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  41040. adtsFrames = [];
  41041. moof = mp4.moof(sequenceNumber, [track]);
  41042. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  41043. sequenceNumber++;
  41044. boxes.set(moof);
  41045. boxes.set(mdat, moof.byteLength);
  41046. trackDecodeInfo.clearDtsInfo(track);
  41047. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  41048. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  41049. // valid use-case where an init segment/data should be triggered without associated
  41050. // frames. Leaving for now, but should be looked into.
  41051. if (frames.length) {
  41052. segmentDuration = frames.length * frameDuration;
  41053. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(
  41054. // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  41055. // frame info is in video clock cycles. Convert to match expectation of
  41056. // listeners (that all timestamps will be based on video clock cycles).
  41057. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate),
  41058. // frame times are already in video clock, as is segment duration
  41059. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  41060. this.trigger('timingInfo', {
  41061. start: frames[0].pts,
  41062. end: frames[0].pts + segmentDuration
  41063. });
  41064. }
  41065. this.trigger('data', {
  41066. track: track,
  41067. boxes: boxes
  41068. });
  41069. this.trigger('done', 'AudioSegmentStream');
  41070. };
  41071. this.reset = function () {
  41072. trackDecodeInfo.clearDtsInfo(track);
  41073. adtsFrames = [];
  41074. this.trigger('reset');
  41075. };
  41076. };
  41077. AudioSegmentStream.prototype = new Stream();
  41078. /**
  41079. * Constructs a single-track, ISO BMFF media segment from H264 data
  41080. * events. The output of this stream can be fed to a SourceBuffer
  41081. * configured with a suitable initialization segment.
  41082. * @param track {object} track metadata configuration
  41083. * @param options {object} transmuxer options object
  41084. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  41085. * gopsToAlignWith list when attempting to align gop pts
  41086. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  41087. * in the source; false to adjust the first segment to start at 0.
  41088. */
  41089. VideoSegmentStream = function (track, options) {
  41090. var sequenceNumber,
  41091. nalUnits = [],
  41092. gopsToAlignWith = [],
  41093. config,
  41094. pps;
  41095. options = options || {};
  41096. sequenceNumber = options.firstSequenceNumber || 0;
  41097. VideoSegmentStream.prototype.init.call(this);
  41098. delete track.minPTS;
  41099. this.gopCache_ = [];
  41100. /**
  41101. * Constructs a ISO BMFF segment given H264 nalUnits
  41102. * @param {Object} nalUnit A data event representing a nalUnit
  41103. * @param {String} nalUnit.nalUnitType
  41104. * @param {Object} nalUnit.config Properties for a mp4 track
  41105. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  41106. * @see lib/codecs/h264.js
  41107. **/
  41108. this.push = function (nalUnit) {
  41109. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  41110. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  41111. config = nalUnit.config;
  41112. track.sps = [nalUnit.data];
  41113. VIDEO_PROPERTIES.forEach(function (prop) {
  41114. track[prop] = config[prop];
  41115. }, this);
  41116. }
  41117. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  41118. pps = nalUnit.data;
  41119. track.pps = [nalUnit.data];
  41120. } // buffer video until flush() is called
  41121. nalUnits.push(nalUnit);
  41122. };
  41123. /**
  41124. * Pass constructed ISO BMFF track and boxes on to the
  41125. * next stream in the pipeline
  41126. **/
  41127. this.flush = function () {
  41128. var frames,
  41129. gopForFusion,
  41130. gops,
  41131. moof,
  41132. mdat,
  41133. boxes,
  41134. prependedContentDuration = 0,
  41135. firstGop,
  41136. lastGop; // Throw away nalUnits at the start of the byte stream until
  41137. // we find the first AUD
  41138. while (nalUnits.length) {
  41139. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  41140. break;
  41141. }
  41142. nalUnits.shift();
  41143. } // Return early if no video data has been observed
  41144. if (nalUnits.length === 0) {
  41145. this.resetStream_();
  41146. this.trigger('done', 'VideoSegmentStream');
  41147. return;
  41148. } // Organize the raw nal-units into arrays that represent
  41149. // higher-level constructs such as frames and gops
  41150. // (group-of-pictures)
  41151. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  41152. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  41153. // a problem since MSE (on Chrome) requires a leading keyframe.
  41154. //
  41155. // We have two approaches to repairing this situation:
  41156. // 1) GOP-FUSION:
  41157. // This is where we keep track of the GOPS (group-of-pictures)
  41158. // from previous fragments and attempt to find one that we can
  41159. // prepend to the current fragment in order to create a valid
  41160. // fragment.
  41161. // 2) KEYFRAME-PULLING:
  41162. // Here we search for the first keyframe in the fragment and
  41163. // throw away all the frames between the start of the fragment
  41164. // and that keyframe. We then extend the duration and pull the
  41165. // PTS of the keyframe forward so that it covers the time range
  41166. // of the frames that were disposed of.
  41167. //
  41168. // #1 is far prefereable over #2 which can cause "stuttering" but
  41169. // requires more things to be just right.
  41170. if (!gops[0][0].keyFrame) {
  41171. // Search for a gop for fusion from our gopCache
  41172. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  41173. if (gopForFusion) {
  41174. // in order to provide more accurate timing information about the segment, save
  41175. // the number of seconds prepended to the original segment due to GOP fusion
  41176. prependedContentDuration = gopForFusion.duration;
  41177. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  41178. // new gop at the beginning
  41179. gops.byteLength += gopForFusion.byteLength;
  41180. gops.nalCount += gopForFusion.nalCount;
  41181. gops.pts = gopForFusion.pts;
  41182. gops.dts = gopForFusion.dts;
  41183. gops.duration += gopForFusion.duration;
  41184. } else {
  41185. // If we didn't find a candidate gop fall back to keyframe-pulling
  41186. gops = frameUtils.extendFirstKeyFrame(gops);
  41187. }
  41188. } // Trim gops to align with gopsToAlignWith
  41189. if (gopsToAlignWith.length) {
  41190. var alignedGops;
  41191. if (options.alignGopsAtEnd) {
  41192. alignedGops = this.alignGopsAtEnd_(gops);
  41193. } else {
  41194. alignedGops = this.alignGopsAtStart_(gops);
  41195. }
  41196. if (!alignedGops) {
  41197. // save all the nals in the last GOP into the gop cache
  41198. this.gopCache_.unshift({
  41199. gop: gops.pop(),
  41200. pps: track.pps,
  41201. sps: track.sps
  41202. }); // Keep a maximum of 6 GOPs in the cache
  41203. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  41204. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  41205. this.resetStream_();
  41206. this.trigger('done', 'VideoSegmentStream');
  41207. return;
  41208. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  41209. // when recalculated before sending off to CoalesceStream
  41210. trackDecodeInfo.clearDtsInfo(track);
  41211. gops = alignedGops;
  41212. }
  41213. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  41214. // samples (that is, frames) in the video data
  41215. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  41216. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  41217. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  41218. this.trigger('processedGopsInfo', gops.map(function (gop) {
  41219. return {
  41220. pts: gop.pts,
  41221. dts: gop.dts,
  41222. byteLength: gop.byteLength
  41223. };
  41224. }));
  41225. firstGop = gops[0];
  41226. lastGop = gops[gops.length - 1];
  41227. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  41228. this.trigger('timingInfo', {
  41229. start: gops[0].pts,
  41230. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  41231. }); // save all the nals in the last GOP into the gop cache
  41232. this.gopCache_.unshift({
  41233. gop: gops.pop(),
  41234. pps: track.pps,
  41235. sps: track.sps
  41236. }); // Keep a maximum of 6 GOPs in the cache
  41237. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  41238. nalUnits = [];
  41239. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  41240. this.trigger('timelineStartInfo', track.timelineStartInfo);
  41241. moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  41242. // throwing away hundreds of media segment fragments
  41243. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  41244. sequenceNumber++;
  41245. boxes.set(moof);
  41246. boxes.set(mdat, moof.byteLength);
  41247. this.trigger('data', {
  41248. track: track,
  41249. boxes: boxes
  41250. });
  41251. this.resetStream_(); // Continue with the flush process now
  41252. this.trigger('done', 'VideoSegmentStream');
  41253. };
  41254. this.reset = function () {
  41255. this.resetStream_();
  41256. nalUnits = [];
  41257. this.gopCache_.length = 0;
  41258. gopsToAlignWith.length = 0;
  41259. this.trigger('reset');
  41260. };
  41261. this.resetStream_ = function () {
  41262. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  41263. // for instance, when we are rendition switching
  41264. config = undefined;
  41265. pps = undefined;
  41266. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  41267. // return it or return null if no good candidate was found
  41268. this.getGopForFusion_ = function (nalUnit) {
  41269. var halfSecond = 45000,
  41270. // Half-a-second in a 90khz clock
  41271. allowableOverlap = 10000,
  41272. // About 3 frames @ 30fps
  41273. nearestDistance = Infinity,
  41274. dtsDistance,
  41275. nearestGopObj,
  41276. currentGop,
  41277. currentGopObj,
  41278. i; // Search for the GOP nearest to the beginning of this nal unit
  41279. for (i = 0; i < this.gopCache_.length; i++) {
  41280. currentGopObj = this.gopCache_[i];
  41281. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  41282. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  41283. continue;
  41284. } // Reject Gops that would require a negative baseMediaDecodeTime
  41285. if (currentGop.dts < track.timelineStartInfo.dts) {
  41286. continue;
  41287. } // The distance between the end of the gop and the start of the nalUnit
  41288. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  41289. // a half-second of the nal unit
  41290. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  41291. // Always use the closest GOP we found if there is more than
  41292. // one candidate
  41293. if (!nearestGopObj || nearestDistance > dtsDistance) {
  41294. nearestGopObj = currentGopObj;
  41295. nearestDistance = dtsDistance;
  41296. }
  41297. }
  41298. }
  41299. if (nearestGopObj) {
  41300. return nearestGopObj.gop;
  41301. }
  41302. return null;
  41303. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  41304. // of gopsToAlignWith starting from the START of the list
  41305. this.alignGopsAtStart_ = function (gops) {
  41306. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  41307. byteLength = gops.byteLength;
  41308. nalCount = gops.nalCount;
  41309. duration = gops.duration;
  41310. alignIndex = gopIndex = 0;
  41311. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  41312. align = gopsToAlignWith[alignIndex];
  41313. gop = gops[gopIndex];
  41314. if (align.pts === gop.pts) {
  41315. break;
  41316. }
  41317. if (gop.pts > align.pts) {
  41318. // this current gop starts after the current gop we want to align on, so increment
  41319. // align index
  41320. alignIndex++;
  41321. continue;
  41322. } // current gop starts before the current gop we want to align on. so increment gop
  41323. // index
  41324. gopIndex++;
  41325. byteLength -= gop.byteLength;
  41326. nalCount -= gop.nalCount;
  41327. duration -= gop.duration;
  41328. }
  41329. if (gopIndex === 0) {
  41330. // no gops to trim
  41331. return gops;
  41332. }
  41333. if (gopIndex === gops.length) {
  41334. // all gops trimmed, skip appending all gops
  41335. return null;
  41336. }
  41337. alignedGops = gops.slice(gopIndex);
  41338. alignedGops.byteLength = byteLength;
  41339. alignedGops.duration = duration;
  41340. alignedGops.nalCount = nalCount;
  41341. alignedGops.pts = alignedGops[0].pts;
  41342. alignedGops.dts = alignedGops[0].dts;
  41343. return alignedGops;
  41344. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  41345. // of gopsToAlignWith starting from the END of the list
  41346. this.alignGopsAtEnd_ = function (gops) {
  41347. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  41348. alignIndex = gopsToAlignWith.length - 1;
  41349. gopIndex = gops.length - 1;
  41350. alignEndIndex = null;
  41351. matchFound = false;
  41352. while (alignIndex >= 0 && gopIndex >= 0) {
  41353. align = gopsToAlignWith[alignIndex];
  41354. gop = gops[gopIndex];
  41355. if (align.pts === gop.pts) {
  41356. matchFound = true;
  41357. break;
  41358. }
  41359. if (align.pts > gop.pts) {
  41360. alignIndex--;
  41361. continue;
  41362. }
  41363. if (alignIndex === gopsToAlignWith.length - 1) {
  41364. // gop.pts is greater than the last alignment candidate. If no match is found
  41365. // by the end of this loop, we still want to append gops that come after this
  41366. // point
  41367. alignEndIndex = gopIndex;
  41368. }
  41369. gopIndex--;
  41370. }
  41371. if (!matchFound && alignEndIndex === null) {
  41372. return null;
  41373. }
  41374. var trimIndex;
  41375. if (matchFound) {
  41376. trimIndex = gopIndex;
  41377. } else {
  41378. trimIndex = alignEndIndex;
  41379. }
  41380. if (trimIndex === 0) {
  41381. return gops;
  41382. }
  41383. var alignedGops = gops.slice(trimIndex);
  41384. var metadata = alignedGops.reduce(function (total, gop) {
  41385. total.byteLength += gop.byteLength;
  41386. total.duration += gop.duration;
  41387. total.nalCount += gop.nalCount;
  41388. return total;
  41389. }, {
  41390. byteLength: 0,
  41391. duration: 0,
  41392. nalCount: 0
  41393. });
  41394. alignedGops.byteLength = metadata.byteLength;
  41395. alignedGops.duration = metadata.duration;
  41396. alignedGops.nalCount = metadata.nalCount;
  41397. alignedGops.pts = alignedGops[0].pts;
  41398. alignedGops.dts = alignedGops[0].dts;
  41399. return alignedGops;
  41400. };
  41401. this.alignGopsWith = function (newGopsToAlignWith) {
  41402. gopsToAlignWith = newGopsToAlignWith;
  41403. };
  41404. };
  41405. VideoSegmentStream.prototype = new Stream();
  41406. /**
  41407. * A Stream that can combine multiple streams (ie. audio & video)
  41408. * into a single output segment for MSE. Also supports audio-only
  41409. * and video-only streams.
  41410. * @param options {object} transmuxer options object
  41411. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  41412. * in the source; false to adjust the first segment to start at media timeline start.
  41413. */
  41414. CoalesceStream = function (options, metadataStream) {
  41415. // Number of Tracks per output segment
  41416. // If greater than 1, we combine multiple
  41417. // tracks into a single segment
  41418. this.numberOfTracks = 0;
  41419. this.metadataStream = metadataStream;
  41420. options = options || {};
  41421. if (typeof options.remux !== 'undefined') {
  41422. this.remuxTracks = !!options.remux;
  41423. } else {
  41424. this.remuxTracks = true;
  41425. }
  41426. if (typeof options.keepOriginalTimestamps === 'boolean') {
  41427. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  41428. } else {
  41429. this.keepOriginalTimestamps = false;
  41430. }
  41431. this.pendingTracks = [];
  41432. this.videoTrack = null;
  41433. this.pendingBoxes = [];
  41434. this.pendingCaptions = [];
  41435. this.pendingMetadata = [];
  41436. this.pendingBytes = 0;
  41437. this.emittedTracks = 0;
  41438. CoalesceStream.prototype.init.call(this); // Take output from multiple
  41439. this.push = function (output) {
  41440. // buffer incoming captions until the associated video segment
  41441. // finishes
  41442. if (output.text) {
  41443. return this.pendingCaptions.push(output);
  41444. } // buffer incoming id3 tags until the final flush
  41445. if (output.frames) {
  41446. return this.pendingMetadata.push(output);
  41447. } // Add this track to the list of pending tracks and store
  41448. // important information required for the construction of
  41449. // the final segment
  41450. this.pendingTracks.push(output.track);
  41451. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  41452. // We unshift audio and push video because
  41453. // as of Chrome 75 when switching from
  41454. // one init segment to another if the video
  41455. // mdat does not appear after the audio mdat
  41456. // only audio will play for the duration of our transmux.
  41457. if (output.track.type === 'video') {
  41458. this.videoTrack = output.track;
  41459. this.pendingBoxes.push(output.boxes);
  41460. }
  41461. if (output.track.type === 'audio') {
  41462. this.audioTrack = output.track;
  41463. this.pendingBoxes.unshift(output.boxes);
  41464. }
  41465. };
  41466. };
  41467. CoalesceStream.prototype = new Stream();
  41468. CoalesceStream.prototype.flush = function (flushSource) {
  41469. var offset = 0,
  41470. event = {
  41471. captions: [],
  41472. captionStreams: {},
  41473. metadata: [],
  41474. info: {}
  41475. },
  41476. caption,
  41477. id3,
  41478. initSegment,
  41479. timelineStartPts = 0,
  41480. i;
  41481. if (this.pendingTracks.length < this.numberOfTracks) {
  41482. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  41483. // Return because we haven't received a flush from a data-generating
  41484. // portion of the segment (meaning that we have only recieved meta-data
  41485. // or captions.)
  41486. return;
  41487. } else if (this.remuxTracks) {
  41488. // Return until we have enough tracks from the pipeline to remux (if we
  41489. // are remuxing audio and video into a single MP4)
  41490. return;
  41491. } else if (this.pendingTracks.length === 0) {
  41492. // In the case where we receive a flush without any data having been
  41493. // received we consider it an emitted track for the purposes of coalescing
  41494. // `done` events.
  41495. // We do this for the case where there is an audio and video track in the
  41496. // segment but no audio data. (seen in several playlists with alternate
  41497. // audio tracks and no audio present in the main TS segments.)
  41498. this.emittedTracks++;
  41499. if (this.emittedTracks >= this.numberOfTracks) {
  41500. this.trigger('done');
  41501. this.emittedTracks = 0;
  41502. }
  41503. return;
  41504. }
  41505. }
  41506. if (this.videoTrack) {
  41507. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  41508. VIDEO_PROPERTIES.forEach(function (prop) {
  41509. event.info[prop] = this.videoTrack[prop];
  41510. }, this);
  41511. } else if (this.audioTrack) {
  41512. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  41513. AUDIO_PROPERTIES.forEach(function (prop) {
  41514. event.info[prop] = this.audioTrack[prop];
  41515. }, this);
  41516. }
  41517. if (this.videoTrack || this.audioTrack) {
  41518. if (this.pendingTracks.length === 1) {
  41519. event.type = this.pendingTracks[0].type;
  41520. } else {
  41521. event.type = 'combined';
  41522. }
  41523. this.emittedTracks += this.pendingTracks.length;
  41524. initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  41525. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  41526. // and track definitions
  41527. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  41528. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  41529. for (i = 0; i < this.pendingBoxes.length; i++) {
  41530. event.data.set(this.pendingBoxes[i], offset);
  41531. offset += this.pendingBoxes[i].byteLength;
  41532. } // Translate caption PTS times into second offsets to match the
  41533. // video timeline for the segment, and add track info
  41534. for (i = 0; i < this.pendingCaptions.length; i++) {
  41535. caption = this.pendingCaptions[i];
  41536. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  41537. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  41538. event.captionStreams[caption.stream] = true;
  41539. event.captions.push(caption);
  41540. } // Translate ID3 frame PTS times into second offsets to match the
  41541. // video timeline for the segment
  41542. for (i = 0; i < this.pendingMetadata.length; i++) {
  41543. id3 = this.pendingMetadata[i];
  41544. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  41545. event.metadata.push(id3);
  41546. } // We add this to every single emitted segment even though we only need
  41547. // it for the first
  41548. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  41549. this.pendingTracks.length = 0;
  41550. this.videoTrack = null;
  41551. this.pendingBoxes.length = 0;
  41552. this.pendingCaptions.length = 0;
  41553. this.pendingBytes = 0;
  41554. this.pendingMetadata.length = 0; // Emit the built segment
  41555. // We include captions and ID3 tags for backwards compatibility,
  41556. // ideally we should send only video and audio in the data event
  41557. this.trigger('data', event); // Emit each caption to the outside world
  41558. // Ideally, this would happen immediately on parsing captions,
  41559. // but we need to ensure that video data is sent back first
  41560. // so that caption timing can be adjusted to match video timing
  41561. for (i = 0; i < event.captions.length; i++) {
  41562. caption = event.captions[i];
  41563. this.trigger('caption', caption);
  41564. } // Emit each id3 tag to the outside world
  41565. // Ideally, this would happen immediately on parsing the tag,
  41566. // but we need to ensure that video data is sent back first
  41567. // so that ID3 frame timing can be adjusted to match video timing
  41568. for (i = 0; i < event.metadata.length; i++) {
  41569. id3 = event.metadata[i];
  41570. this.trigger('id3Frame', id3);
  41571. }
  41572. } // Only emit `done` if all tracks have been flushed and emitted
  41573. if (this.emittedTracks >= this.numberOfTracks) {
  41574. this.trigger('done');
  41575. this.emittedTracks = 0;
  41576. }
  41577. };
  41578. CoalesceStream.prototype.setRemux = function (val) {
  41579. this.remuxTracks = val;
  41580. };
  41581. /**
  41582. * A Stream that expects MP2T binary data as input and produces
  41583. * corresponding media segments, suitable for use with Media Source
  41584. * Extension (MSE) implementations that support the ISO BMFF byte
  41585. * stream format, like Chrome.
  41586. */
  41587. Transmuxer = function (options) {
  41588. var self = this,
  41589. hasFlushed = true,
  41590. videoTrack,
  41591. audioTrack;
  41592. Transmuxer.prototype.init.call(this);
  41593. options = options || {};
  41594. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  41595. this.transmuxPipeline_ = {};
  41596. this.setupAacPipeline = function () {
  41597. var pipeline = {};
  41598. this.transmuxPipeline_ = pipeline;
  41599. pipeline.type = 'aac';
  41600. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  41601. pipeline.aacStream = new AacStream();
  41602. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  41603. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  41604. pipeline.adtsStream = new AdtsStream();
  41605. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  41606. pipeline.headOfPipeline = pipeline.aacStream;
  41607. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  41608. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  41609. pipeline.metadataStream.on('timestamp', function (frame) {
  41610. pipeline.aacStream.setTimestamp(frame.timeStamp);
  41611. });
  41612. pipeline.aacStream.on('data', function (data) {
  41613. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  41614. return;
  41615. }
  41616. audioTrack = audioTrack || {
  41617. timelineStartInfo: {
  41618. baseMediaDecodeTime: self.baseMediaDecodeTime
  41619. },
  41620. codec: 'adts',
  41621. type: 'audio'
  41622. }; // hook up the audio segment stream to the first track with aac data
  41623. pipeline.coalesceStream.numberOfTracks++;
  41624. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  41625. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  41626. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  41627. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  41628. self.trigger('trackinfo', {
  41629. hasAudio: !!audioTrack,
  41630. hasVideo: !!videoTrack
  41631. });
  41632. }); // Re-emit any data coming from the coalesce stream to the outside world
  41633. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  41634. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  41635. addPipelineLogRetriggers(this, pipeline);
  41636. };
  41637. this.setupTsPipeline = function () {
  41638. var pipeline = {};
  41639. this.transmuxPipeline_ = pipeline;
  41640. pipeline.type = 'ts';
  41641. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  41642. pipeline.packetStream = new m2ts.TransportPacketStream();
  41643. pipeline.parseStream = new m2ts.TransportParseStream();
  41644. pipeline.elementaryStream = new m2ts.ElementaryStream();
  41645. pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
  41646. pipeline.adtsStream = new AdtsStream();
  41647. pipeline.h264Stream = new H264Stream();
  41648. pipeline.captionStream = new m2ts.CaptionStream(options);
  41649. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  41650. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  41651. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  41652. // demux the streams
  41653. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  41654. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  41655. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  41656. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  41657. pipeline.elementaryStream.on('data', function (data) {
  41658. var i;
  41659. if (data.type === 'metadata') {
  41660. i = data.tracks.length; // scan the tracks listed in the metadata
  41661. while (i--) {
  41662. if (!videoTrack && data.tracks[i].type === 'video') {
  41663. videoTrack = data.tracks[i];
  41664. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  41665. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  41666. audioTrack = data.tracks[i];
  41667. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  41668. }
  41669. } // hook up the video segment stream to the first track with h264 data
  41670. if (videoTrack && !pipeline.videoSegmentStream) {
  41671. pipeline.coalesceStream.numberOfTracks++;
  41672. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  41673. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  41674. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  41675. // When video emits timelineStartInfo data after a flush, we forward that
  41676. // info to the AudioSegmentStream, if it exists, because video timeline
  41677. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  41678. // because this is a particularly subtle form of timestamp alteration.
  41679. if (audioTrack && !options.keepOriginalTimestamps) {
  41680. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  41681. // very earliest DTS we have seen in video because Chrome will
  41682. // interpret any video track with a baseMediaDecodeTime that is
  41683. // non-zero as a gap.
  41684. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  41685. }
  41686. });
  41687. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  41688. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  41689. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  41690. if (audioTrack) {
  41691. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  41692. }
  41693. });
  41694. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  41695. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  41696. }
  41697. if (audioTrack && !pipeline.audioSegmentStream) {
  41698. // hook up the audio segment stream to the first track with aac data
  41699. pipeline.coalesceStream.numberOfTracks++;
  41700. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  41701. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  41702. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  41703. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  41704. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  41705. } // emit pmt info
  41706. self.trigger('trackinfo', {
  41707. hasAudio: !!audioTrack,
  41708. hasVideo: !!videoTrack
  41709. });
  41710. }
  41711. }); // Re-emit any data coming from the coalesce stream to the outside world
  41712. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  41713. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  41714. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  41715. self.trigger('id3Frame', id3Frame);
  41716. });
  41717. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  41718. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  41719. addPipelineLogRetriggers(this, pipeline);
  41720. }; // hook up the segment streams once track metadata is delivered
  41721. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  41722. var pipeline = this.transmuxPipeline_;
  41723. if (!options.keepOriginalTimestamps) {
  41724. this.baseMediaDecodeTime = baseMediaDecodeTime;
  41725. }
  41726. if (audioTrack) {
  41727. audioTrack.timelineStartInfo.dts = undefined;
  41728. audioTrack.timelineStartInfo.pts = undefined;
  41729. trackDecodeInfo.clearDtsInfo(audioTrack);
  41730. if (pipeline.audioTimestampRolloverStream) {
  41731. pipeline.audioTimestampRolloverStream.discontinuity();
  41732. }
  41733. }
  41734. if (videoTrack) {
  41735. if (pipeline.videoSegmentStream) {
  41736. pipeline.videoSegmentStream.gopCache_ = [];
  41737. }
  41738. videoTrack.timelineStartInfo.dts = undefined;
  41739. videoTrack.timelineStartInfo.pts = undefined;
  41740. trackDecodeInfo.clearDtsInfo(videoTrack);
  41741. pipeline.captionStream.reset();
  41742. }
  41743. if (pipeline.timestampRolloverStream) {
  41744. pipeline.timestampRolloverStream.discontinuity();
  41745. }
  41746. };
  41747. this.setAudioAppendStart = function (timestamp) {
  41748. if (audioTrack) {
  41749. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  41750. }
  41751. };
  41752. this.setRemux = function (val) {
  41753. var pipeline = this.transmuxPipeline_;
  41754. options.remux = val;
  41755. if (pipeline && pipeline.coalesceStream) {
  41756. pipeline.coalesceStream.setRemux(val);
  41757. }
  41758. };
  41759. this.alignGopsWith = function (gopsToAlignWith) {
  41760. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  41761. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  41762. }
  41763. };
  41764. this.getLogTrigger_ = function (key) {
  41765. var self = this;
  41766. return function (event) {
  41767. event.stream = key;
  41768. self.trigger('log', event);
  41769. };
  41770. }; // feed incoming data to the front of the parsing pipeline
  41771. this.push = function (data) {
  41772. if (hasFlushed) {
  41773. var isAac = isLikelyAacData(data);
  41774. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  41775. this.setupAacPipeline();
  41776. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  41777. this.setupTsPipeline();
  41778. }
  41779. hasFlushed = false;
  41780. }
  41781. this.transmuxPipeline_.headOfPipeline.push(data);
  41782. }; // flush any buffered data
  41783. this.flush = function () {
  41784. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  41785. this.transmuxPipeline_.headOfPipeline.flush();
  41786. };
  41787. this.endTimeline = function () {
  41788. this.transmuxPipeline_.headOfPipeline.endTimeline();
  41789. };
  41790. this.reset = function () {
  41791. if (this.transmuxPipeline_.headOfPipeline) {
  41792. this.transmuxPipeline_.headOfPipeline.reset();
  41793. }
  41794. }; // Caption data has to be reset when seeking outside buffered range
  41795. this.resetCaptions = function () {
  41796. if (this.transmuxPipeline_.captionStream) {
  41797. this.transmuxPipeline_.captionStream.reset();
  41798. }
  41799. };
  41800. };
  41801. Transmuxer.prototype = new Stream();
  41802. var transmuxer = {
  41803. Transmuxer: Transmuxer,
  41804. VideoSegmentStream: VideoSegmentStream,
  41805. AudioSegmentStream: AudioSegmentStream,
  41806. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  41807. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  41808. // exported for testing
  41809. generateSegmentTimingInfo: generateSegmentTimingInfo
  41810. };
  41811. /**
  41812. * mux.js
  41813. *
  41814. * Copyright (c) Brightcove
  41815. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  41816. */
  41817. var toUnsigned$3 = function (value) {
  41818. return value >>> 0;
  41819. };
  41820. var toHexString$1 = function (value) {
  41821. return ('00' + value.toString(16)).slice(-2);
  41822. };
  41823. var bin = {
  41824. toUnsigned: toUnsigned$3,
  41825. toHexString: toHexString$1
  41826. };
  41827. var parseType$3 = function (buffer) {
  41828. var result = '';
  41829. result += String.fromCharCode(buffer[0]);
  41830. result += String.fromCharCode(buffer[1]);
  41831. result += String.fromCharCode(buffer[2]);
  41832. result += String.fromCharCode(buffer[3]);
  41833. return result;
  41834. };
  41835. var parseType_1 = parseType$3;
  41836. var toUnsigned$2 = bin.toUnsigned;
  41837. var parseType$2 = parseType_1;
  41838. var findBox$2 = function (data, path) {
  41839. var results = [],
  41840. i,
  41841. size,
  41842. type,
  41843. end,
  41844. subresults;
  41845. if (!path.length) {
  41846. // short-circuit the search for empty paths
  41847. return null;
  41848. }
  41849. for (i = 0; i < data.byteLength;) {
  41850. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  41851. type = parseType$2(data.subarray(i + 4, i + 8));
  41852. end = size > 1 ? i + size : data.byteLength;
  41853. if (type === path[0]) {
  41854. if (path.length === 1) {
  41855. // this is the end of the path and we've found the box we were
  41856. // looking for
  41857. results.push(data.subarray(i + 8, end));
  41858. } else {
  41859. // recursively search for the next box along the path
  41860. subresults = findBox$2(data.subarray(i + 8, end), path.slice(1));
  41861. if (subresults.length) {
  41862. results = results.concat(subresults);
  41863. }
  41864. }
  41865. }
  41866. i = end;
  41867. } // we've finished searching all of data
  41868. return results;
  41869. };
  41870. var findBox_1 = findBox$2;
  41871. var toUnsigned$1 = bin.toUnsigned;
  41872. var getUint64$2 = numbers.getUint64;
  41873. var tfdt = function (data) {
  41874. var result = {
  41875. version: data[0],
  41876. flags: new Uint8Array(data.subarray(1, 4))
  41877. };
  41878. if (result.version === 1) {
  41879. result.baseMediaDecodeTime = getUint64$2(data.subarray(4));
  41880. } else {
  41881. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  41882. }
  41883. return result;
  41884. };
  41885. var parseTfdt$2 = tfdt;
  41886. var parseSampleFlags$1 = function (flags) {
  41887. return {
  41888. isLeading: (flags[0] & 0x0c) >>> 2,
  41889. dependsOn: flags[0] & 0x03,
  41890. isDependedOn: (flags[1] & 0xc0) >>> 6,
  41891. hasRedundancy: (flags[1] & 0x30) >>> 4,
  41892. paddingValue: (flags[1] & 0x0e) >>> 1,
  41893. isNonSyncSample: flags[1] & 0x01,
  41894. degradationPriority: flags[2] << 8 | flags[3]
  41895. };
  41896. };
  41897. var parseSampleFlags_1 = parseSampleFlags$1;
  41898. var parseSampleFlags = parseSampleFlags_1;
  41899. var trun = function (data) {
  41900. var result = {
  41901. version: data[0],
  41902. flags: new Uint8Array(data.subarray(1, 4)),
  41903. samples: []
  41904. },
  41905. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  41906. // Flag interpretation
  41907. dataOffsetPresent = result.flags[2] & 0x01,
  41908. // compare with 2nd byte of 0x1
  41909. firstSampleFlagsPresent = result.flags[2] & 0x04,
  41910. // compare with 2nd byte of 0x4
  41911. sampleDurationPresent = result.flags[1] & 0x01,
  41912. // compare with 2nd byte of 0x100
  41913. sampleSizePresent = result.flags[1] & 0x02,
  41914. // compare with 2nd byte of 0x200
  41915. sampleFlagsPresent = result.flags[1] & 0x04,
  41916. // compare with 2nd byte of 0x400
  41917. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  41918. // compare with 2nd byte of 0x800
  41919. sampleCount = view.getUint32(4),
  41920. offset = 8,
  41921. sample;
  41922. if (dataOffsetPresent) {
  41923. // 32 bit signed integer
  41924. result.dataOffset = view.getInt32(offset);
  41925. offset += 4;
  41926. } // Overrides the flags for the first sample only. The order of
  41927. // optional values will be: duration, size, compositionTimeOffset
  41928. if (firstSampleFlagsPresent && sampleCount) {
  41929. sample = {
  41930. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  41931. };
  41932. offset += 4;
  41933. if (sampleDurationPresent) {
  41934. sample.duration = view.getUint32(offset);
  41935. offset += 4;
  41936. }
  41937. if (sampleSizePresent) {
  41938. sample.size = view.getUint32(offset);
  41939. offset += 4;
  41940. }
  41941. if (sampleCompositionTimeOffsetPresent) {
  41942. if (result.version === 1) {
  41943. sample.compositionTimeOffset = view.getInt32(offset);
  41944. } else {
  41945. sample.compositionTimeOffset = view.getUint32(offset);
  41946. }
  41947. offset += 4;
  41948. }
  41949. result.samples.push(sample);
  41950. sampleCount--;
  41951. }
  41952. while (sampleCount--) {
  41953. sample = {};
  41954. if (sampleDurationPresent) {
  41955. sample.duration = view.getUint32(offset);
  41956. offset += 4;
  41957. }
  41958. if (sampleSizePresent) {
  41959. sample.size = view.getUint32(offset);
  41960. offset += 4;
  41961. }
  41962. if (sampleFlagsPresent) {
  41963. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  41964. offset += 4;
  41965. }
  41966. if (sampleCompositionTimeOffsetPresent) {
  41967. if (result.version === 1) {
  41968. sample.compositionTimeOffset = view.getInt32(offset);
  41969. } else {
  41970. sample.compositionTimeOffset = view.getUint32(offset);
  41971. }
  41972. offset += 4;
  41973. }
  41974. result.samples.push(sample);
  41975. }
  41976. return result;
  41977. };
  41978. var parseTrun$2 = trun;
  41979. var tfhd = function (data) {
  41980. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  41981. result = {
  41982. version: data[0],
  41983. flags: new Uint8Array(data.subarray(1, 4)),
  41984. trackId: view.getUint32(4)
  41985. },
  41986. baseDataOffsetPresent = result.flags[2] & 0x01,
  41987. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  41988. defaultSampleDurationPresent = result.flags[2] & 0x08,
  41989. defaultSampleSizePresent = result.flags[2] & 0x10,
  41990. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  41991. durationIsEmpty = result.flags[0] & 0x010000,
  41992. defaultBaseIsMoof = result.flags[0] & 0x020000,
  41993. i;
  41994. i = 8;
  41995. if (baseDataOffsetPresent) {
  41996. i += 4; // truncate top 4 bytes
  41997. // FIXME: should we read the full 64 bits?
  41998. result.baseDataOffset = view.getUint32(12);
  41999. i += 4;
  42000. }
  42001. if (sampleDescriptionIndexPresent) {
  42002. result.sampleDescriptionIndex = view.getUint32(i);
  42003. i += 4;
  42004. }
  42005. if (defaultSampleDurationPresent) {
  42006. result.defaultSampleDuration = view.getUint32(i);
  42007. i += 4;
  42008. }
  42009. if (defaultSampleSizePresent) {
  42010. result.defaultSampleSize = view.getUint32(i);
  42011. i += 4;
  42012. }
  42013. if (defaultSampleFlagsPresent) {
  42014. result.defaultSampleFlags = view.getUint32(i);
  42015. }
  42016. if (durationIsEmpty) {
  42017. result.durationIsEmpty = true;
  42018. }
  42019. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  42020. result.baseDataOffsetIsMoof = true;
  42021. }
  42022. return result;
  42023. };
  42024. var parseTfhd$2 = tfhd;
  42025. var win;
  42026. if (typeof window !== "undefined") {
  42027. win = window;
  42028. } else if (typeof commonjsGlobal !== "undefined") {
  42029. win = commonjsGlobal;
  42030. } else if (typeof self !== "undefined") {
  42031. win = self;
  42032. } else {
  42033. win = {};
  42034. }
  42035. var window_1 = win;
  42036. /**
  42037. * mux.js
  42038. *
  42039. * Copyright (c) Brightcove
  42040. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  42041. *
  42042. * Reads in-band CEA-708 captions out of FMP4 segments.
  42043. * @see https://en.wikipedia.org/wiki/CEA-708
  42044. */
  42045. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  42046. var CaptionStream = captionStream.CaptionStream;
  42047. var findBox$1 = findBox_1;
  42048. var parseTfdt$1 = parseTfdt$2;
  42049. var parseTrun$1 = parseTrun$2;
  42050. var parseTfhd$1 = parseTfhd$2;
  42051. var window$2 = window_1;
  42052. /**
  42053. * Maps an offset in the mdat to a sample based on the the size of the samples.
  42054. * Assumes that `parseSamples` has been called first.
  42055. *
  42056. * @param {Number} offset - The offset into the mdat
  42057. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  42058. * @return {?Object} The matching sample, or null if no match was found.
  42059. *
  42060. * @see ISO-BMFF-12/2015, Section 8.8.8
  42061. **/
  42062. var mapToSample = function (offset, samples) {
  42063. var approximateOffset = offset;
  42064. for (var i = 0; i < samples.length; i++) {
  42065. var sample = samples[i];
  42066. if (approximateOffset < sample.size) {
  42067. return sample;
  42068. }
  42069. approximateOffset -= sample.size;
  42070. }
  42071. return null;
  42072. };
  42073. /**
  42074. * Finds SEI nal units contained in a Media Data Box.
  42075. * Assumes that `parseSamples` has been called first.
  42076. *
  42077. * @param {Uint8Array} avcStream - The bytes of the mdat
  42078. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  42079. * @param {Number} trackId - The trackId of this video track
  42080. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  42081. * The contents of the seiNal should match what is expected by
  42082. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  42083. *
  42084. * @see ISO-BMFF-12/2015, Section 8.1.1
  42085. * @see Rec. ITU-T H.264, 7.3.2.3.1
  42086. **/
  42087. var findSeiNals = function (avcStream, samples, trackId) {
  42088. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  42089. result = {
  42090. logs: [],
  42091. seiNals: []
  42092. },
  42093. seiNal,
  42094. i,
  42095. length,
  42096. lastMatchedSample;
  42097. for (i = 0; i + 4 < avcStream.length; i += length) {
  42098. length = avcView.getUint32(i);
  42099. i += 4; // Bail if this doesn't appear to be an H264 stream
  42100. if (length <= 0) {
  42101. continue;
  42102. }
  42103. switch (avcStream[i] & 0x1F) {
  42104. case 0x06:
  42105. var data = avcStream.subarray(i + 1, i + 1 + length);
  42106. var matchingSample = mapToSample(i, samples);
  42107. seiNal = {
  42108. nalUnitType: 'sei_rbsp',
  42109. size: length,
  42110. data: data,
  42111. escapedRBSP: discardEmulationPreventionBytes(data),
  42112. trackId: trackId
  42113. };
  42114. if (matchingSample) {
  42115. seiNal.pts = matchingSample.pts;
  42116. seiNal.dts = matchingSample.dts;
  42117. lastMatchedSample = matchingSample;
  42118. } else if (lastMatchedSample) {
  42119. // If a matching sample cannot be found, use the last
  42120. // sample's values as they should be as close as possible
  42121. seiNal.pts = lastMatchedSample.pts;
  42122. seiNal.dts = lastMatchedSample.dts;
  42123. } else {
  42124. result.logs.push({
  42125. level: 'warn',
  42126. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  42127. });
  42128. break;
  42129. }
  42130. result.seiNals.push(seiNal);
  42131. break;
  42132. }
  42133. }
  42134. return result;
  42135. };
  42136. /**
  42137. * Parses sample information out of Track Run Boxes and calculates
  42138. * the absolute presentation and decode timestamps of each sample.
  42139. *
  42140. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  42141. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  42142. @see ISO-BMFF-12/2015, Section 8.8.12
  42143. * @param {Object} tfhd - The parsed Track Fragment Header
  42144. * @see inspect.parseTfhd
  42145. * @return {Object[]} the parsed samples
  42146. *
  42147. * @see ISO-BMFF-12/2015, Section 8.8.8
  42148. **/
  42149. var parseSamples = function (truns, baseMediaDecodeTime, tfhd) {
  42150. var currentDts = baseMediaDecodeTime;
  42151. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  42152. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  42153. var trackId = tfhd.trackId;
  42154. var allSamples = [];
  42155. truns.forEach(function (trun) {
  42156. // Note: We currently do not parse the sample table as well
  42157. // as the trun. It's possible some sources will require this.
  42158. // moov > trak > mdia > minf > stbl
  42159. var trackRun = parseTrun$1(trun);
  42160. var samples = trackRun.samples;
  42161. samples.forEach(function (sample) {
  42162. if (sample.duration === undefined) {
  42163. sample.duration = defaultSampleDuration;
  42164. }
  42165. if (sample.size === undefined) {
  42166. sample.size = defaultSampleSize;
  42167. }
  42168. sample.trackId = trackId;
  42169. sample.dts = currentDts;
  42170. if (sample.compositionTimeOffset === undefined) {
  42171. sample.compositionTimeOffset = 0;
  42172. }
  42173. if (typeof currentDts === 'bigint') {
  42174. sample.pts = currentDts + window$2.BigInt(sample.compositionTimeOffset);
  42175. currentDts += window$2.BigInt(sample.duration);
  42176. } else {
  42177. sample.pts = currentDts + sample.compositionTimeOffset;
  42178. currentDts += sample.duration;
  42179. }
  42180. });
  42181. allSamples = allSamples.concat(samples);
  42182. });
  42183. return allSamples;
  42184. };
  42185. /**
  42186. * Parses out caption nals from an FMP4 segment's video tracks.
  42187. *
  42188. * @param {Uint8Array} segment - The bytes of a single segment
  42189. * @param {Number} videoTrackId - The trackId of a video track in the segment
  42190. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  42191. * a list of seiNals found in that track
  42192. **/
  42193. var parseCaptionNals = function (segment, videoTrackId) {
  42194. // To get the samples
  42195. var trafs = findBox$1(segment, ['moof', 'traf']); // To get SEI NAL units
  42196. var mdats = findBox$1(segment, ['mdat']);
  42197. var captionNals = {};
  42198. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  42199. mdats.forEach(function (mdat, index) {
  42200. var matchingTraf = trafs[index];
  42201. mdatTrafPairs.push({
  42202. mdat: mdat,
  42203. traf: matchingTraf
  42204. });
  42205. });
  42206. mdatTrafPairs.forEach(function (pair) {
  42207. var mdat = pair.mdat;
  42208. var traf = pair.traf;
  42209. var tfhd = findBox$1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  42210. var headerInfo = parseTfhd$1(tfhd[0]);
  42211. var trackId = headerInfo.trackId;
  42212. var tfdt = findBox$1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  42213. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt$1(tfdt[0]).baseMediaDecodeTime : 0;
  42214. var truns = findBox$1(traf, ['trun']);
  42215. var samples;
  42216. var result; // Only parse video data for the chosen video track
  42217. if (videoTrackId === trackId && truns.length > 0) {
  42218. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  42219. result = findSeiNals(mdat, samples, trackId);
  42220. if (!captionNals[trackId]) {
  42221. captionNals[trackId] = {
  42222. seiNals: [],
  42223. logs: []
  42224. };
  42225. }
  42226. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  42227. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  42228. }
  42229. });
  42230. return captionNals;
  42231. };
  42232. /**
  42233. * Parses out inband captions from an MP4 container and returns
  42234. * caption objects that can be used by WebVTT and the TextTrack API.
  42235. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  42236. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  42237. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  42238. *
  42239. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  42240. * @param {Number} trackId - The id of the video track to parse
  42241. * @param {Number} timescale - The timescale for the video track from the init segment
  42242. *
  42243. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  42244. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  42245. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  42246. * @return {String} parsedCaptions[].text - The visible content of the caption
  42247. **/
  42248. var parseEmbeddedCaptions = function (segment, trackId, timescale) {
  42249. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  42250. if (trackId === null) {
  42251. return null;
  42252. }
  42253. captionNals = parseCaptionNals(segment, trackId);
  42254. var trackNals = captionNals[trackId] || {};
  42255. return {
  42256. seiNals: trackNals.seiNals,
  42257. logs: trackNals.logs,
  42258. timescale: timescale
  42259. };
  42260. };
  42261. /**
  42262. * Converts SEI NALUs into captions that can be used by video.js
  42263. **/
  42264. var CaptionParser = function () {
  42265. var isInitialized = false;
  42266. var captionStream; // Stores segments seen before trackId and timescale are set
  42267. var segmentCache; // Stores video track ID of the track being parsed
  42268. var trackId; // Stores the timescale of the track being parsed
  42269. var timescale; // Stores captions parsed so far
  42270. var parsedCaptions; // Stores whether we are receiving partial data or not
  42271. var parsingPartial;
  42272. /**
  42273. * A method to indicate whether a CaptionParser has been initalized
  42274. * @returns {Boolean}
  42275. **/
  42276. this.isInitialized = function () {
  42277. return isInitialized;
  42278. };
  42279. /**
  42280. * Initializes the underlying CaptionStream, SEI NAL parsing
  42281. * and management, and caption collection
  42282. **/
  42283. this.init = function (options) {
  42284. captionStream = new CaptionStream();
  42285. isInitialized = true;
  42286. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  42287. captionStream.on('data', function (event) {
  42288. // Convert to seconds in the source's timescale
  42289. event.startTime = event.startPts / timescale;
  42290. event.endTime = event.endPts / timescale;
  42291. parsedCaptions.captions.push(event);
  42292. parsedCaptions.captionStreams[event.stream] = true;
  42293. });
  42294. captionStream.on('log', function (log) {
  42295. parsedCaptions.logs.push(log);
  42296. });
  42297. };
  42298. /**
  42299. * Determines if a new video track will be selected
  42300. * or if the timescale changed
  42301. * @return {Boolean}
  42302. **/
  42303. this.isNewInit = function (videoTrackIds, timescales) {
  42304. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  42305. return false;
  42306. }
  42307. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  42308. };
  42309. /**
  42310. * Parses out SEI captions and interacts with underlying
  42311. * CaptionStream to return dispatched captions
  42312. *
  42313. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  42314. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  42315. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  42316. * @see parseEmbeddedCaptions
  42317. * @see m2ts/caption-stream.js
  42318. **/
  42319. this.parse = function (segment, videoTrackIds, timescales) {
  42320. var parsedData;
  42321. if (!this.isInitialized()) {
  42322. return null; // This is not likely to be a video segment
  42323. } else if (!videoTrackIds || !timescales) {
  42324. return null;
  42325. } else if (this.isNewInit(videoTrackIds, timescales)) {
  42326. // Use the first video track only as there is no
  42327. // mechanism to switch to other video tracks
  42328. trackId = videoTrackIds[0];
  42329. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  42330. // data until we have one.
  42331. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  42332. } else if (trackId === null || !timescale) {
  42333. segmentCache.push(segment);
  42334. return null;
  42335. } // Now that a timescale and trackId is set, parse cached segments
  42336. while (segmentCache.length > 0) {
  42337. var cachedSegment = segmentCache.shift();
  42338. this.parse(cachedSegment, videoTrackIds, timescales);
  42339. }
  42340. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  42341. if (parsedData && parsedData.logs) {
  42342. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  42343. }
  42344. if (parsedData === null || !parsedData.seiNals) {
  42345. if (parsedCaptions.logs.length) {
  42346. return {
  42347. logs: parsedCaptions.logs,
  42348. captions: [],
  42349. captionStreams: []
  42350. };
  42351. }
  42352. return null;
  42353. }
  42354. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  42355. this.flushStream();
  42356. return parsedCaptions;
  42357. };
  42358. /**
  42359. * Pushes SEI NALUs onto CaptionStream
  42360. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  42361. * Assumes that `parseCaptionNals` has been called first
  42362. * @see m2ts/caption-stream.js
  42363. **/
  42364. this.pushNals = function (nals) {
  42365. if (!this.isInitialized() || !nals || nals.length === 0) {
  42366. return null;
  42367. }
  42368. nals.forEach(function (nal) {
  42369. captionStream.push(nal);
  42370. });
  42371. };
  42372. /**
  42373. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  42374. * @see m2ts/caption-stream.js
  42375. **/
  42376. this.flushStream = function () {
  42377. if (!this.isInitialized()) {
  42378. return null;
  42379. }
  42380. if (!parsingPartial) {
  42381. captionStream.flush();
  42382. } else {
  42383. captionStream.partialFlush();
  42384. }
  42385. };
  42386. /**
  42387. * Reset caption buckets for new data
  42388. **/
  42389. this.clearParsedCaptions = function () {
  42390. parsedCaptions.captions = [];
  42391. parsedCaptions.captionStreams = {};
  42392. parsedCaptions.logs = [];
  42393. };
  42394. /**
  42395. * Resets underlying CaptionStream
  42396. * @see m2ts/caption-stream.js
  42397. **/
  42398. this.resetCaptionStream = function () {
  42399. if (!this.isInitialized()) {
  42400. return null;
  42401. }
  42402. captionStream.reset();
  42403. };
  42404. /**
  42405. * Convenience method to clear all captions flushed from the
  42406. * CaptionStream and still being parsed
  42407. * @see m2ts/caption-stream.js
  42408. **/
  42409. this.clearAllCaptions = function () {
  42410. this.clearParsedCaptions();
  42411. this.resetCaptionStream();
  42412. };
  42413. /**
  42414. * Reset caption parser
  42415. **/
  42416. this.reset = function () {
  42417. segmentCache = [];
  42418. trackId = null;
  42419. timescale = null;
  42420. if (!parsedCaptions) {
  42421. parsedCaptions = {
  42422. captions: [],
  42423. // CC1, CC2, CC3, CC4
  42424. captionStreams: {},
  42425. logs: []
  42426. };
  42427. } else {
  42428. this.clearParsedCaptions();
  42429. }
  42430. this.resetCaptionStream();
  42431. };
  42432. this.reset();
  42433. };
  42434. var captionParser = CaptionParser;
  42435. /**
  42436. * Returns the first string in the data array ending with a null char '\0'
  42437. * @param {UInt8} data
  42438. * @returns the string with the null char
  42439. */
  42440. var uint8ToCString$1 = function (data) {
  42441. var index = 0;
  42442. var curChar = String.fromCharCode(data[index]);
  42443. var retString = '';
  42444. while (curChar !== '\0') {
  42445. retString += curChar;
  42446. index++;
  42447. curChar = String.fromCharCode(data[index]);
  42448. } // Add nullChar
  42449. retString += curChar;
  42450. return retString;
  42451. };
  42452. var string = {
  42453. uint8ToCString: uint8ToCString$1
  42454. };
  42455. var uint8ToCString = string.uint8ToCString;
  42456. var getUint64$1 = numbers.getUint64;
  42457. /**
  42458. * Based on: ISO/IEC 23009 Section: 5.10.3.3
  42459. * References:
  42460. * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format
  42461. * https://aomediacodec.github.io/id3-emsg/
  42462. *
  42463. * Takes emsg box data as a uint8 array and returns a emsg box object
  42464. * @param {UInt8Array} boxData data from emsg box
  42465. * @returns A parsed emsg box object
  42466. */
  42467. var parseEmsgBox = function (boxData) {
  42468. // version + flags
  42469. var offset = 4;
  42470. var version = boxData[0];
  42471. var scheme_id_uri, value, timescale, presentation_time, presentation_time_delta, event_duration, id, message_data;
  42472. if (version === 0) {
  42473. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  42474. offset += scheme_id_uri.length;
  42475. value = uint8ToCString(boxData.subarray(offset));
  42476. offset += value.length;
  42477. var dv = new DataView(boxData.buffer);
  42478. timescale = dv.getUint32(offset);
  42479. offset += 4;
  42480. presentation_time_delta = dv.getUint32(offset);
  42481. offset += 4;
  42482. event_duration = dv.getUint32(offset);
  42483. offset += 4;
  42484. id = dv.getUint32(offset);
  42485. offset += 4;
  42486. } else if (version === 1) {
  42487. var dv = new DataView(boxData.buffer);
  42488. timescale = dv.getUint32(offset);
  42489. offset += 4;
  42490. presentation_time = getUint64$1(boxData.subarray(offset));
  42491. offset += 8;
  42492. event_duration = dv.getUint32(offset);
  42493. offset += 4;
  42494. id = dv.getUint32(offset);
  42495. offset += 4;
  42496. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  42497. offset += scheme_id_uri.length;
  42498. value = uint8ToCString(boxData.subarray(offset));
  42499. offset += value.length;
  42500. }
  42501. message_data = new Uint8Array(boxData.subarray(offset, boxData.byteLength));
  42502. var emsgBox = {
  42503. scheme_id_uri,
  42504. value,
  42505. // if timescale is undefined or 0 set to 1
  42506. timescale: timescale ? timescale : 1,
  42507. presentation_time,
  42508. presentation_time_delta,
  42509. event_duration,
  42510. id,
  42511. message_data
  42512. };
  42513. return isValidEmsgBox(version, emsgBox) ? emsgBox : undefined;
  42514. };
  42515. /**
  42516. * Scales a presentation time or time delta with an offset with a provided timescale
  42517. * @param {number} presentationTime
  42518. * @param {number} timescale
  42519. * @param {number} timeDelta
  42520. * @param {number} offset
  42521. * @returns the scaled time as a number
  42522. */
  42523. var scaleTime = function (presentationTime, timescale, timeDelta, offset) {
  42524. return presentationTime || presentationTime === 0 ? presentationTime / timescale : offset + timeDelta / timescale;
  42525. };
  42526. /**
  42527. * Checks the emsg box data for validity based on the version
  42528. * @param {number} version of the emsg box to validate
  42529. * @param {Object} emsg the emsg data to validate
  42530. * @returns if the box is valid as a boolean
  42531. */
  42532. var isValidEmsgBox = function (version, emsg) {
  42533. var hasScheme = emsg.scheme_id_uri !== '\0';
  42534. var isValidV0Box = version === 0 && isDefined(emsg.presentation_time_delta) && hasScheme;
  42535. var isValidV1Box = version === 1 && isDefined(emsg.presentation_time) && hasScheme; // Only valid versions of emsg are 0 and 1
  42536. return !(version > 1) && isValidV0Box || isValidV1Box;
  42537. }; // Utility function to check if an object is defined
  42538. var isDefined = function (data) {
  42539. return data !== undefined || data !== null;
  42540. };
  42541. var emsg$1 = {
  42542. parseEmsgBox: parseEmsgBox,
  42543. scaleTime: scaleTime
  42544. };
  42545. /**
  42546. * mux.js
  42547. *
  42548. * Copyright (c) Brightcove
  42549. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  42550. *
  42551. * Utilities to detect basic properties and metadata about MP4s.
  42552. */
  42553. var toUnsigned = bin.toUnsigned;
  42554. var toHexString = bin.toHexString;
  42555. var findBox = findBox_1;
  42556. var parseType$1 = parseType_1;
  42557. var emsg = emsg$1;
  42558. var parseTfhd = parseTfhd$2;
  42559. var parseTrun = parseTrun$2;
  42560. var parseTfdt = parseTfdt$2;
  42561. var getUint64 = numbers.getUint64;
  42562. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader, getEmsgID3;
  42563. var window$1 = window_1;
  42564. var parseId3Frames = parseId3.parseId3Frames;
  42565. /**
  42566. * Parses an MP4 initialization segment and extracts the timescale
  42567. * values for any declared tracks. Timescale values indicate the
  42568. * number of clock ticks per second to assume for time-based values
  42569. * elsewhere in the MP4.
  42570. *
  42571. * To determine the start time of an MP4, you need two pieces of
  42572. * information: the timescale unit and the earliest base media decode
  42573. * time. Multiple timescales can be specified within an MP4 but the
  42574. * base media decode time is always expressed in the timescale from
  42575. * the media header box for the track:
  42576. * ```
  42577. * moov > trak > mdia > mdhd.timescale
  42578. * ```
  42579. * @param init {Uint8Array} the bytes of the init segment
  42580. * @return {object} a hash of track ids to timescale values or null if
  42581. * the init segment is malformed.
  42582. */
  42583. timescale = function (init) {
  42584. var result = {},
  42585. traks = findBox(init, ['moov', 'trak']); // mdhd timescale
  42586. return traks.reduce(function (result, trak) {
  42587. var tkhd, version, index, id, mdhd;
  42588. tkhd = findBox(trak, ['tkhd'])[0];
  42589. if (!tkhd) {
  42590. return null;
  42591. }
  42592. version = tkhd[0];
  42593. index = version === 0 ? 12 : 20;
  42594. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  42595. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  42596. if (!mdhd) {
  42597. return null;
  42598. }
  42599. version = mdhd[0];
  42600. index = version === 0 ? 12 : 20;
  42601. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  42602. return result;
  42603. }, result);
  42604. };
  42605. /**
  42606. * Determine the base media decode start time, in seconds, for an MP4
  42607. * fragment. If multiple fragments are specified, the earliest time is
  42608. * returned.
  42609. *
  42610. * The base media decode time can be parsed from track fragment
  42611. * metadata:
  42612. * ```
  42613. * moof > traf > tfdt.baseMediaDecodeTime
  42614. * ```
  42615. * It requires the timescale value from the mdhd to interpret.
  42616. *
  42617. * @param timescale {object} a hash of track ids to timescale values.
  42618. * @return {number} the earliest base media decode start time for the
  42619. * fragment, in seconds
  42620. */
  42621. startTime = function (timescale, fragment) {
  42622. var trafs; // we need info from two childrend of each track fragment box
  42623. trafs = findBox(fragment, ['moof', 'traf']); // determine the start times for each track
  42624. var lowestTime = trafs.reduce(function (acc, traf) {
  42625. var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
  42626. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  42627. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  42628. var tfdt = findBox(traf, ['tfdt'])[0];
  42629. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  42630. var baseTime; // version 1 is 64 bit
  42631. if (tfdt[0] === 1) {
  42632. baseTime = getUint64(tfdt.subarray(4, 12));
  42633. } else {
  42634. baseTime = dv.getUint32(4);
  42635. } // convert base time to seconds if it is a valid number.
  42636. let seconds;
  42637. if (typeof baseTime === 'bigint') {
  42638. seconds = baseTime / window$1.BigInt(scale);
  42639. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  42640. seconds = baseTime / scale;
  42641. }
  42642. if (seconds < Number.MAX_SAFE_INTEGER) {
  42643. seconds = Number(seconds);
  42644. }
  42645. if (seconds < acc) {
  42646. acc = seconds;
  42647. }
  42648. return acc;
  42649. }, Infinity);
  42650. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  42651. };
  42652. /**
  42653. * Determine the composition start, in seconds, for an MP4
  42654. * fragment.
  42655. *
  42656. * The composition start time of a fragment can be calculated using the base
  42657. * media decode time, composition time offset, and timescale, as follows:
  42658. *
  42659. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  42660. *
  42661. * All of the aforementioned information is contained within a media fragment's
  42662. * `traf` box, except for timescale info, which comes from the initialization
  42663. * segment, so a track id (also contained within a `traf`) is also necessary to
  42664. * associate it with a timescale
  42665. *
  42666. *
  42667. * @param timescales {object} - a hash of track ids to timescale values.
  42668. * @param fragment {Unit8Array} - the bytes of a media segment
  42669. * @return {number} the composition start time for the fragment, in seconds
  42670. **/
  42671. compositionStartTime = function (timescales, fragment) {
  42672. var trafBoxes = findBox(fragment, ['moof', 'traf']);
  42673. var baseMediaDecodeTime = 0;
  42674. var compositionTimeOffset = 0;
  42675. var trackId;
  42676. if (trafBoxes && trafBoxes.length) {
  42677. // The spec states that track run samples contained within a `traf` box are contiguous, but
  42678. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  42679. // We will assume that they are, so we only need the first to calculate start time.
  42680. var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
  42681. var trun = findBox(trafBoxes[0], ['trun'])[0];
  42682. var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];
  42683. if (tfhd) {
  42684. var parsedTfhd = parseTfhd(tfhd);
  42685. trackId = parsedTfhd.trackId;
  42686. }
  42687. if (tfdt) {
  42688. var parsedTfdt = parseTfdt(tfdt);
  42689. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  42690. }
  42691. if (trun) {
  42692. var parsedTrun = parseTrun(trun);
  42693. if (parsedTrun.samples && parsedTrun.samples.length) {
  42694. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  42695. }
  42696. }
  42697. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  42698. // specified.
  42699. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  42700. if (typeof baseMediaDecodeTime === 'bigint') {
  42701. compositionTimeOffset = window$1.BigInt(compositionTimeOffset);
  42702. timescale = window$1.BigInt(timescale);
  42703. }
  42704. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  42705. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  42706. result = Number(result);
  42707. }
  42708. return result;
  42709. };
  42710. /**
  42711. * Find the trackIds of the video tracks in this source.
  42712. * Found by parsing the Handler Reference and Track Header Boxes:
  42713. * moov > trak > mdia > hdlr
  42714. * moov > trak > tkhd
  42715. *
  42716. * @param {Uint8Array} init - The bytes of the init segment for this source
  42717. * @return {Number[]} A list of trackIds
  42718. *
  42719. * @see ISO-BMFF-12/2015, Section 8.4.3
  42720. **/
  42721. getVideoTrackIds = function (init) {
  42722. var traks = findBox(init, ['moov', 'trak']);
  42723. var videoTrackIds = [];
  42724. traks.forEach(function (trak) {
  42725. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  42726. var tkhds = findBox(trak, ['tkhd']);
  42727. hdlrs.forEach(function (hdlr, index) {
  42728. var handlerType = parseType$1(hdlr.subarray(8, 12));
  42729. var tkhd = tkhds[index];
  42730. var view;
  42731. var version;
  42732. var trackId;
  42733. if (handlerType === 'vide') {
  42734. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  42735. version = view.getUint8(0);
  42736. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  42737. videoTrackIds.push(trackId);
  42738. }
  42739. });
  42740. });
  42741. return videoTrackIds;
  42742. };
  42743. getTimescaleFromMediaHeader = function (mdhd) {
  42744. // mdhd is a FullBox, meaning it will have its own version as the first byte
  42745. var version = mdhd[0];
  42746. var index = version === 0 ? 12 : 20;
  42747. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  42748. };
  42749. /**
  42750. * Get all the video, audio, and hint tracks from a non fragmented
  42751. * mp4 segment
  42752. */
  42753. getTracks = function (init) {
  42754. var traks = findBox(init, ['moov', 'trak']);
  42755. var tracks = [];
  42756. traks.forEach(function (trak) {
  42757. var track = {};
  42758. var tkhd = findBox(trak, ['tkhd'])[0];
  42759. var view, tkhdVersion; // id
  42760. if (tkhd) {
  42761. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  42762. tkhdVersion = view.getUint8(0);
  42763. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  42764. }
  42765. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0]; // type
  42766. if (hdlr) {
  42767. var type = parseType$1(hdlr.subarray(8, 12));
  42768. if (type === 'vide') {
  42769. track.type = 'video';
  42770. } else if (type === 'soun') {
  42771. track.type = 'audio';
  42772. } else {
  42773. track.type = type;
  42774. }
  42775. } // codec
  42776. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  42777. if (stsd) {
  42778. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  42779. track.codec = parseType$1(sampleDescriptions.subarray(4, 8));
  42780. var codecBox = findBox(sampleDescriptions, [track.codec])[0];
  42781. var codecConfig, codecConfigType;
  42782. if (codecBox) {
  42783. // https://tools.ietf.org/html/rfc6381#section-3.3
  42784. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  42785. // we don't need anything but the "config" parameter of the
  42786. // avc1 codecBox
  42787. codecConfig = codecBox.subarray(78);
  42788. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  42789. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  42790. track.codec += '.'; // left padded with zeroes for single digit hex
  42791. // profile idc
  42792. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  42793. track.codec += toHexString(codecConfig[10]); // level idc
  42794. track.codec += toHexString(codecConfig[11]);
  42795. } else {
  42796. // TODO: show a warning that we couldn't parse the codec
  42797. // and are using the default
  42798. track.codec = 'avc1.4d400d';
  42799. }
  42800. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  42801. // we do not need anything but the streamDescriptor of the mp4a codecBox
  42802. codecConfig = codecBox.subarray(28);
  42803. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  42804. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  42805. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  42806. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  42807. } else {
  42808. // TODO: show a warning that we couldn't parse the codec
  42809. // and are using the default
  42810. track.codec = 'mp4a.40.2';
  42811. }
  42812. } else {
  42813. // flac, opus, etc
  42814. track.codec = track.codec.toLowerCase();
  42815. }
  42816. }
  42817. }
  42818. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  42819. if (mdhd) {
  42820. track.timescale = getTimescaleFromMediaHeader(mdhd);
  42821. }
  42822. tracks.push(track);
  42823. });
  42824. return tracks;
  42825. };
  42826. /**
  42827. * Returns an array of emsg ID3 data from the provided segmentData.
  42828. * An offset can also be provided as the Latest Arrival Time to calculate
  42829. * the Event Start Time of v0 EMSG boxes.
  42830. * See: https://dashif-documents.azurewebsites.net/Events/master/event.html#Inband-event-timing
  42831. *
  42832. * @param {Uint8Array} segmentData the segment byte array.
  42833. * @param {number} offset the segment start time or Latest Arrival Time,
  42834. * @return {Object[]} an array of ID3 parsed from EMSG boxes
  42835. */
  42836. getEmsgID3 = function (segmentData, offset = 0) {
  42837. var emsgBoxes = findBox(segmentData, ['emsg']);
  42838. return emsgBoxes.map(data => {
  42839. var parsedBox = emsg.parseEmsgBox(new Uint8Array(data));
  42840. var parsedId3Frames = parseId3Frames(parsedBox.message_data);
  42841. return {
  42842. cueTime: emsg.scaleTime(parsedBox.presentation_time, parsedBox.timescale, parsedBox.presentation_time_delta, offset),
  42843. duration: emsg.scaleTime(parsedBox.event_duration, parsedBox.timescale),
  42844. frames: parsedId3Frames
  42845. };
  42846. });
  42847. };
  42848. var probe$2 = {
  42849. // export mp4 inspector's findBox and parseType for backwards compatibility
  42850. findBox: findBox,
  42851. parseType: parseType$1,
  42852. timescale: timescale,
  42853. startTime: startTime,
  42854. compositionStartTime: compositionStartTime,
  42855. videoTrackIds: getVideoTrackIds,
  42856. tracks: getTracks,
  42857. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader,
  42858. getEmsgID3: getEmsgID3
  42859. };
  42860. /**
  42861. * mux.js
  42862. *
  42863. * Copyright (c) Brightcove
  42864. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  42865. *
  42866. * Utilities to detect basic properties and metadata about TS Segments.
  42867. */
  42868. var StreamTypes$1 = streamTypes;
  42869. var parsePid = function (packet) {
  42870. var pid = packet[1] & 0x1f;
  42871. pid <<= 8;
  42872. pid |= packet[2];
  42873. return pid;
  42874. };
  42875. var parsePayloadUnitStartIndicator = function (packet) {
  42876. return !!(packet[1] & 0x40);
  42877. };
  42878. var parseAdaptionField = function (packet) {
  42879. var offset = 0; // if an adaption field is present, its length is specified by the
  42880. // fifth byte of the TS packet header. The adaptation field is
  42881. // used to add stuffing to PES packets that don't fill a complete
  42882. // TS packet, and to specify some forms of timing and control data
  42883. // that we do not currently use.
  42884. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  42885. offset += packet[4] + 1;
  42886. }
  42887. return offset;
  42888. };
  42889. var parseType = function (packet, pmtPid) {
  42890. var pid = parsePid(packet);
  42891. if (pid === 0) {
  42892. return 'pat';
  42893. } else if (pid === pmtPid) {
  42894. return 'pmt';
  42895. } else if (pmtPid) {
  42896. return 'pes';
  42897. }
  42898. return null;
  42899. };
  42900. var parsePat = function (packet) {
  42901. var pusi = parsePayloadUnitStartIndicator(packet);
  42902. var offset = 4 + parseAdaptionField(packet);
  42903. if (pusi) {
  42904. offset += packet[offset] + 1;
  42905. }
  42906. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  42907. };
  42908. var parsePmt = function (packet) {
  42909. var programMapTable = {};
  42910. var pusi = parsePayloadUnitStartIndicator(packet);
  42911. var payloadOffset = 4 + parseAdaptionField(packet);
  42912. if (pusi) {
  42913. payloadOffset += packet[payloadOffset] + 1;
  42914. } // PMTs can be sent ahead of the time when they should actually
  42915. // take effect. We don't believe this should ever be the case
  42916. // for HLS but we'll ignore "forward" PMT declarations if we see
  42917. // them. Future PMT declarations have the current_next_indicator
  42918. // set to zero.
  42919. if (!(packet[payloadOffset + 5] & 0x01)) {
  42920. return;
  42921. }
  42922. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  42923. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  42924. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  42925. // long the program info descriptors are
  42926. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  42927. var offset = 12 + programInfoLength;
  42928. while (offset < tableEnd) {
  42929. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  42930. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  42931. // skip past the elementary stream descriptors, if present
  42932. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  42933. }
  42934. return programMapTable;
  42935. };
  42936. var parsePesType = function (packet, programMapTable) {
  42937. var pid = parsePid(packet);
  42938. var type = programMapTable[pid];
  42939. switch (type) {
  42940. case StreamTypes$1.H264_STREAM_TYPE:
  42941. return 'video';
  42942. case StreamTypes$1.ADTS_STREAM_TYPE:
  42943. return 'audio';
  42944. case StreamTypes$1.METADATA_STREAM_TYPE:
  42945. return 'timed-metadata';
  42946. default:
  42947. return null;
  42948. }
  42949. };
  42950. var parsePesTime = function (packet) {
  42951. var pusi = parsePayloadUnitStartIndicator(packet);
  42952. if (!pusi) {
  42953. return null;
  42954. }
  42955. var offset = 4 + parseAdaptionField(packet);
  42956. if (offset >= packet.byteLength) {
  42957. // From the H 222.0 MPEG-TS spec
  42958. // "For transport stream packets carrying PES packets, stuffing is needed when there
  42959. // is insufficient PES packet data to completely fill the transport stream packet
  42960. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  42961. // the sum of the lengths of the data elements in it, so that the payload bytes
  42962. // remaining after the adaptation field exactly accommodates the available PES packet
  42963. // data."
  42964. //
  42965. // If the offset is >= the length of the packet, then the packet contains no data
  42966. // and instead is just adaption field stuffing bytes
  42967. return null;
  42968. }
  42969. var pes = null;
  42970. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  42971. // and a DTS value. Determine what combination of values is
  42972. // available to work with.
  42973. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  42974. // performs all bitwise operations on 32-bit integers but javascript
  42975. // supports a much greater range (52-bits) of integer using standard
  42976. // mathematical operations.
  42977. // We construct a 31-bit value using bitwise operators over the 31
  42978. // most significant bits and then multiply by 4 (equal to a left-shift
  42979. // of 2) before we add the final 2 least significant bits of the
  42980. // timestamp (equal to an OR.)
  42981. if (ptsDtsFlags & 0xC0) {
  42982. pes = {}; // the PTS and DTS are not written out directly. For information
  42983. // on how they are encoded, see
  42984. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  42985. 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;
  42986. pes.pts *= 4; // Left shift by 2
  42987. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  42988. pes.dts = pes.pts;
  42989. if (ptsDtsFlags & 0x40) {
  42990. 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;
  42991. pes.dts *= 4; // Left shift by 2
  42992. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  42993. }
  42994. }
  42995. return pes;
  42996. };
  42997. var parseNalUnitType = function (type) {
  42998. switch (type) {
  42999. case 0x05:
  43000. return 'slice_layer_without_partitioning_rbsp_idr';
  43001. case 0x06:
  43002. return 'sei_rbsp';
  43003. case 0x07:
  43004. return 'seq_parameter_set_rbsp';
  43005. case 0x08:
  43006. return 'pic_parameter_set_rbsp';
  43007. case 0x09:
  43008. return 'access_unit_delimiter_rbsp';
  43009. default:
  43010. return null;
  43011. }
  43012. };
  43013. var videoPacketContainsKeyFrame = function (packet) {
  43014. var offset = 4 + parseAdaptionField(packet);
  43015. var frameBuffer = packet.subarray(offset);
  43016. var frameI = 0;
  43017. var frameSyncPoint = 0;
  43018. var foundKeyFrame = false;
  43019. var nalType; // advance the sync point to a NAL start, if necessary
  43020. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  43021. if (frameBuffer[frameSyncPoint + 2] === 1) {
  43022. // the sync point is properly aligned
  43023. frameI = frameSyncPoint + 5;
  43024. break;
  43025. }
  43026. }
  43027. while (frameI < frameBuffer.byteLength) {
  43028. // look at the current byte to determine if we've hit the end of
  43029. // a NAL unit boundary
  43030. switch (frameBuffer[frameI]) {
  43031. case 0:
  43032. // skip past non-sync sequences
  43033. if (frameBuffer[frameI - 1] !== 0) {
  43034. frameI += 2;
  43035. break;
  43036. } else if (frameBuffer[frameI - 2] !== 0) {
  43037. frameI++;
  43038. break;
  43039. }
  43040. if (frameSyncPoint + 3 !== frameI - 2) {
  43041. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  43042. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  43043. foundKeyFrame = true;
  43044. }
  43045. } // drop trailing zeroes
  43046. do {
  43047. frameI++;
  43048. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  43049. frameSyncPoint = frameI - 2;
  43050. frameI += 3;
  43051. break;
  43052. case 1:
  43053. // skip past non-sync sequences
  43054. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  43055. frameI += 3;
  43056. break;
  43057. }
  43058. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  43059. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  43060. foundKeyFrame = true;
  43061. }
  43062. frameSyncPoint = frameI - 2;
  43063. frameI += 3;
  43064. break;
  43065. default:
  43066. // the current byte isn't a one or zero, so it cannot be part
  43067. // of a sync sequence
  43068. frameI += 3;
  43069. break;
  43070. }
  43071. }
  43072. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  43073. frameI -= frameSyncPoint;
  43074. frameSyncPoint = 0; // parse the final nal
  43075. if (frameBuffer && frameBuffer.byteLength > 3) {
  43076. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  43077. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  43078. foundKeyFrame = true;
  43079. }
  43080. }
  43081. return foundKeyFrame;
  43082. };
  43083. var probe$1 = {
  43084. parseType: parseType,
  43085. parsePat: parsePat,
  43086. parsePmt: parsePmt,
  43087. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  43088. parsePesType: parsePesType,
  43089. parsePesTime: parsePesTime,
  43090. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  43091. };
  43092. /**
  43093. * mux.js
  43094. *
  43095. * Copyright (c) Brightcove
  43096. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  43097. *
  43098. * Parse mpeg2 transport stream packets to extract basic timing information
  43099. */
  43100. var StreamTypes = streamTypes;
  43101. var handleRollover = timestampRolloverStream.handleRollover;
  43102. var probe = {};
  43103. probe.ts = probe$1;
  43104. probe.aac = utils;
  43105. var ONE_SECOND_IN_TS = clock$2.ONE_SECOND_IN_TS;
  43106. var MP2T_PACKET_LENGTH = 188,
  43107. // bytes
  43108. SYNC_BYTE = 0x47;
  43109. /**
  43110. * walks through segment data looking for pat and pmt packets to parse out
  43111. * program map table information
  43112. */
  43113. var parsePsi_ = function (bytes, pmt) {
  43114. var startIndex = 0,
  43115. endIndex = MP2T_PACKET_LENGTH,
  43116. packet,
  43117. type;
  43118. while (endIndex < bytes.byteLength) {
  43119. // Look for a pair of start and end sync bytes in the data..
  43120. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  43121. // We found a packet
  43122. packet = bytes.subarray(startIndex, endIndex);
  43123. type = probe.ts.parseType(packet, pmt.pid);
  43124. switch (type) {
  43125. case 'pat':
  43126. pmt.pid = probe.ts.parsePat(packet);
  43127. break;
  43128. case 'pmt':
  43129. var table = probe.ts.parsePmt(packet);
  43130. pmt.table = pmt.table || {};
  43131. Object.keys(table).forEach(function (key) {
  43132. pmt.table[key] = table[key];
  43133. });
  43134. break;
  43135. }
  43136. startIndex += MP2T_PACKET_LENGTH;
  43137. endIndex += MP2T_PACKET_LENGTH;
  43138. continue;
  43139. } // If we get here, we have somehow become de-synchronized and we need to step
  43140. // forward one byte at a time until we find a pair of sync bytes that denote
  43141. // a packet
  43142. startIndex++;
  43143. endIndex++;
  43144. }
  43145. };
  43146. /**
  43147. * walks through the segment data from the start and end to get timing information
  43148. * for the first and last audio pes packets
  43149. */
  43150. var parseAudioPes_ = function (bytes, pmt, result) {
  43151. var startIndex = 0,
  43152. endIndex = MP2T_PACKET_LENGTH,
  43153. packet,
  43154. type,
  43155. pesType,
  43156. pusi,
  43157. parsed;
  43158. var endLoop = false; // Start walking from start of segment to get first audio packet
  43159. while (endIndex <= bytes.byteLength) {
  43160. // Look for a pair of start and end sync bytes in the data..
  43161. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  43162. // We found a packet
  43163. packet = bytes.subarray(startIndex, endIndex);
  43164. type = probe.ts.parseType(packet, pmt.pid);
  43165. switch (type) {
  43166. case 'pes':
  43167. pesType = probe.ts.parsePesType(packet, pmt.table);
  43168. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  43169. if (pesType === 'audio' && pusi) {
  43170. parsed = probe.ts.parsePesTime(packet);
  43171. if (parsed) {
  43172. parsed.type = 'audio';
  43173. result.audio.push(parsed);
  43174. endLoop = true;
  43175. }
  43176. }
  43177. break;
  43178. }
  43179. if (endLoop) {
  43180. break;
  43181. }
  43182. startIndex += MP2T_PACKET_LENGTH;
  43183. endIndex += MP2T_PACKET_LENGTH;
  43184. continue;
  43185. } // If we get here, we have somehow become de-synchronized and we need to step
  43186. // forward one byte at a time until we find a pair of sync bytes that denote
  43187. // a packet
  43188. startIndex++;
  43189. endIndex++;
  43190. } // Start walking from end of segment to get last audio packet
  43191. endIndex = bytes.byteLength;
  43192. startIndex = endIndex - MP2T_PACKET_LENGTH;
  43193. endLoop = false;
  43194. while (startIndex >= 0) {
  43195. // Look for a pair of start and end sync bytes in the data..
  43196. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  43197. // We found a packet
  43198. packet = bytes.subarray(startIndex, endIndex);
  43199. type = probe.ts.parseType(packet, pmt.pid);
  43200. switch (type) {
  43201. case 'pes':
  43202. pesType = probe.ts.parsePesType(packet, pmt.table);
  43203. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  43204. if (pesType === 'audio' && pusi) {
  43205. parsed = probe.ts.parsePesTime(packet);
  43206. if (parsed) {
  43207. parsed.type = 'audio';
  43208. result.audio.push(parsed);
  43209. endLoop = true;
  43210. }
  43211. }
  43212. break;
  43213. }
  43214. if (endLoop) {
  43215. break;
  43216. }
  43217. startIndex -= MP2T_PACKET_LENGTH;
  43218. endIndex -= MP2T_PACKET_LENGTH;
  43219. continue;
  43220. } // If we get here, we have somehow become de-synchronized and we need to step
  43221. // forward one byte at a time until we find a pair of sync bytes that denote
  43222. // a packet
  43223. startIndex--;
  43224. endIndex--;
  43225. }
  43226. };
  43227. /**
  43228. * walks through the segment data from the start and end to get timing information
  43229. * for the first and last video pes packets as well as timing information for the first
  43230. * key frame.
  43231. */
  43232. var parseVideoPes_ = function (bytes, pmt, result) {
  43233. var startIndex = 0,
  43234. endIndex = MP2T_PACKET_LENGTH,
  43235. packet,
  43236. type,
  43237. pesType,
  43238. pusi,
  43239. parsed,
  43240. frame,
  43241. i,
  43242. pes;
  43243. var endLoop = false;
  43244. var currentFrame = {
  43245. data: [],
  43246. size: 0
  43247. }; // Start walking from start of segment to get first video packet
  43248. while (endIndex < bytes.byteLength) {
  43249. // Look for a pair of start and end sync bytes in the data..
  43250. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  43251. // We found a packet
  43252. packet = bytes.subarray(startIndex, endIndex);
  43253. type = probe.ts.parseType(packet, pmt.pid);
  43254. switch (type) {
  43255. case 'pes':
  43256. pesType = probe.ts.parsePesType(packet, pmt.table);
  43257. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  43258. if (pesType === 'video') {
  43259. if (pusi && !endLoop) {
  43260. parsed = probe.ts.parsePesTime(packet);
  43261. if (parsed) {
  43262. parsed.type = 'video';
  43263. result.video.push(parsed);
  43264. endLoop = true;
  43265. }
  43266. }
  43267. if (!result.firstKeyFrame) {
  43268. if (pusi) {
  43269. if (currentFrame.size !== 0) {
  43270. frame = new Uint8Array(currentFrame.size);
  43271. i = 0;
  43272. while (currentFrame.data.length) {
  43273. pes = currentFrame.data.shift();
  43274. frame.set(pes, i);
  43275. i += pes.byteLength;
  43276. }
  43277. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  43278. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  43279. // the keyframe seems to work fine with HLS playback
  43280. // and definitely preferable to a crash with TypeError...
  43281. if (firstKeyFrame) {
  43282. result.firstKeyFrame = firstKeyFrame;
  43283. result.firstKeyFrame.type = 'video';
  43284. } else {
  43285. // eslint-disable-next-line
  43286. 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.');
  43287. }
  43288. }
  43289. currentFrame.size = 0;
  43290. }
  43291. }
  43292. currentFrame.data.push(packet);
  43293. currentFrame.size += packet.byteLength;
  43294. }
  43295. }
  43296. break;
  43297. }
  43298. if (endLoop && result.firstKeyFrame) {
  43299. break;
  43300. }
  43301. startIndex += MP2T_PACKET_LENGTH;
  43302. endIndex += MP2T_PACKET_LENGTH;
  43303. continue;
  43304. } // If we get here, we have somehow become de-synchronized and we need to step
  43305. // forward one byte at a time until we find a pair of sync bytes that denote
  43306. // a packet
  43307. startIndex++;
  43308. endIndex++;
  43309. } // Start walking from end of segment to get last video packet
  43310. endIndex = bytes.byteLength;
  43311. startIndex = endIndex - MP2T_PACKET_LENGTH;
  43312. endLoop = false;
  43313. while (startIndex >= 0) {
  43314. // Look for a pair of start and end sync bytes in the data..
  43315. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  43316. // We found a packet
  43317. packet = bytes.subarray(startIndex, endIndex);
  43318. type = probe.ts.parseType(packet, pmt.pid);
  43319. switch (type) {
  43320. case 'pes':
  43321. pesType = probe.ts.parsePesType(packet, pmt.table);
  43322. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  43323. if (pesType === 'video' && pusi) {
  43324. parsed = probe.ts.parsePesTime(packet);
  43325. if (parsed) {
  43326. parsed.type = 'video';
  43327. result.video.push(parsed);
  43328. endLoop = true;
  43329. }
  43330. }
  43331. break;
  43332. }
  43333. if (endLoop) {
  43334. break;
  43335. }
  43336. startIndex -= MP2T_PACKET_LENGTH;
  43337. endIndex -= MP2T_PACKET_LENGTH;
  43338. continue;
  43339. } // If we get here, we have somehow become de-synchronized and we need to step
  43340. // forward one byte at a time until we find a pair of sync bytes that denote
  43341. // a packet
  43342. startIndex--;
  43343. endIndex--;
  43344. }
  43345. };
  43346. /**
  43347. * Adjusts the timestamp information for the segment to account for
  43348. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  43349. */
  43350. var adjustTimestamp_ = function (segmentInfo, baseTimestamp) {
  43351. if (segmentInfo.audio && segmentInfo.audio.length) {
  43352. var audioBaseTimestamp = baseTimestamp;
  43353. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  43354. audioBaseTimestamp = segmentInfo.audio[0].dts;
  43355. }
  43356. segmentInfo.audio.forEach(function (info) {
  43357. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  43358. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  43359. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  43360. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  43361. });
  43362. }
  43363. if (segmentInfo.video && segmentInfo.video.length) {
  43364. var videoBaseTimestamp = baseTimestamp;
  43365. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  43366. videoBaseTimestamp = segmentInfo.video[0].dts;
  43367. }
  43368. segmentInfo.video.forEach(function (info) {
  43369. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  43370. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  43371. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  43372. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  43373. });
  43374. if (segmentInfo.firstKeyFrame) {
  43375. var frame = segmentInfo.firstKeyFrame;
  43376. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  43377. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  43378. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  43379. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  43380. }
  43381. }
  43382. };
  43383. /**
  43384. * inspects the aac data stream for start and end time information
  43385. */
  43386. var inspectAac_ = function (bytes) {
  43387. var endLoop = false,
  43388. audioCount = 0,
  43389. sampleRate = null,
  43390. timestamp = null,
  43391. frameSize = 0,
  43392. byteIndex = 0,
  43393. packet;
  43394. while (bytes.length - byteIndex >= 3) {
  43395. var type = probe.aac.parseType(bytes, byteIndex);
  43396. switch (type) {
  43397. case 'timed-metadata':
  43398. // Exit early because we don't have enough to parse
  43399. // the ID3 tag header
  43400. if (bytes.length - byteIndex < 10) {
  43401. endLoop = true;
  43402. break;
  43403. }
  43404. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  43405. // to emit a full packet
  43406. if (frameSize > bytes.length) {
  43407. endLoop = true;
  43408. break;
  43409. }
  43410. if (timestamp === null) {
  43411. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  43412. timestamp = probe.aac.parseAacTimestamp(packet);
  43413. }
  43414. byteIndex += frameSize;
  43415. break;
  43416. case 'audio':
  43417. // Exit early because we don't have enough to parse
  43418. // the ADTS frame header
  43419. if (bytes.length - byteIndex < 7) {
  43420. endLoop = true;
  43421. break;
  43422. }
  43423. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  43424. // to emit a full packet
  43425. if (frameSize > bytes.length) {
  43426. endLoop = true;
  43427. break;
  43428. }
  43429. if (sampleRate === null) {
  43430. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  43431. sampleRate = probe.aac.parseSampleRate(packet);
  43432. }
  43433. audioCount++;
  43434. byteIndex += frameSize;
  43435. break;
  43436. default:
  43437. byteIndex++;
  43438. break;
  43439. }
  43440. if (endLoop) {
  43441. return null;
  43442. }
  43443. }
  43444. if (sampleRate === null || timestamp === null) {
  43445. return null;
  43446. }
  43447. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  43448. var result = {
  43449. audio: [{
  43450. type: 'audio',
  43451. dts: timestamp,
  43452. pts: timestamp
  43453. }, {
  43454. type: 'audio',
  43455. dts: timestamp + audioCount * 1024 * audioTimescale,
  43456. pts: timestamp + audioCount * 1024 * audioTimescale
  43457. }]
  43458. };
  43459. return result;
  43460. };
  43461. /**
  43462. * inspects the transport stream segment data for start and end time information
  43463. * of the audio and video tracks (when present) as well as the first key frame's
  43464. * start time.
  43465. */
  43466. var inspectTs_ = function (bytes) {
  43467. var pmt = {
  43468. pid: null,
  43469. table: null
  43470. };
  43471. var result = {};
  43472. parsePsi_(bytes, pmt);
  43473. for (var pid in pmt.table) {
  43474. if (pmt.table.hasOwnProperty(pid)) {
  43475. var type = pmt.table[pid];
  43476. switch (type) {
  43477. case StreamTypes.H264_STREAM_TYPE:
  43478. result.video = [];
  43479. parseVideoPes_(bytes, pmt, result);
  43480. if (result.video.length === 0) {
  43481. delete result.video;
  43482. }
  43483. break;
  43484. case StreamTypes.ADTS_STREAM_TYPE:
  43485. result.audio = [];
  43486. parseAudioPes_(bytes, pmt, result);
  43487. if (result.audio.length === 0) {
  43488. delete result.audio;
  43489. }
  43490. break;
  43491. }
  43492. }
  43493. }
  43494. return result;
  43495. };
  43496. /**
  43497. * Inspects segment byte data and returns an object with start and end timing information
  43498. *
  43499. * @param {Uint8Array} bytes The segment byte data
  43500. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  43501. * timestamps for rollover. This value must be in 90khz clock.
  43502. * @return {Object} Object containing start and end frame timing info of segment.
  43503. */
  43504. var inspect = function (bytes, baseTimestamp) {
  43505. var isAacData = probe.aac.isLikelyAacData(bytes);
  43506. var result;
  43507. if (isAacData) {
  43508. result = inspectAac_(bytes);
  43509. } else {
  43510. result = inspectTs_(bytes);
  43511. }
  43512. if (!result || !result.audio && !result.video) {
  43513. return null;
  43514. }
  43515. adjustTimestamp_(result, baseTimestamp);
  43516. return result;
  43517. };
  43518. var tsInspector = {
  43519. inspect: inspect,
  43520. parseAudioPes_: parseAudioPes_
  43521. };
  43522. /* global self */
  43523. /**
  43524. * Re-emits transmuxer events by converting them into messages to the
  43525. * world outside the worker.
  43526. *
  43527. * @param {Object} transmuxer the transmuxer to wire events on
  43528. * @private
  43529. */
  43530. const wireTransmuxerEvents = function (self, transmuxer) {
  43531. transmuxer.on('data', function (segment) {
  43532. // transfer ownership of the underlying ArrayBuffer
  43533. // instead of doing a copy to save memory
  43534. // ArrayBuffers are transferable but generic TypedArrays are not
  43535. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  43536. const initArray = segment.initSegment;
  43537. segment.initSegment = {
  43538. data: initArray.buffer,
  43539. byteOffset: initArray.byteOffset,
  43540. byteLength: initArray.byteLength
  43541. };
  43542. const typedArray = segment.data;
  43543. segment.data = typedArray.buffer;
  43544. self.postMessage({
  43545. action: 'data',
  43546. segment,
  43547. byteOffset: typedArray.byteOffset,
  43548. byteLength: typedArray.byteLength
  43549. }, [segment.data]);
  43550. });
  43551. transmuxer.on('done', function (data) {
  43552. self.postMessage({
  43553. action: 'done'
  43554. });
  43555. });
  43556. transmuxer.on('gopInfo', function (gopInfo) {
  43557. self.postMessage({
  43558. action: 'gopInfo',
  43559. gopInfo
  43560. });
  43561. });
  43562. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  43563. const videoSegmentTimingInfo = {
  43564. start: {
  43565. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  43566. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  43567. },
  43568. end: {
  43569. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  43570. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  43571. },
  43572. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  43573. };
  43574. if (timingInfo.prependedContentDuration) {
  43575. videoSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  43576. }
  43577. self.postMessage({
  43578. action: 'videoSegmentTimingInfo',
  43579. videoSegmentTimingInfo
  43580. });
  43581. });
  43582. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  43583. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  43584. const audioSegmentTimingInfo = {
  43585. start: {
  43586. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  43587. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  43588. },
  43589. end: {
  43590. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  43591. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  43592. },
  43593. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  43594. };
  43595. if (timingInfo.prependedContentDuration) {
  43596. audioSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  43597. }
  43598. self.postMessage({
  43599. action: 'audioSegmentTimingInfo',
  43600. audioSegmentTimingInfo
  43601. });
  43602. });
  43603. transmuxer.on('id3Frame', function (id3Frame) {
  43604. self.postMessage({
  43605. action: 'id3Frame',
  43606. id3Frame
  43607. });
  43608. });
  43609. transmuxer.on('caption', function (caption) {
  43610. self.postMessage({
  43611. action: 'caption',
  43612. caption
  43613. });
  43614. });
  43615. transmuxer.on('trackinfo', function (trackInfo) {
  43616. self.postMessage({
  43617. action: 'trackinfo',
  43618. trackInfo
  43619. });
  43620. });
  43621. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  43622. // convert to video TS since we prioritize video time over audio
  43623. self.postMessage({
  43624. action: 'audioTimingInfo',
  43625. audioTimingInfo: {
  43626. start: clock$2.videoTsToSeconds(audioTimingInfo.start),
  43627. end: clock$2.videoTsToSeconds(audioTimingInfo.end)
  43628. }
  43629. });
  43630. });
  43631. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  43632. self.postMessage({
  43633. action: 'videoTimingInfo',
  43634. videoTimingInfo: {
  43635. start: clock$2.videoTsToSeconds(videoTimingInfo.start),
  43636. end: clock$2.videoTsToSeconds(videoTimingInfo.end)
  43637. }
  43638. });
  43639. });
  43640. transmuxer.on('log', function (log) {
  43641. self.postMessage({
  43642. action: 'log',
  43643. log
  43644. });
  43645. });
  43646. };
  43647. /**
  43648. * All incoming messages route through this hash. If no function exists
  43649. * to handle an incoming message, then we ignore the message.
  43650. *
  43651. * @class MessageHandlers
  43652. * @param {Object} options the options to initialize with
  43653. */
  43654. class MessageHandlers {
  43655. constructor(self, options) {
  43656. this.options = options || {};
  43657. this.self = self;
  43658. this.init();
  43659. }
  43660. /**
  43661. * initialize our web worker and wire all the events.
  43662. */
  43663. init() {
  43664. if (this.transmuxer) {
  43665. this.transmuxer.dispose();
  43666. }
  43667. this.transmuxer = new transmuxer.Transmuxer(this.options);
  43668. wireTransmuxerEvents(this.self, this.transmuxer);
  43669. }
  43670. pushMp4Captions(data) {
  43671. if (!this.captionParser) {
  43672. this.captionParser = new captionParser();
  43673. this.captionParser.init();
  43674. }
  43675. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  43676. const parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  43677. this.self.postMessage({
  43678. action: 'mp4Captions',
  43679. captions: parsed && parsed.captions || [],
  43680. logs: parsed && parsed.logs || [],
  43681. data: segment.buffer
  43682. }, [segment.buffer]);
  43683. }
  43684. probeMp4StartTime({
  43685. timescales,
  43686. data
  43687. }) {
  43688. const startTime = probe$2.startTime(timescales, data);
  43689. this.self.postMessage({
  43690. action: 'probeMp4StartTime',
  43691. startTime,
  43692. data
  43693. }, [data.buffer]);
  43694. }
  43695. probeMp4Tracks({
  43696. data
  43697. }) {
  43698. const tracks = probe$2.tracks(data);
  43699. this.self.postMessage({
  43700. action: 'probeMp4Tracks',
  43701. tracks,
  43702. data
  43703. }, [data.buffer]);
  43704. }
  43705. /**
  43706. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  43707. * internal "media time," as well as whether it contains video and/or audio.
  43708. *
  43709. * @private
  43710. * @param {Uint8Array} bytes - segment bytes
  43711. * @param {number} baseStartTime
  43712. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  43713. * This value should be in seconds, as it's converted to a 90khz clock within the
  43714. * function body.
  43715. * @return {Object} The start time of the current segment in "media time" as well as
  43716. * whether it contains video and/or audio
  43717. */
  43718. probeTs({
  43719. data,
  43720. baseStartTime
  43721. }) {
  43722. const tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock$2.ONE_SECOND_IN_TS : void 0;
  43723. const timeInfo = tsInspector.inspect(data, tsStartTime);
  43724. let result = null;
  43725. if (timeInfo) {
  43726. result = {
  43727. // each type's time info comes back as an array of 2 times, start and end
  43728. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  43729. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  43730. };
  43731. if (result.hasVideo) {
  43732. result.videoStart = timeInfo.video[0].ptsTime;
  43733. }
  43734. if (result.hasAudio) {
  43735. result.audioStart = timeInfo.audio[0].ptsTime;
  43736. }
  43737. }
  43738. this.self.postMessage({
  43739. action: 'probeTs',
  43740. result,
  43741. data
  43742. }, [data.buffer]);
  43743. }
  43744. clearAllMp4Captions() {
  43745. if (this.captionParser) {
  43746. this.captionParser.clearAllCaptions();
  43747. }
  43748. }
  43749. clearParsedMp4Captions() {
  43750. if (this.captionParser) {
  43751. this.captionParser.clearParsedCaptions();
  43752. }
  43753. }
  43754. /**
  43755. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  43756. * processing.
  43757. *
  43758. * @param {ArrayBuffer} data data to push into the muxer
  43759. */
  43760. push(data) {
  43761. // Cast array buffer to correct type for transmuxer
  43762. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  43763. this.transmuxer.push(segment);
  43764. }
  43765. /**
  43766. * Recreate the transmuxer so that the next segment added via `push`
  43767. * start with a fresh transmuxer.
  43768. */
  43769. reset() {
  43770. this.transmuxer.reset();
  43771. }
  43772. /**
  43773. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  43774. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  43775. * set relative to the first based on the PTS values.
  43776. *
  43777. * @param {Object} data used to set the timestamp offset in the muxer
  43778. */
  43779. setTimestampOffset(data) {
  43780. const timestampOffset = data.timestampOffset || 0;
  43781. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock$2.secondsToVideoTs(timestampOffset)));
  43782. }
  43783. setAudioAppendStart(data) {
  43784. this.transmuxer.setAudioAppendStart(Math.ceil(clock$2.secondsToVideoTs(data.appendStart)));
  43785. }
  43786. setRemux(data) {
  43787. this.transmuxer.setRemux(data.remux);
  43788. }
  43789. /**
  43790. * Forces the pipeline to finish processing the last segment and emit it's
  43791. * results.
  43792. *
  43793. * @param {Object} data event data, not really used
  43794. */
  43795. flush(data) {
  43796. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  43797. self.postMessage({
  43798. action: 'done',
  43799. type: 'transmuxed'
  43800. });
  43801. }
  43802. endTimeline() {
  43803. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  43804. // timelines
  43805. self.postMessage({
  43806. action: 'endedtimeline',
  43807. type: 'transmuxed'
  43808. });
  43809. }
  43810. alignGopsWith(data) {
  43811. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  43812. }
  43813. }
  43814. /**
  43815. * Our web worker interface so that things can talk to mux.js
  43816. * that will be running in a web worker. the scope is passed to this by
  43817. * webworkify.
  43818. *
  43819. * @param {Object} self the scope for the web worker
  43820. */
  43821. self.onmessage = function (event) {
  43822. if (event.data.action === 'init' && event.data.options) {
  43823. this.messageHandlers = new MessageHandlers(self, event.data.options);
  43824. return;
  43825. }
  43826. if (!this.messageHandlers) {
  43827. this.messageHandlers = new MessageHandlers(self);
  43828. }
  43829. if (event.data && event.data.action && event.data.action !== 'init') {
  43830. if (this.messageHandlers[event.data.action]) {
  43831. this.messageHandlers[event.data.action](event.data);
  43832. }
  43833. }
  43834. };
  43835. }));
  43836. var TransmuxWorker = factory(workerCode$1);
  43837. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  43838. const handleData_ = (event, transmuxedData, callback) => {
  43839. const {
  43840. type,
  43841. initSegment,
  43842. captions,
  43843. captionStreams,
  43844. metadata,
  43845. videoFrameDtsTime,
  43846. videoFramePtsTime
  43847. } = event.data.segment;
  43848. transmuxedData.buffer.push({
  43849. captions,
  43850. captionStreams,
  43851. metadata
  43852. });
  43853. const boxes = event.data.segment.boxes || {
  43854. data: event.data.segment.data
  43855. };
  43856. const result = {
  43857. type,
  43858. // cast ArrayBuffer to TypedArray
  43859. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  43860. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  43861. };
  43862. if (typeof videoFrameDtsTime !== 'undefined') {
  43863. result.videoFrameDtsTime = videoFrameDtsTime;
  43864. }
  43865. if (typeof videoFramePtsTime !== 'undefined') {
  43866. result.videoFramePtsTime = videoFramePtsTime;
  43867. }
  43868. callback(result);
  43869. };
  43870. const handleDone_ = ({
  43871. transmuxedData,
  43872. callback
  43873. }) => {
  43874. // Previously we only returned data on data events,
  43875. // not on done events. Clear out the buffer to keep that consistent.
  43876. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  43877. // have received
  43878. callback(transmuxedData);
  43879. };
  43880. const handleGopInfo_ = (event, transmuxedData) => {
  43881. transmuxedData.gopInfo = event.data.gopInfo;
  43882. };
  43883. const processTransmux = options => {
  43884. const {
  43885. transmuxer,
  43886. bytes,
  43887. audioAppendStart,
  43888. gopsToAlignWith,
  43889. remux,
  43890. onData,
  43891. onTrackInfo,
  43892. onAudioTimingInfo,
  43893. onVideoTimingInfo,
  43894. onVideoSegmentTimingInfo,
  43895. onAudioSegmentTimingInfo,
  43896. onId3,
  43897. onCaptions,
  43898. onDone,
  43899. onEndedTimeline,
  43900. onTransmuxerLog,
  43901. isEndOfTimeline
  43902. } = options;
  43903. const transmuxedData = {
  43904. buffer: []
  43905. };
  43906. let waitForEndedTimelineEvent = isEndOfTimeline;
  43907. const handleMessage = event => {
  43908. if (transmuxer.currentTransmux !== options) {
  43909. // disposed
  43910. return;
  43911. }
  43912. if (event.data.action === 'data') {
  43913. handleData_(event, transmuxedData, onData);
  43914. }
  43915. if (event.data.action === 'trackinfo') {
  43916. onTrackInfo(event.data.trackInfo);
  43917. }
  43918. if (event.data.action === 'gopInfo') {
  43919. handleGopInfo_(event, transmuxedData);
  43920. }
  43921. if (event.data.action === 'audioTimingInfo') {
  43922. onAudioTimingInfo(event.data.audioTimingInfo);
  43923. }
  43924. if (event.data.action === 'videoTimingInfo') {
  43925. onVideoTimingInfo(event.data.videoTimingInfo);
  43926. }
  43927. if (event.data.action === 'videoSegmentTimingInfo') {
  43928. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  43929. }
  43930. if (event.data.action === 'audioSegmentTimingInfo') {
  43931. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  43932. }
  43933. if (event.data.action === 'id3Frame') {
  43934. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  43935. }
  43936. if (event.data.action === 'caption') {
  43937. onCaptions(event.data.caption);
  43938. }
  43939. if (event.data.action === 'endedtimeline') {
  43940. waitForEndedTimelineEvent = false;
  43941. onEndedTimeline();
  43942. }
  43943. if (event.data.action === 'log') {
  43944. onTransmuxerLog(event.data.log);
  43945. } // wait for the transmuxed event since we may have audio and video
  43946. if (event.data.type !== 'transmuxed') {
  43947. return;
  43948. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  43949. // of a timeline, that means there may still be data events before the segment
  43950. // processing can be considerred complete. In that case, the final event should be
  43951. // an "endedtimeline" event with the type "transmuxed."
  43952. if (waitForEndedTimelineEvent) {
  43953. return;
  43954. }
  43955. transmuxer.onmessage = null;
  43956. handleDone_({
  43957. transmuxedData,
  43958. callback: onDone
  43959. });
  43960. /* eslint-disable no-use-before-define */
  43961. dequeue(transmuxer);
  43962. /* eslint-enable */
  43963. };
  43964. transmuxer.onmessage = handleMessage;
  43965. if (audioAppendStart) {
  43966. transmuxer.postMessage({
  43967. action: 'setAudioAppendStart',
  43968. appendStart: audioAppendStart
  43969. });
  43970. } // allow empty arrays to be passed to clear out GOPs
  43971. if (Array.isArray(gopsToAlignWith)) {
  43972. transmuxer.postMessage({
  43973. action: 'alignGopsWith',
  43974. gopsToAlignWith
  43975. });
  43976. }
  43977. if (typeof remux !== 'undefined') {
  43978. transmuxer.postMessage({
  43979. action: 'setRemux',
  43980. remux
  43981. });
  43982. }
  43983. if (bytes.byteLength) {
  43984. const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  43985. const byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  43986. transmuxer.postMessage({
  43987. action: 'push',
  43988. // Send the typed-array of data as an ArrayBuffer so that
  43989. // it can be sent as a "Transferable" and avoid the costly
  43990. // memory copy
  43991. data: buffer,
  43992. // To recreate the original typed-array, we need information
  43993. // about what portion of the ArrayBuffer it was a view into
  43994. byteOffset,
  43995. byteLength: bytes.byteLength
  43996. }, [buffer]);
  43997. }
  43998. if (isEndOfTimeline) {
  43999. transmuxer.postMessage({
  44000. action: 'endTimeline'
  44001. });
  44002. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  44003. // the end of the segment
  44004. transmuxer.postMessage({
  44005. action: 'flush'
  44006. });
  44007. };
  44008. const dequeue = transmuxer => {
  44009. transmuxer.currentTransmux = null;
  44010. if (transmuxer.transmuxQueue.length) {
  44011. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  44012. if (typeof transmuxer.currentTransmux === 'function') {
  44013. transmuxer.currentTransmux();
  44014. } else {
  44015. processTransmux(transmuxer.currentTransmux);
  44016. }
  44017. }
  44018. };
  44019. const processAction = (transmuxer, action) => {
  44020. transmuxer.postMessage({
  44021. action
  44022. });
  44023. dequeue(transmuxer);
  44024. };
  44025. const enqueueAction = (action, transmuxer) => {
  44026. if (!transmuxer.currentTransmux) {
  44027. transmuxer.currentTransmux = action;
  44028. processAction(transmuxer, action);
  44029. return;
  44030. }
  44031. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  44032. };
  44033. const reset = transmuxer => {
  44034. enqueueAction('reset', transmuxer);
  44035. };
  44036. const endTimeline = transmuxer => {
  44037. enqueueAction('endTimeline', transmuxer);
  44038. };
  44039. const transmux = options => {
  44040. if (!options.transmuxer.currentTransmux) {
  44041. options.transmuxer.currentTransmux = options;
  44042. processTransmux(options);
  44043. return;
  44044. }
  44045. options.transmuxer.transmuxQueue.push(options);
  44046. };
  44047. const createTransmuxer = options => {
  44048. const transmuxer = new TransmuxWorker();
  44049. transmuxer.currentTransmux = null;
  44050. transmuxer.transmuxQueue = [];
  44051. const term = transmuxer.terminate;
  44052. transmuxer.terminate = () => {
  44053. transmuxer.currentTransmux = null;
  44054. transmuxer.transmuxQueue.length = 0;
  44055. return term.call(transmuxer);
  44056. };
  44057. transmuxer.postMessage({
  44058. action: 'init',
  44059. options
  44060. });
  44061. return transmuxer;
  44062. };
  44063. var segmentTransmuxer = {
  44064. reset,
  44065. endTimeline,
  44066. transmux,
  44067. createTransmuxer
  44068. };
  44069. const workerCallback = function (options) {
  44070. const transmuxer = options.transmuxer;
  44071. const endAction = options.endAction || options.action;
  44072. const callback = options.callback;
  44073. const message = _extends$1({}, options, {
  44074. endAction: null,
  44075. transmuxer: null,
  44076. callback: null
  44077. });
  44078. const listenForEndEvent = event => {
  44079. if (event.data.action !== endAction) {
  44080. return;
  44081. }
  44082. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  44083. if (event.data.data) {
  44084. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  44085. if (options.data) {
  44086. options.data = event.data.data;
  44087. }
  44088. }
  44089. callback(event.data);
  44090. };
  44091. transmuxer.addEventListener('message', listenForEndEvent);
  44092. if (options.data) {
  44093. const isArrayBuffer = options.data instanceof ArrayBuffer;
  44094. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  44095. message.byteLength = options.data.byteLength;
  44096. const transfers = [isArrayBuffer ? options.data : options.data.buffer];
  44097. transmuxer.postMessage(message, transfers);
  44098. } else {
  44099. transmuxer.postMessage(message);
  44100. }
  44101. };
  44102. const REQUEST_ERRORS = {
  44103. FAILURE: 2,
  44104. TIMEOUT: -101,
  44105. ABORTED: -102
  44106. };
  44107. /**
  44108. * Abort all requests
  44109. *
  44110. * @param {Object} activeXhrs - an object that tracks all XHR requests
  44111. */
  44112. const abortAll = activeXhrs => {
  44113. activeXhrs.forEach(xhr => {
  44114. xhr.abort();
  44115. });
  44116. };
  44117. /**
  44118. * Gather important bandwidth stats once a request has completed
  44119. *
  44120. * @param {Object} request - the XHR request from which to gather stats
  44121. */
  44122. const getRequestStats = request => {
  44123. return {
  44124. bandwidth: request.bandwidth,
  44125. bytesReceived: request.bytesReceived || 0,
  44126. roundTripTime: request.roundTripTime || 0
  44127. };
  44128. };
  44129. /**
  44130. * If possible gather bandwidth stats as a request is in
  44131. * progress
  44132. *
  44133. * @param {Event} progressEvent - an event object from an XHR's progress event
  44134. */
  44135. const getProgressStats = progressEvent => {
  44136. const request = progressEvent.target;
  44137. const roundTripTime = Date.now() - request.requestTime;
  44138. const stats = {
  44139. bandwidth: Infinity,
  44140. bytesReceived: 0,
  44141. roundTripTime: roundTripTime || 0
  44142. };
  44143. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  44144. // because we should only use bandwidth stats on progress to determine when
  44145. // abort a request early due to insufficient bandwidth
  44146. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  44147. return stats;
  44148. };
  44149. /**
  44150. * Handle all error conditions in one place and return an object
  44151. * with all the information
  44152. *
  44153. * @param {Error|null} error - if non-null signals an error occured with the XHR
  44154. * @param {Object} request - the XHR request that possibly generated the error
  44155. */
  44156. const handleErrors = (error, request) => {
  44157. if (request.timedout) {
  44158. return {
  44159. status: request.status,
  44160. message: 'HLS request timed-out at URL: ' + request.uri,
  44161. code: REQUEST_ERRORS.TIMEOUT,
  44162. xhr: request
  44163. };
  44164. }
  44165. if (request.aborted) {
  44166. return {
  44167. status: request.status,
  44168. message: 'HLS request aborted at URL: ' + request.uri,
  44169. code: REQUEST_ERRORS.ABORTED,
  44170. xhr: request
  44171. };
  44172. }
  44173. if (error) {
  44174. return {
  44175. status: request.status,
  44176. message: 'HLS request errored at URL: ' + request.uri,
  44177. code: REQUEST_ERRORS.FAILURE,
  44178. xhr: request
  44179. };
  44180. }
  44181. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  44182. return {
  44183. status: request.status,
  44184. message: 'Empty HLS response at URL: ' + request.uri,
  44185. code: REQUEST_ERRORS.FAILURE,
  44186. xhr: request
  44187. };
  44188. }
  44189. return null;
  44190. };
  44191. /**
  44192. * Handle responses for key data and convert the key data to the correct format
  44193. * for the decryption step later
  44194. *
  44195. * @param {Object} segment - a simplified copy of the segmentInfo object
  44196. * from SegmentLoader
  44197. * @param {Array} objects - objects to add the key bytes to.
  44198. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  44199. * this request
  44200. */
  44201. const handleKeyResponse = (segment, objects, finishProcessingFn) => (error, request) => {
  44202. const response = request.response;
  44203. const errorObj = handleErrors(error, request);
  44204. if (errorObj) {
  44205. return finishProcessingFn(errorObj, segment);
  44206. }
  44207. if (response.byteLength !== 16) {
  44208. return finishProcessingFn({
  44209. status: request.status,
  44210. message: 'Invalid HLS key at URL: ' + request.uri,
  44211. code: REQUEST_ERRORS.FAILURE,
  44212. xhr: request
  44213. }, segment);
  44214. }
  44215. const view = new DataView(response);
  44216. const bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  44217. for (let i = 0; i < objects.length; i++) {
  44218. objects[i].bytes = bytes;
  44219. }
  44220. return finishProcessingFn(null, segment);
  44221. };
  44222. const parseInitSegment = (segment, callback) => {
  44223. const type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  44224. // only know how to parse mp4 init segments at the moment
  44225. if (type !== 'mp4') {
  44226. const uri = segment.map.resolvedUri || segment.map.uri;
  44227. return callback({
  44228. internal: true,
  44229. message: `Found unsupported ${type || 'unknown'} container for initialization segment at URL: ${uri}`,
  44230. code: REQUEST_ERRORS.FAILURE
  44231. });
  44232. }
  44233. workerCallback({
  44234. action: 'probeMp4Tracks',
  44235. data: segment.map.bytes,
  44236. transmuxer: segment.transmuxer,
  44237. callback: ({
  44238. tracks,
  44239. data
  44240. }) => {
  44241. // transfer bytes back to us
  44242. segment.map.bytes = data;
  44243. tracks.forEach(function (track) {
  44244. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  44245. if (segment.map.tracks[track.type]) {
  44246. return;
  44247. }
  44248. segment.map.tracks[track.type] = track;
  44249. if (typeof track.id === 'number' && track.timescale) {
  44250. segment.map.timescales = segment.map.timescales || {};
  44251. segment.map.timescales[track.id] = track.timescale;
  44252. }
  44253. });
  44254. return callback(null);
  44255. }
  44256. });
  44257. };
  44258. /**
  44259. * Handle init-segment responses
  44260. *
  44261. * @param {Object} segment - a simplified copy of the segmentInfo object
  44262. * from SegmentLoader
  44263. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  44264. * this request
  44265. */
  44266. const handleInitSegmentResponse = ({
  44267. segment,
  44268. finishProcessingFn
  44269. }) => (error, request) => {
  44270. const errorObj = handleErrors(error, request);
  44271. if (errorObj) {
  44272. return finishProcessingFn(errorObj, segment);
  44273. }
  44274. const bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  44275. // until the key request is done to decrypt.
  44276. if (segment.map.key) {
  44277. segment.map.encryptedBytes = bytes;
  44278. return finishProcessingFn(null, segment);
  44279. }
  44280. segment.map.bytes = bytes;
  44281. parseInitSegment(segment, function (parseError) {
  44282. if (parseError) {
  44283. parseError.xhr = request;
  44284. parseError.status = request.status;
  44285. return finishProcessingFn(parseError, segment);
  44286. }
  44287. finishProcessingFn(null, segment);
  44288. });
  44289. };
  44290. /**
  44291. * Response handler for segment-requests being sure to set the correct
  44292. * property depending on whether the segment is encryped or not
  44293. * Also records and keeps track of stats that are used for ABR purposes
  44294. *
  44295. * @param {Object} segment - a simplified copy of the segmentInfo object
  44296. * from SegmentLoader
  44297. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  44298. * this request
  44299. */
  44300. const handleSegmentResponse = ({
  44301. segment,
  44302. finishProcessingFn,
  44303. responseType
  44304. }) => (error, request) => {
  44305. const errorObj = handleErrors(error, request);
  44306. if (errorObj) {
  44307. return finishProcessingFn(errorObj, segment);
  44308. }
  44309. const newBytes =
  44310. // although responseText "should" exist, this guard serves to prevent an error being
  44311. // thrown for two primary cases:
  44312. // 1. the mime type override stops working, or is not implemented for a specific
  44313. // browser
  44314. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  44315. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  44316. segment.stats = getRequestStats(request);
  44317. if (segment.key) {
  44318. segment.encryptedBytes = new Uint8Array(newBytes);
  44319. } else {
  44320. segment.bytes = new Uint8Array(newBytes);
  44321. }
  44322. return finishProcessingFn(null, segment);
  44323. };
  44324. const transmuxAndNotify = ({
  44325. segment,
  44326. bytes,
  44327. trackInfoFn,
  44328. timingInfoFn,
  44329. videoSegmentTimingInfoFn,
  44330. audioSegmentTimingInfoFn,
  44331. id3Fn,
  44332. captionsFn,
  44333. isEndOfTimeline,
  44334. endedTimelineFn,
  44335. dataFn,
  44336. doneFn,
  44337. onTransmuxerLog
  44338. }) => {
  44339. const fmp4Tracks = segment.map && segment.map.tracks || {};
  44340. const isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  44341. // One reason for this is that in the case of full segments, we want to trust start
  44342. // times from the probe, rather than the transmuxer.
  44343. let audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  44344. const audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  44345. let videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  44346. const videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  44347. const finish = () => transmux({
  44348. bytes,
  44349. transmuxer: segment.transmuxer,
  44350. audioAppendStart: segment.audioAppendStart,
  44351. gopsToAlignWith: segment.gopsToAlignWith,
  44352. remux: isMuxed,
  44353. onData: result => {
  44354. result.type = result.type === 'combined' ? 'video' : result.type;
  44355. dataFn(segment, result);
  44356. },
  44357. onTrackInfo: trackInfo => {
  44358. if (trackInfoFn) {
  44359. if (isMuxed) {
  44360. trackInfo.isMuxed = true;
  44361. }
  44362. trackInfoFn(segment, trackInfo);
  44363. }
  44364. },
  44365. onAudioTimingInfo: audioTimingInfo => {
  44366. // we only want the first start value we encounter
  44367. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  44368. audioStartFn(audioTimingInfo.start);
  44369. audioStartFn = null;
  44370. } // we want to continually update the end time
  44371. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  44372. audioEndFn(audioTimingInfo.end);
  44373. }
  44374. },
  44375. onVideoTimingInfo: videoTimingInfo => {
  44376. // we only want the first start value we encounter
  44377. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  44378. videoStartFn(videoTimingInfo.start);
  44379. videoStartFn = null;
  44380. } // we want to continually update the end time
  44381. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  44382. videoEndFn(videoTimingInfo.end);
  44383. }
  44384. },
  44385. onVideoSegmentTimingInfo: videoSegmentTimingInfo => {
  44386. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  44387. },
  44388. onAudioSegmentTimingInfo: audioSegmentTimingInfo => {
  44389. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  44390. },
  44391. onId3: (id3Frames, dispatchType) => {
  44392. id3Fn(segment, id3Frames, dispatchType);
  44393. },
  44394. onCaptions: captions => {
  44395. captionsFn(segment, [captions]);
  44396. },
  44397. isEndOfTimeline,
  44398. onEndedTimeline: () => {
  44399. endedTimelineFn();
  44400. },
  44401. onTransmuxerLog,
  44402. onDone: result => {
  44403. if (!doneFn) {
  44404. return;
  44405. }
  44406. result.type = result.type === 'combined' ? 'video' : result.type;
  44407. doneFn(null, segment, result);
  44408. }
  44409. }); // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  44410. // Meaning cached frame data may corrupt our notion of where this segment
  44411. // really starts. To get around this, probe for the info needed.
  44412. workerCallback({
  44413. action: 'probeTs',
  44414. transmuxer: segment.transmuxer,
  44415. data: bytes,
  44416. baseStartTime: segment.baseStartTime,
  44417. callback: data => {
  44418. segment.bytes = bytes = data.data;
  44419. const probeResult = data.result;
  44420. if (probeResult) {
  44421. trackInfoFn(segment, {
  44422. hasAudio: probeResult.hasAudio,
  44423. hasVideo: probeResult.hasVideo,
  44424. isMuxed
  44425. });
  44426. trackInfoFn = null;
  44427. if (probeResult.hasAudio && !isMuxed) {
  44428. audioStartFn(probeResult.audioStart);
  44429. }
  44430. if (probeResult.hasVideo) {
  44431. videoStartFn(probeResult.videoStart);
  44432. }
  44433. audioStartFn = null;
  44434. videoStartFn = null;
  44435. }
  44436. finish();
  44437. }
  44438. });
  44439. };
  44440. const handleSegmentBytes = ({
  44441. segment,
  44442. bytes,
  44443. trackInfoFn,
  44444. timingInfoFn,
  44445. videoSegmentTimingInfoFn,
  44446. audioSegmentTimingInfoFn,
  44447. id3Fn,
  44448. captionsFn,
  44449. isEndOfTimeline,
  44450. endedTimelineFn,
  44451. dataFn,
  44452. doneFn,
  44453. onTransmuxerLog
  44454. }) => {
  44455. let bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  44456. // We should have a handler that fetches the number of bytes required
  44457. // to check if something is fmp4. This will allow us to save bandwidth
  44458. // because we can only exclude a playlist and abort requests
  44459. // by codec after trackinfo triggers.
  44460. if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  44461. segment.isFmp4 = true;
  44462. const {
  44463. tracks
  44464. } = segment.map;
  44465. const trackInfo = {
  44466. isFmp4: true,
  44467. hasVideo: !!tracks.video,
  44468. hasAudio: !!tracks.audio
  44469. }; // if we have a audio track, with a codec that is not set to
  44470. // encrypted audio
  44471. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  44472. trackInfo.audioCodec = tracks.audio.codec;
  44473. } // if we have a video track, with a codec that is not set to
  44474. // encrypted video
  44475. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  44476. trackInfo.videoCodec = tracks.video.codec;
  44477. }
  44478. if (tracks.video && tracks.audio) {
  44479. trackInfo.isMuxed = true;
  44480. } // since we don't support appending fmp4 data on progress, we know we have the full
  44481. // segment here
  44482. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  44483. // time. The end time can be roughly calculated by the receiver using the duration.
  44484. //
  44485. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  44486. // that is the true start of the segment (where the playback engine should begin
  44487. // decoding).
  44488. const finishLoading = captions => {
  44489. // if the track still has audio at this point it is only possible
  44490. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  44491. // above.
  44492. // we make sure to use segment.bytes here as that
  44493. dataFn(segment, {
  44494. data: bytesAsUint8Array,
  44495. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  44496. });
  44497. if (captions && captions.length) {
  44498. captionsFn(segment, captions);
  44499. }
  44500. doneFn(null, segment, {});
  44501. };
  44502. workerCallback({
  44503. action: 'probeMp4StartTime',
  44504. timescales: segment.map.timescales,
  44505. data: bytesAsUint8Array,
  44506. transmuxer: segment.transmuxer,
  44507. callback: ({
  44508. data,
  44509. startTime
  44510. }) => {
  44511. // transfer bytes back to us
  44512. bytes = data.buffer;
  44513. segment.bytes = bytesAsUint8Array = data;
  44514. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  44515. timingInfoFn(segment, 'audio', 'start', startTime);
  44516. }
  44517. if (trackInfo.hasVideo) {
  44518. timingInfoFn(segment, 'video', 'start', startTime);
  44519. } // Run through the CaptionParser in case there are captions.
  44520. // Initialize CaptionParser if it hasn't been yet
  44521. if (!tracks.video || !data.byteLength || !segment.transmuxer) {
  44522. finishLoading();
  44523. return;
  44524. }
  44525. workerCallback({
  44526. action: 'pushMp4Captions',
  44527. endAction: 'mp4Captions',
  44528. transmuxer: segment.transmuxer,
  44529. data: bytesAsUint8Array,
  44530. timescales: segment.map.timescales,
  44531. trackIds: [tracks.video.id],
  44532. callback: message => {
  44533. // transfer bytes back to us
  44534. bytes = message.data.buffer;
  44535. segment.bytes = bytesAsUint8Array = message.data;
  44536. message.logs.forEach(function (log) {
  44537. onTransmuxerLog(merge(log, {
  44538. stream: 'mp4CaptionParser'
  44539. }));
  44540. });
  44541. finishLoading(message.captions);
  44542. }
  44543. });
  44544. }
  44545. });
  44546. return;
  44547. } // VTT or other segments that don't need processing
  44548. if (!segment.transmuxer) {
  44549. doneFn(null, segment, {});
  44550. return;
  44551. }
  44552. if (typeof segment.container === 'undefined') {
  44553. segment.container = detectContainerForBytes(bytesAsUint8Array);
  44554. }
  44555. if (segment.container !== 'ts' && segment.container !== 'aac') {
  44556. trackInfoFn(segment, {
  44557. hasAudio: false,
  44558. hasVideo: false
  44559. });
  44560. doneFn(null, segment, {});
  44561. return;
  44562. } // ts or aac
  44563. transmuxAndNotify({
  44564. segment,
  44565. bytes,
  44566. trackInfoFn,
  44567. timingInfoFn,
  44568. videoSegmentTimingInfoFn,
  44569. audioSegmentTimingInfoFn,
  44570. id3Fn,
  44571. captionsFn,
  44572. isEndOfTimeline,
  44573. endedTimelineFn,
  44574. dataFn,
  44575. doneFn,
  44576. onTransmuxerLog
  44577. });
  44578. };
  44579. const decrypt = function ({
  44580. id,
  44581. key,
  44582. encryptedBytes,
  44583. decryptionWorker
  44584. }, callback) {
  44585. const decryptionHandler = event => {
  44586. if (event.data.source === id) {
  44587. decryptionWorker.removeEventListener('message', decryptionHandler);
  44588. const decrypted = event.data.decrypted;
  44589. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  44590. }
  44591. };
  44592. decryptionWorker.addEventListener('message', decryptionHandler);
  44593. let keyBytes;
  44594. if (key.bytes.slice) {
  44595. keyBytes = key.bytes.slice();
  44596. } else {
  44597. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  44598. } // incrementally decrypt the bytes
  44599. decryptionWorker.postMessage(createTransferableMessage({
  44600. source: id,
  44601. encrypted: encryptedBytes,
  44602. key: keyBytes,
  44603. iv: key.iv
  44604. }), [encryptedBytes.buffer, keyBytes.buffer]);
  44605. };
  44606. /**
  44607. * Decrypt the segment via the decryption web worker
  44608. *
  44609. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  44610. * routines
  44611. * @param {Object} segment - a simplified copy of the segmentInfo object
  44612. * from SegmentLoader
  44613. * @param {Function} trackInfoFn - a callback that receives track info
  44614. * @param {Function} timingInfoFn - a callback that receives timing info
  44615. * @param {Function} videoSegmentTimingInfoFn
  44616. * a callback that receives video timing info based on media times and
  44617. * any adjustments made by the transmuxer
  44618. * @param {Function} audioSegmentTimingInfoFn
  44619. * a callback that receives audio timing info based on media times and
  44620. * any adjustments made by the transmuxer
  44621. * @param {boolean} isEndOfTimeline
  44622. * true if this segment represents the last segment in a timeline
  44623. * @param {Function} endedTimelineFn
  44624. * a callback made when a timeline is ended, will only be called if
  44625. * isEndOfTimeline is true
  44626. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  44627. * and ready to use
  44628. * @param {Function} doneFn - a callback that is executed after decryption has completed
  44629. */
  44630. const decryptSegment = ({
  44631. decryptionWorker,
  44632. segment,
  44633. trackInfoFn,
  44634. timingInfoFn,
  44635. videoSegmentTimingInfoFn,
  44636. audioSegmentTimingInfoFn,
  44637. id3Fn,
  44638. captionsFn,
  44639. isEndOfTimeline,
  44640. endedTimelineFn,
  44641. dataFn,
  44642. doneFn,
  44643. onTransmuxerLog
  44644. }) => {
  44645. decrypt({
  44646. id: segment.requestId,
  44647. key: segment.key,
  44648. encryptedBytes: segment.encryptedBytes,
  44649. decryptionWorker
  44650. }, decryptedBytes => {
  44651. segment.bytes = decryptedBytes;
  44652. handleSegmentBytes({
  44653. segment,
  44654. bytes: segment.bytes,
  44655. trackInfoFn,
  44656. timingInfoFn,
  44657. videoSegmentTimingInfoFn,
  44658. audioSegmentTimingInfoFn,
  44659. id3Fn,
  44660. captionsFn,
  44661. isEndOfTimeline,
  44662. endedTimelineFn,
  44663. dataFn,
  44664. doneFn,
  44665. onTransmuxerLog
  44666. });
  44667. });
  44668. };
  44669. /**
  44670. * This function waits for all XHRs to finish (with either success or failure)
  44671. * before continueing processing via it's callback. The function gathers errors
  44672. * from each request into a single errors array so that the error status for
  44673. * each request can be examined later.
  44674. *
  44675. * @param {Object} activeXhrs - an object that tracks all XHR requests
  44676. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  44677. * routines
  44678. * @param {Function} trackInfoFn - a callback that receives track info
  44679. * @param {Function} timingInfoFn - a callback that receives timing info
  44680. * @param {Function} videoSegmentTimingInfoFn
  44681. * a callback that receives video timing info based on media times and
  44682. * any adjustments made by the transmuxer
  44683. * @param {Function} audioSegmentTimingInfoFn
  44684. * a callback that receives audio timing info based on media times and
  44685. * any adjustments made by the transmuxer
  44686. * @param {Function} id3Fn - a callback that receives ID3 metadata
  44687. * @param {Function} captionsFn - a callback that receives captions
  44688. * @param {boolean} isEndOfTimeline
  44689. * true if this segment represents the last segment in a timeline
  44690. * @param {Function} endedTimelineFn
  44691. * a callback made when a timeline is ended, will only be called if
  44692. * isEndOfTimeline is true
  44693. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  44694. * and ready to use
  44695. * @param {Function} doneFn - a callback that is executed after all resources have been
  44696. * downloaded and any decryption completed
  44697. */
  44698. const waitForCompletion = ({
  44699. activeXhrs,
  44700. decryptionWorker,
  44701. trackInfoFn,
  44702. timingInfoFn,
  44703. videoSegmentTimingInfoFn,
  44704. audioSegmentTimingInfoFn,
  44705. id3Fn,
  44706. captionsFn,
  44707. isEndOfTimeline,
  44708. endedTimelineFn,
  44709. dataFn,
  44710. doneFn,
  44711. onTransmuxerLog
  44712. }) => {
  44713. let count = 0;
  44714. let didError = false;
  44715. return (error, segment) => {
  44716. if (didError) {
  44717. return;
  44718. }
  44719. if (error) {
  44720. didError = true; // If there are errors, we have to abort any outstanding requests
  44721. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  44722. // handle the aborted events from those requests, there are some cases where we may
  44723. // never get an aborted event. For instance, if the network connection is lost and
  44724. // there were two requests, the first may have triggered an error immediately, while
  44725. // the second request remains unsent. In that case, the aborted algorithm will not
  44726. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  44727. //
  44728. // We also can't rely on the ready state of the XHR, since the request that
  44729. // triggered the connection error may also show as a ready state of 0 (unsent).
  44730. // Therefore, we have to finish this group of requests immediately after the first
  44731. // seen error.
  44732. return doneFn(error, segment);
  44733. }
  44734. count += 1;
  44735. if (count === activeXhrs.length) {
  44736. const segmentFinish = function () {
  44737. if (segment.encryptedBytes) {
  44738. return decryptSegment({
  44739. decryptionWorker,
  44740. segment,
  44741. trackInfoFn,
  44742. timingInfoFn,
  44743. videoSegmentTimingInfoFn,
  44744. audioSegmentTimingInfoFn,
  44745. id3Fn,
  44746. captionsFn,
  44747. isEndOfTimeline,
  44748. endedTimelineFn,
  44749. dataFn,
  44750. doneFn,
  44751. onTransmuxerLog
  44752. });
  44753. } // Otherwise, everything is ready just continue
  44754. handleSegmentBytes({
  44755. segment,
  44756. bytes: segment.bytes,
  44757. trackInfoFn,
  44758. timingInfoFn,
  44759. videoSegmentTimingInfoFn,
  44760. audioSegmentTimingInfoFn,
  44761. id3Fn,
  44762. captionsFn,
  44763. isEndOfTimeline,
  44764. endedTimelineFn,
  44765. dataFn,
  44766. doneFn,
  44767. onTransmuxerLog
  44768. });
  44769. }; // Keep track of when *all* of the requests have completed
  44770. segment.endOfAllRequests = Date.now();
  44771. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  44772. return decrypt({
  44773. decryptionWorker,
  44774. // add -init to the "id" to differentiate between segment
  44775. // and init segment decryption, just in case they happen
  44776. // at the same time at some point in the future.
  44777. id: segment.requestId + '-init',
  44778. encryptedBytes: segment.map.encryptedBytes,
  44779. key: segment.map.key
  44780. }, decryptedBytes => {
  44781. segment.map.bytes = decryptedBytes;
  44782. parseInitSegment(segment, parseError => {
  44783. if (parseError) {
  44784. abortAll(activeXhrs);
  44785. return doneFn(parseError, segment);
  44786. }
  44787. segmentFinish();
  44788. });
  44789. });
  44790. }
  44791. segmentFinish();
  44792. }
  44793. };
  44794. };
  44795. /**
  44796. * Calls the abort callback if any request within the batch was aborted. Will only call
  44797. * the callback once per batch of requests, even if multiple were aborted.
  44798. *
  44799. * @param {Object} loadendState - state to check to see if the abort function was called
  44800. * @param {Function} abortFn - callback to call for abort
  44801. */
  44802. const handleLoadEnd = ({
  44803. loadendState,
  44804. abortFn
  44805. }) => event => {
  44806. const request = event.target;
  44807. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  44808. abortFn();
  44809. loadendState.calledAbortFn = true;
  44810. }
  44811. };
  44812. /**
  44813. * Simple progress event callback handler that gathers some stats before
  44814. * executing a provided callback with the `segment` object
  44815. *
  44816. * @param {Object} segment - a simplified copy of the segmentInfo object
  44817. * from SegmentLoader
  44818. * @param {Function} progressFn - a callback that is executed each time a progress event
  44819. * is received
  44820. * @param {Function} trackInfoFn - a callback that receives track info
  44821. * @param {Function} timingInfoFn - a callback that receives timing info
  44822. * @param {Function} videoSegmentTimingInfoFn
  44823. * a callback that receives video timing info based on media times and
  44824. * any adjustments made by the transmuxer
  44825. * @param {Function} audioSegmentTimingInfoFn
  44826. * a callback that receives audio timing info based on media times and
  44827. * any adjustments made by the transmuxer
  44828. * @param {boolean} isEndOfTimeline
  44829. * true if this segment represents the last segment in a timeline
  44830. * @param {Function} endedTimelineFn
  44831. * a callback made when a timeline is ended, will only be called if
  44832. * isEndOfTimeline is true
  44833. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  44834. * and ready to use
  44835. * @param {Event} event - the progress event object from XMLHttpRequest
  44836. */
  44837. const handleProgress = ({
  44838. segment,
  44839. progressFn,
  44840. trackInfoFn,
  44841. timingInfoFn,
  44842. videoSegmentTimingInfoFn,
  44843. audioSegmentTimingInfoFn,
  44844. id3Fn,
  44845. captionsFn,
  44846. isEndOfTimeline,
  44847. endedTimelineFn,
  44848. dataFn
  44849. }) => event => {
  44850. const request = event.target;
  44851. if (request.aborted) {
  44852. return;
  44853. }
  44854. segment.stats = merge(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  44855. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  44856. segment.stats.firstBytesReceivedAt = Date.now();
  44857. }
  44858. return progressFn(event, segment);
  44859. };
  44860. /**
  44861. * Load all resources and does any processing necessary for a media-segment
  44862. *
  44863. * Features:
  44864. * decrypts the media-segment if it has a key uri and an iv
  44865. * aborts *all* requests if *any* one request fails
  44866. *
  44867. * The segment object, at minimum, has the following format:
  44868. * {
  44869. * resolvedUri: String,
  44870. * [transmuxer]: Object,
  44871. * [byterange]: {
  44872. * offset: Number,
  44873. * length: Number
  44874. * },
  44875. * [key]: {
  44876. * resolvedUri: String
  44877. * [byterange]: {
  44878. * offset: Number,
  44879. * length: Number
  44880. * },
  44881. * iv: {
  44882. * bytes: Uint32Array
  44883. * }
  44884. * },
  44885. * [map]: {
  44886. * resolvedUri: String,
  44887. * [byterange]: {
  44888. * offset: Number,
  44889. * length: Number
  44890. * },
  44891. * [bytes]: Uint8Array
  44892. * }
  44893. * }
  44894. * ...where [name] denotes optional properties
  44895. *
  44896. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  44897. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  44898. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  44899. * decryption routines
  44900. * @param {Object} segment - a simplified copy of the segmentInfo object
  44901. * from SegmentLoader
  44902. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  44903. * aborted
  44904. * @param {Function} progressFn - a callback that receives progress events from the main
  44905. * segment's xhr request
  44906. * @param {Function} trackInfoFn - a callback that receives track info
  44907. * @param {Function} timingInfoFn - a callback that receives timing info
  44908. * @param {Function} videoSegmentTimingInfoFn
  44909. * a callback that receives video timing info based on media times and
  44910. * any adjustments made by the transmuxer
  44911. * @param {Function} audioSegmentTimingInfoFn
  44912. * a callback that receives audio timing info based on media times and
  44913. * any adjustments made by the transmuxer
  44914. * @param {Function} id3Fn - a callback that receives ID3 metadata
  44915. * @param {Function} captionsFn - a callback that receives captions
  44916. * @param {boolean} isEndOfTimeline
  44917. * true if this segment represents the last segment in a timeline
  44918. * @param {Function} endedTimelineFn
  44919. * a callback made when a timeline is ended, will only be called if
  44920. * isEndOfTimeline is true
  44921. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  44922. * request, transmuxed if needed
  44923. * @param {Function} doneFn - a callback that is executed only once all requests have
  44924. * succeeded or failed
  44925. * @return {Function} a function that, when invoked, immediately aborts all
  44926. * outstanding requests
  44927. */
  44928. const mediaSegmentRequest = ({
  44929. xhr,
  44930. xhrOptions,
  44931. decryptionWorker,
  44932. segment,
  44933. abortFn,
  44934. progressFn,
  44935. trackInfoFn,
  44936. timingInfoFn,
  44937. videoSegmentTimingInfoFn,
  44938. audioSegmentTimingInfoFn,
  44939. id3Fn,
  44940. captionsFn,
  44941. isEndOfTimeline,
  44942. endedTimelineFn,
  44943. dataFn,
  44944. doneFn,
  44945. onTransmuxerLog
  44946. }) => {
  44947. const activeXhrs = [];
  44948. const finishProcessingFn = waitForCompletion({
  44949. activeXhrs,
  44950. decryptionWorker,
  44951. trackInfoFn,
  44952. timingInfoFn,
  44953. videoSegmentTimingInfoFn,
  44954. audioSegmentTimingInfoFn,
  44955. id3Fn,
  44956. captionsFn,
  44957. isEndOfTimeline,
  44958. endedTimelineFn,
  44959. dataFn,
  44960. doneFn,
  44961. onTransmuxerLog
  44962. }); // optionally, request the decryption key
  44963. if (segment.key && !segment.key.bytes) {
  44964. const objects = [segment.key];
  44965. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  44966. objects.push(segment.map.key);
  44967. }
  44968. const keyRequestOptions = merge(xhrOptions, {
  44969. uri: segment.key.resolvedUri,
  44970. responseType: 'arraybuffer'
  44971. });
  44972. const keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  44973. const keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  44974. activeXhrs.push(keyXhr);
  44975. } // optionally, request the associated media init segment
  44976. if (segment.map && !segment.map.bytes) {
  44977. const differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  44978. if (differentMapKey) {
  44979. const mapKeyRequestOptions = merge(xhrOptions, {
  44980. uri: segment.map.key.resolvedUri,
  44981. responseType: 'arraybuffer'
  44982. });
  44983. const mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  44984. const mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  44985. activeXhrs.push(mapKeyXhr);
  44986. }
  44987. const initSegmentOptions = merge(xhrOptions, {
  44988. uri: segment.map.resolvedUri,
  44989. responseType: 'arraybuffer',
  44990. headers: segmentXhrHeaders(segment.map)
  44991. });
  44992. const initSegmentRequestCallback = handleInitSegmentResponse({
  44993. segment,
  44994. finishProcessingFn
  44995. });
  44996. const initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  44997. activeXhrs.push(initSegmentXhr);
  44998. }
  44999. const segmentRequestOptions = merge(xhrOptions, {
  45000. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  45001. responseType: 'arraybuffer',
  45002. headers: segmentXhrHeaders(segment)
  45003. });
  45004. const segmentRequestCallback = handleSegmentResponse({
  45005. segment,
  45006. finishProcessingFn,
  45007. responseType: segmentRequestOptions.responseType
  45008. });
  45009. const segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  45010. segmentXhr.addEventListener('progress', handleProgress({
  45011. segment,
  45012. progressFn,
  45013. trackInfoFn,
  45014. timingInfoFn,
  45015. videoSegmentTimingInfoFn,
  45016. audioSegmentTimingInfoFn,
  45017. id3Fn,
  45018. captionsFn,
  45019. isEndOfTimeline,
  45020. endedTimelineFn,
  45021. dataFn
  45022. }));
  45023. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  45024. // multiple times, provide a shared state object
  45025. const loadendState = {};
  45026. activeXhrs.forEach(activeXhr => {
  45027. activeXhr.addEventListener('loadend', handleLoadEnd({
  45028. loadendState,
  45029. abortFn
  45030. }));
  45031. });
  45032. return () => abortAll(activeXhrs);
  45033. };
  45034. /**
  45035. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  45036. * codec strings, or translating codec strings into objects that can be examined.
  45037. */
  45038. const logFn$1 = logger('CodecUtils');
  45039. /**
  45040. * Returns a set of codec strings parsed from the playlist or the default
  45041. * codec strings if no codecs were specified in the playlist
  45042. *
  45043. * @param {Playlist} media the current media playlist
  45044. * @return {Object} an object with the video and audio codecs
  45045. */
  45046. const getCodecs = function (media) {
  45047. // if the codecs were explicitly specified, use them instead of the
  45048. // defaults
  45049. const mediaAttributes = media.attributes || {};
  45050. if (mediaAttributes.CODECS) {
  45051. return parseCodecs(mediaAttributes.CODECS);
  45052. }
  45053. };
  45054. const isMaat = (main, media) => {
  45055. const mediaAttributes = media.attributes || {};
  45056. return main && main.mediaGroups && main.mediaGroups.AUDIO && mediaAttributes.AUDIO && main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  45057. };
  45058. const isMuxed = (main, media) => {
  45059. if (!isMaat(main, media)) {
  45060. return true;
  45061. }
  45062. const mediaAttributes = media.attributes || {};
  45063. const audioGroup = main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  45064. for (const groupId in audioGroup) {
  45065. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  45066. // or there are listed playlists (the case for DASH, as the manifest will have already
  45067. // provided all of the details necessary to generate the audio playlist, as opposed to
  45068. // HLS' externally requested playlists), then the content is demuxed.
  45069. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  45070. return true;
  45071. }
  45072. }
  45073. return false;
  45074. };
  45075. const unwrapCodecList = function (codecList) {
  45076. const codecs = {};
  45077. codecList.forEach(({
  45078. mediaType,
  45079. type,
  45080. details
  45081. }) => {
  45082. codecs[mediaType] = codecs[mediaType] || [];
  45083. codecs[mediaType].push(translateLegacyCodec(`${type}${details}`));
  45084. });
  45085. Object.keys(codecs).forEach(function (mediaType) {
  45086. if (codecs[mediaType].length > 1) {
  45087. 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.`);
  45088. codecs[mediaType] = null;
  45089. return;
  45090. }
  45091. codecs[mediaType] = codecs[mediaType][0];
  45092. });
  45093. return codecs;
  45094. };
  45095. const codecCount = function (codecObj) {
  45096. let count = 0;
  45097. if (codecObj.audio) {
  45098. count++;
  45099. }
  45100. if (codecObj.video) {
  45101. count++;
  45102. }
  45103. return count;
  45104. };
  45105. /**
  45106. * Calculates the codec strings for a working configuration of
  45107. * SourceBuffers to play variant streams in a main playlist. If
  45108. * there is no possible working configuration, an empty object will be
  45109. * returned.
  45110. *
  45111. * @param main {Object} the m3u8 object for the main playlist
  45112. * @param media {Object} the m3u8 object for the variant playlist
  45113. * @return {Object} the codec strings.
  45114. *
  45115. * @private
  45116. */
  45117. const codecsForPlaylist = function (main, media) {
  45118. const mediaAttributes = media.attributes || {};
  45119. const codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  45120. // Put another way, there is no way to have a video-only multiple-audio HLS!
  45121. if (isMaat(main, media) && !codecInfo.audio) {
  45122. if (!isMuxed(main, media)) {
  45123. // It is possible for codecs to be specified on the audio media group playlist but
  45124. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  45125. // video are always separate (and separately specified).
  45126. const defaultCodecs = unwrapCodecList(codecsFromDefault(main, mediaAttributes.AUDIO) || []);
  45127. if (defaultCodecs.audio) {
  45128. codecInfo.audio = defaultCodecs.audio;
  45129. }
  45130. }
  45131. }
  45132. return codecInfo;
  45133. };
  45134. const logFn = logger('PlaylistSelector');
  45135. const representationToString = function (representation) {
  45136. if (!representation || !representation.playlist) {
  45137. return;
  45138. }
  45139. const playlist = representation.playlist;
  45140. return JSON.stringify({
  45141. id: playlist.id,
  45142. bandwidth: representation.bandwidth,
  45143. width: representation.width,
  45144. height: representation.height,
  45145. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  45146. });
  45147. }; // Utilities
  45148. /**
  45149. * Returns the CSS value for the specified property on an element
  45150. * using `getComputedStyle`. Firefox has a long-standing issue where
  45151. * getComputedStyle() may return null when running in an iframe with
  45152. * `display: none`.
  45153. *
  45154. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  45155. * @param {HTMLElement} el the htmlelement to work on
  45156. * @param {string} the proprety to get the style for
  45157. */
  45158. const safeGetComputedStyle = function (el, property) {
  45159. if (!el) {
  45160. return '';
  45161. }
  45162. const result = window.getComputedStyle(el);
  45163. if (!result) {
  45164. return '';
  45165. }
  45166. return result[property];
  45167. };
  45168. /**
  45169. * Resuable stable sort function
  45170. *
  45171. * @param {Playlists} array
  45172. * @param {Function} sortFn Different comparators
  45173. * @function stableSort
  45174. */
  45175. const stableSort = function (array, sortFn) {
  45176. const newArray = array.slice();
  45177. array.sort(function (left, right) {
  45178. const cmp = sortFn(left, right);
  45179. if (cmp === 0) {
  45180. return newArray.indexOf(left) - newArray.indexOf(right);
  45181. }
  45182. return cmp;
  45183. });
  45184. };
  45185. /**
  45186. * A comparator function to sort two playlist object by bandwidth.
  45187. *
  45188. * @param {Object} left a media playlist object
  45189. * @param {Object} right a media playlist object
  45190. * @return {number} Greater than zero if the bandwidth attribute of
  45191. * left is greater than the corresponding attribute of right. Less
  45192. * than zero if the bandwidth of right is greater than left and
  45193. * exactly zero if the two are equal.
  45194. */
  45195. const comparePlaylistBandwidth = function (left, right) {
  45196. let leftBandwidth;
  45197. let rightBandwidth;
  45198. if (left.attributes.BANDWIDTH) {
  45199. leftBandwidth = left.attributes.BANDWIDTH;
  45200. }
  45201. leftBandwidth = leftBandwidth || window.Number.MAX_VALUE;
  45202. if (right.attributes.BANDWIDTH) {
  45203. rightBandwidth = right.attributes.BANDWIDTH;
  45204. }
  45205. rightBandwidth = rightBandwidth || window.Number.MAX_VALUE;
  45206. return leftBandwidth - rightBandwidth;
  45207. };
  45208. /**
  45209. * A comparator function to sort two playlist object by resolution (width).
  45210. *
  45211. * @param {Object} left a media playlist object
  45212. * @param {Object} right a media playlist object
  45213. * @return {number} Greater than zero if the resolution.width attribute of
  45214. * left is greater than the corresponding attribute of right. Less
  45215. * than zero if the resolution.width of right is greater than left and
  45216. * exactly zero if the two are equal.
  45217. */
  45218. const comparePlaylistResolution = function (left, right) {
  45219. let leftWidth;
  45220. let rightWidth;
  45221. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  45222. leftWidth = left.attributes.RESOLUTION.width;
  45223. }
  45224. leftWidth = leftWidth || window.Number.MAX_VALUE;
  45225. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  45226. rightWidth = right.attributes.RESOLUTION.width;
  45227. }
  45228. rightWidth = rightWidth || window.Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  45229. // have the same media dimensions/ resolution
  45230. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  45231. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  45232. }
  45233. return leftWidth - rightWidth;
  45234. };
  45235. /**
  45236. * Chooses the appropriate media playlist based on bandwidth and player size
  45237. *
  45238. * @param {Object} main
  45239. * Object representation of the main manifest
  45240. * @param {number} playerBandwidth
  45241. * Current calculated bandwidth of the player
  45242. * @param {number} playerWidth
  45243. * Current width of the player element (should account for the device pixel ratio)
  45244. * @param {number} playerHeight
  45245. * Current height of the player element (should account for the device pixel ratio)
  45246. * @param {boolean} limitRenditionByPlayerDimensions
  45247. * True if the player width and height should be used during the selection, false otherwise
  45248. * @param {Object} playlistController
  45249. * the current playlistController object
  45250. * @return {Playlist} the highest bitrate playlist less than the
  45251. * currently detected bandwidth, accounting for some amount of
  45252. * bandwidth variance
  45253. */
  45254. let simpleSelector = function (main, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, playlistController) {
  45255. // If we end up getting called before `main` is available, exit early
  45256. if (!main) {
  45257. return;
  45258. }
  45259. const options = {
  45260. bandwidth: playerBandwidth,
  45261. width: playerWidth,
  45262. height: playerHeight,
  45263. limitRenditionByPlayerDimensions
  45264. };
  45265. let playlists = main.playlists; // if playlist is audio only, select between currently active audio group playlists.
  45266. if (Playlist.isAudioOnly(main)) {
  45267. playlists = playlistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  45268. // at the buttom of this function for debugging.
  45269. options.audioOnly = true;
  45270. } // convert the playlists to an intermediary representation to make comparisons easier
  45271. let sortedPlaylistReps = playlists.map(playlist => {
  45272. let bandwidth;
  45273. const width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  45274. const height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  45275. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  45276. bandwidth = bandwidth || window.Number.MAX_VALUE;
  45277. return {
  45278. bandwidth,
  45279. width,
  45280. height,
  45281. playlist
  45282. };
  45283. });
  45284. stableSort(sortedPlaylistReps, (left, right) => left.bandwidth - right.bandwidth); // filter out any playlists that have been excluded due to
  45285. // incompatible configurations
  45286. sortedPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isIncompatible(rep.playlist)); // filter out any playlists that have been disabled manually through the representations
  45287. // api or excluded temporarily due to playback errors.
  45288. let enabledPlaylistReps = sortedPlaylistReps.filter(rep => Playlist.isEnabled(rep.playlist));
  45289. if (!enabledPlaylistReps.length) {
  45290. // if there are no enabled playlists, then they have all been excluded or disabled
  45291. // by the user through the representations api. In this case, ignore exclusion and
  45292. // fallback to what the user wants by using playlists the user has not disabled.
  45293. enabledPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isDisabled(rep.playlist));
  45294. } // filter out any variant that has greater effective bitrate
  45295. // than the current estimated bandwidth
  45296. const bandwidthPlaylistReps = enabledPlaylistReps.filter(rep => rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth);
  45297. let highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  45298. // and then taking the very first element
  45299. const bandwidthBestRep = bandwidthPlaylistReps.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0]; // if we're not going to limit renditions by player size, make an early decision.
  45300. if (limitRenditionByPlayerDimensions === false) {
  45301. const chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  45302. if (chosenRep && chosenRep.playlist) {
  45303. let type = 'sortedPlaylistReps';
  45304. if (bandwidthBestRep) {
  45305. type = 'bandwidthBestRep';
  45306. }
  45307. if (enabledPlaylistReps[0]) {
  45308. type = 'enabledPlaylistReps';
  45309. }
  45310. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  45311. return chosenRep.playlist;
  45312. }
  45313. logFn('could not choose a playlist with options', options);
  45314. return null;
  45315. } // filter out playlists without resolution information
  45316. const haveResolution = bandwidthPlaylistReps.filter(rep => rep.width && rep.height); // sort variants by resolution
  45317. stableSort(haveResolution, (left, right) => left.width - right.width); // if we have the exact resolution as the player use it
  45318. const resolutionBestRepList = haveResolution.filter(rep => rep.width === playerWidth && rep.height === playerHeight);
  45319. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  45320. const resolutionBestRep = resolutionBestRepList.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  45321. let resolutionPlusOneList;
  45322. let resolutionPlusOneSmallest;
  45323. let resolutionPlusOneRep; // find the smallest variant that is larger than the player
  45324. // if there is no match of exact resolution
  45325. if (!resolutionBestRep) {
  45326. resolutionPlusOneList = haveResolution.filter(rep => rep.width > playerWidth || rep.height > playerHeight); // find all the variants have the same smallest resolution
  45327. resolutionPlusOneSmallest = resolutionPlusOneList.filter(rep => rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height); // ensure that we also pick the highest bandwidth variant that
  45328. // is just-larger-than the video player
  45329. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  45330. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  45331. }
  45332. let leastPixelDiffRep; // If this selector proves to be better than others,
  45333. // resolutionPlusOneRep and resolutionBestRep and all
  45334. // the code involving them should be removed.
  45335. if (playlistController.leastPixelDiffSelector) {
  45336. // find the variant that is closest to the player's pixel size
  45337. const leastPixelDiffList = haveResolution.map(rep => {
  45338. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  45339. return rep;
  45340. }); // get the highest bandwidth, closest resolution playlist
  45341. stableSort(leastPixelDiffList, (left, right) => {
  45342. // sort by highest bandwidth if pixelDiff is the same
  45343. if (left.pixelDiff === right.pixelDiff) {
  45344. return right.bandwidth - left.bandwidth;
  45345. }
  45346. return left.pixelDiff - right.pixelDiff;
  45347. });
  45348. leastPixelDiffRep = leastPixelDiffList[0];
  45349. } // fallback chain of variants
  45350. const chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  45351. if (chosenRep && chosenRep.playlist) {
  45352. let type = 'sortedPlaylistReps';
  45353. if (leastPixelDiffRep) {
  45354. type = 'leastPixelDiffRep';
  45355. } else if (resolutionPlusOneRep) {
  45356. type = 'resolutionPlusOneRep';
  45357. } else if (resolutionBestRep) {
  45358. type = 'resolutionBestRep';
  45359. } else if (bandwidthBestRep) {
  45360. type = 'bandwidthBestRep';
  45361. } else if (enabledPlaylistReps[0]) {
  45362. type = 'enabledPlaylistReps';
  45363. }
  45364. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  45365. return chosenRep.playlist;
  45366. }
  45367. logFn('could not choose a playlist with options', options);
  45368. return null;
  45369. };
  45370. /**
  45371. * Chooses the appropriate media playlist based on the most recent
  45372. * bandwidth estimate and the player size.
  45373. *
  45374. * Expects to be called within the context of an instance of VhsHandler
  45375. *
  45376. * @return {Playlist} the highest bitrate playlist less than the
  45377. * currently detected bandwidth, accounting for some amount of
  45378. * bandwidth variance
  45379. */
  45380. const lastBandwidthSelector = function () {
  45381. const pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  45382. return simpleSelector(this.playlists.main, this.systemBandwidth, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.playlistController_);
  45383. };
  45384. /**
  45385. * Chooses the appropriate media playlist based on an
  45386. * exponential-weighted moving average of the bandwidth after
  45387. * filtering for player size.
  45388. *
  45389. * Expects to be called within the context of an instance of VhsHandler
  45390. *
  45391. * @param {number} decay - a number between 0 and 1. Higher values of
  45392. * this parameter will cause previous bandwidth estimates to lose
  45393. * significance more quickly.
  45394. * @return {Function} a function which can be invoked to create a new
  45395. * playlist selector function.
  45396. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  45397. */
  45398. const movingAverageBandwidthSelector = function (decay) {
  45399. let average = -1;
  45400. let lastSystemBandwidth = -1;
  45401. if (decay < 0 || decay > 1) {
  45402. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  45403. }
  45404. return function () {
  45405. const pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  45406. if (average < 0) {
  45407. average = this.systemBandwidth;
  45408. lastSystemBandwidth = this.systemBandwidth;
  45409. } // stop the average value from decaying for every 250ms
  45410. // when the systemBandwidth is constant
  45411. // and
  45412. // stop average from setting to a very low value when the
  45413. // systemBandwidth becomes 0 in case of chunk cancellation
  45414. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  45415. average = decay * this.systemBandwidth + (1 - decay) * average;
  45416. lastSystemBandwidth = this.systemBandwidth;
  45417. }
  45418. return simpleSelector(this.playlists.main, average, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.playlistController_);
  45419. };
  45420. };
  45421. /**
  45422. * Chooses the appropriate media playlist based on the potential to rebuffer
  45423. *
  45424. * @param {Object} settings
  45425. * Object of information required to use this selector
  45426. * @param {Object} settings.main
  45427. * Object representation of the main manifest
  45428. * @param {number} settings.currentTime
  45429. * The current time of the player
  45430. * @param {number} settings.bandwidth
  45431. * Current measured bandwidth
  45432. * @param {number} settings.duration
  45433. * Duration of the media
  45434. * @param {number} settings.segmentDuration
  45435. * Segment duration to be used in round trip time calculations
  45436. * @param {number} settings.timeUntilRebuffer
  45437. * Time left in seconds until the player has to rebuffer
  45438. * @param {number} settings.currentTimeline
  45439. * The current timeline segments are being loaded from
  45440. * @param {SyncController} settings.syncController
  45441. * SyncController for determining if we have a sync point for a given playlist
  45442. * @return {Object|null}
  45443. * {Object} return.playlist
  45444. * The highest bandwidth playlist with the least amount of rebuffering
  45445. * {Number} return.rebufferingImpact
  45446. * The amount of time in seconds switching to this playlist will rebuffer. A
  45447. * negative value means that switching will cause zero rebuffering.
  45448. */
  45449. const minRebufferMaxBandwidthSelector = function (settings) {
  45450. const {
  45451. main,
  45452. currentTime,
  45453. bandwidth,
  45454. duration,
  45455. segmentDuration,
  45456. timeUntilRebuffer,
  45457. currentTimeline,
  45458. syncController
  45459. } = settings; // filter out any playlists that have been excluded due to
  45460. // incompatible configurations
  45461. const compatiblePlaylists = main.playlists.filter(playlist => !Playlist.isIncompatible(playlist)); // filter out any playlists that have been disabled manually through the representations
  45462. // api or excluded temporarily due to playback errors.
  45463. let enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  45464. if (!enabledPlaylists.length) {
  45465. // if there are no enabled playlists, then they have all been excluded or disabled
  45466. // by the user through the representations api. In this case, ignore exclusion and
  45467. // fallback to what the user wants by using playlists the user has not disabled.
  45468. enabledPlaylists = compatiblePlaylists.filter(playlist => !Playlist.isDisabled(playlist));
  45469. }
  45470. const bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  45471. const rebufferingEstimates = bandwidthPlaylists.map(playlist => {
  45472. const syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  45473. // sync request first. This will double the request time
  45474. const numRequests = syncPoint ? 1 : 2;
  45475. const requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  45476. const rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  45477. return {
  45478. playlist,
  45479. rebufferingImpact
  45480. };
  45481. });
  45482. const noRebufferingPlaylists = rebufferingEstimates.filter(estimate => estimate.rebufferingImpact <= 0); // Sort by bandwidth DESC
  45483. stableSort(noRebufferingPlaylists, (a, b) => comparePlaylistBandwidth(b.playlist, a.playlist));
  45484. if (noRebufferingPlaylists.length) {
  45485. return noRebufferingPlaylists[0];
  45486. }
  45487. stableSort(rebufferingEstimates, (a, b) => a.rebufferingImpact - b.rebufferingImpact);
  45488. return rebufferingEstimates[0] || null;
  45489. };
  45490. /**
  45491. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  45492. * one with video. If no renditions with video exist, return the lowest audio rendition.
  45493. *
  45494. * Expects to be called within the context of an instance of VhsHandler
  45495. *
  45496. * @return {Object|null}
  45497. * {Object} return.playlist
  45498. * The lowest bitrate playlist that contains a video codec. If no such rendition
  45499. * exists pick the lowest audio rendition.
  45500. */
  45501. const lowestBitrateCompatibleVariantSelector = function () {
  45502. // filter out any playlists that have been excluded due to
  45503. // incompatible configurations or playback errors
  45504. const playlists = this.playlists.main.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  45505. stableSort(playlists, (a, b) => comparePlaylistBandwidth(a, b)); // Parse and assume that playlists with no video codec have no video
  45506. // (this is not necessarily true, although it is generally true).
  45507. //
  45508. // If an entire manifest has no valid videos everything will get filtered
  45509. // out.
  45510. const playlistsWithVideo = playlists.filter(playlist => !!codecsForPlaylist(this.playlists.main, playlist).video);
  45511. return playlistsWithVideo[0] || null;
  45512. };
  45513. /**
  45514. * Combine all segments into a single Uint8Array
  45515. *
  45516. * @param {Object} segmentObj
  45517. * @return {Uint8Array} concatenated bytes
  45518. * @private
  45519. */
  45520. const concatSegments = segmentObj => {
  45521. let offset = 0;
  45522. let tempBuffer;
  45523. if (segmentObj.bytes) {
  45524. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  45525. segmentObj.segments.forEach(segment => {
  45526. tempBuffer.set(segment, offset);
  45527. offset += segment.byteLength;
  45528. });
  45529. }
  45530. return tempBuffer;
  45531. };
  45532. /**
  45533. * @file text-tracks.js
  45534. */
  45535. /**
  45536. * Create captions text tracks on video.js if they do not exist
  45537. *
  45538. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  45539. * @param {Object} tech the video.js tech
  45540. * @param {Object} captionStream the caption stream to create
  45541. * @private
  45542. */
  45543. const createCaptionsTrackIfNotExists = function (inbandTextTracks, tech, captionStream) {
  45544. if (!inbandTextTracks[captionStream]) {
  45545. tech.trigger({
  45546. type: 'usage',
  45547. name: 'vhs-608'
  45548. });
  45549. let instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  45550. if (/^cc708_/.test(captionStream)) {
  45551. instreamId = 'SERVICE' + captionStream.split('_')[1];
  45552. }
  45553. const track = tech.textTracks().getTrackById(instreamId);
  45554. if (track) {
  45555. // Resuse an existing track with a CC# id because this was
  45556. // very likely created by videojs-contrib-hls from information
  45557. // in the m3u8 for us to use
  45558. inbandTextTracks[captionStream] = track;
  45559. } else {
  45560. // This section gets called when we have caption services that aren't specified in the manifest.
  45561. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  45562. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  45563. let label = captionStream;
  45564. let language = captionStream;
  45565. let def = false;
  45566. const captionService = captionServices[instreamId];
  45567. if (captionService) {
  45568. label = captionService.label;
  45569. language = captionService.language;
  45570. def = captionService.default;
  45571. } // Otherwise, create a track with the default `CC#` label and
  45572. // without a language
  45573. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  45574. kind: 'captions',
  45575. id: instreamId,
  45576. // TODO: investigate why this doesn't seem to turn the caption on by default
  45577. default: def,
  45578. label,
  45579. language
  45580. }, false).track;
  45581. }
  45582. }
  45583. };
  45584. /**
  45585. * Add caption text track data to a source handler given an array of captions
  45586. *
  45587. * @param {Object}
  45588. * @param {Object} inbandTextTracks the inband text tracks
  45589. * @param {number} timestampOffset the timestamp offset of the source buffer
  45590. * @param {Array} captionArray an array of caption data
  45591. * @private
  45592. */
  45593. const addCaptionData = function ({
  45594. inbandTextTracks,
  45595. captionArray,
  45596. timestampOffset
  45597. }) {
  45598. if (!captionArray) {
  45599. return;
  45600. }
  45601. const Cue = window.WebKitDataCue || window.VTTCue;
  45602. captionArray.forEach(caption => {
  45603. const track = caption.stream;
  45604. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  45605. });
  45606. };
  45607. /**
  45608. * Define properties on a cue for backwards compatability,
  45609. * but warn the user that the way that they are using it
  45610. * is depricated and will be removed at a later date.
  45611. *
  45612. * @param {Cue} cue the cue to add the properties on
  45613. * @private
  45614. */
  45615. const deprecateOldCue = function (cue) {
  45616. Object.defineProperties(cue.frame, {
  45617. id: {
  45618. get() {
  45619. videojs.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  45620. return cue.value.key;
  45621. }
  45622. },
  45623. value: {
  45624. get() {
  45625. videojs.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  45626. return cue.value.data;
  45627. }
  45628. },
  45629. privateData: {
  45630. get() {
  45631. videojs.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  45632. return cue.value.data;
  45633. }
  45634. }
  45635. });
  45636. };
  45637. /**
  45638. * Add metadata text track data to a source handler given an array of metadata
  45639. *
  45640. * @param {Object}
  45641. * @param {Object} inbandTextTracks the inband text tracks
  45642. * @param {Array} metadataArray an array of meta data
  45643. * @param {number} timestampOffset the timestamp offset of the source buffer
  45644. * @param {number} videoDuration the duration of the video
  45645. * @private
  45646. */
  45647. const addMetadata = ({
  45648. inbandTextTracks,
  45649. metadataArray,
  45650. timestampOffset,
  45651. videoDuration
  45652. }) => {
  45653. if (!metadataArray) {
  45654. return;
  45655. }
  45656. const Cue = window.WebKitDataCue || window.VTTCue;
  45657. const metadataTrack = inbandTextTracks.metadataTrack_;
  45658. if (!metadataTrack) {
  45659. return;
  45660. }
  45661. metadataArray.forEach(metadata => {
  45662. const time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  45663. // ignore this bit of metadata.
  45664. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  45665. // which is the "Title/Songname/Content description" frame
  45666. if (typeof time !== 'number' || window.isNaN(time) || time < 0 || !(time < Infinity)) {
  45667. return;
  45668. }
  45669. metadata.frames.forEach(frame => {
  45670. const cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  45671. cue.frame = frame;
  45672. cue.value = frame;
  45673. deprecateOldCue(cue);
  45674. metadataTrack.addCue(cue);
  45675. });
  45676. });
  45677. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  45678. return;
  45679. } // Updating the metadeta cues so that
  45680. // the endTime of each cue is the startTime of the next cue
  45681. // the endTime of last cue is the duration of the video
  45682. const cues = metadataTrack.cues;
  45683. const cuesArray = []; // Create a copy of the TextTrackCueList...
  45684. // ...disregarding cues with a falsey value
  45685. for (let i = 0; i < cues.length; i++) {
  45686. if (cues[i]) {
  45687. cuesArray.push(cues[i]);
  45688. }
  45689. } // Group cues by their startTime value
  45690. const cuesGroupedByStartTime = cuesArray.reduce((obj, cue) => {
  45691. const timeSlot = obj[cue.startTime] || [];
  45692. timeSlot.push(cue);
  45693. obj[cue.startTime] = timeSlot;
  45694. return obj;
  45695. }, {}); // Sort startTimes by ascending order
  45696. const sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort((a, b) => Number(a) - Number(b)); // Map each cue group's endTime to the next group's startTime
  45697. sortedStartTimes.forEach((startTime, idx) => {
  45698. const cueGroup = cuesGroupedByStartTime[startTime];
  45699. const nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
  45700. cueGroup.forEach(cue => {
  45701. cue.endTime = nextTime;
  45702. });
  45703. });
  45704. };
  45705. /**
  45706. * Create metadata text track on video.js if it does not exist
  45707. *
  45708. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  45709. * @param {string} dispatchType the inband metadata track dispatch type
  45710. * @param {Object} tech the video.js tech
  45711. * @private
  45712. */
  45713. const createMetadataTrackIfNotExists = (inbandTextTracks, dispatchType, tech) => {
  45714. if (inbandTextTracks.metadataTrack_) {
  45715. return;
  45716. }
  45717. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  45718. kind: 'metadata',
  45719. label: 'Timed Metadata'
  45720. }, false).track;
  45721. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  45722. };
  45723. /**
  45724. * Remove cues from a track on video.js.
  45725. *
  45726. * @param {Double} start start of where we should remove the cue
  45727. * @param {Double} end end of where the we should remove the cue
  45728. * @param {Object} track the text track to remove the cues from
  45729. * @private
  45730. */
  45731. const removeCuesFromTrack = function (start, end, track) {
  45732. let i;
  45733. let cue;
  45734. if (!track) {
  45735. return;
  45736. }
  45737. if (!track.cues) {
  45738. return;
  45739. }
  45740. i = track.cues.length;
  45741. while (i--) {
  45742. cue = track.cues[i]; // Remove any cue within the provided start and end time
  45743. if (cue.startTime >= start && cue.endTime <= end) {
  45744. track.removeCue(cue);
  45745. }
  45746. }
  45747. };
  45748. /**
  45749. * Remove duplicate cues from a track on video.js (a cue is considered a
  45750. * duplicate if it has the same time interval and text as another)
  45751. *
  45752. * @param {Object} track the text track to remove the duplicate cues from
  45753. * @private
  45754. */
  45755. const removeDuplicateCuesFromTrack = function (track) {
  45756. const cues = track.cues;
  45757. if (!cues) {
  45758. return;
  45759. }
  45760. for (let i = 0; i < cues.length; i++) {
  45761. const duplicates = [];
  45762. let occurrences = 0;
  45763. for (let j = 0; j < cues.length; j++) {
  45764. if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
  45765. occurrences++;
  45766. if (occurrences > 1) {
  45767. duplicates.push(cues[j]);
  45768. }
  45769. }
  45770. }
  45771. if (duplicates.length) {
  45772. duplicates.forEach(dupe => track.removeCue(dupe));
  45773. }
  45774. }
  45775. };
  45776. /**
  45777. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  45778. * front of current time.
  45779. *
  45780. * @param {Array} buffer
  45781. * The current buffer of gop information
  45782. * @param {number} currentTime
  45783. * The current time
  45784. * @param {Double} mapping
  45785. * Offset to map display time to stream presentation time
  45786. * @return {Array}
  45787. * List of gops considered safe to append over
  45788. */
  45789. const gopsSafeToAlignWith = (buffer, currentTime, mapping) => {
  45790. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  45791. return [];
  45792. } // pts value for current time + 3 seconds to give a bit more wiggle room
  45793. const currentTimePts = Math.ceil((currentTime - mapping + 3) * clock_1);
  45794. let i;
  45795. for (i = 0; i < buffer.length; i++) {
  45796. if (buffer[i].pts > currentTimePts) {
  45797. break;
  45798. }
  45799. }
  45800. return buffer.slice(i);
  45801. };
  45802. /**
  45803. * Appends gop information (timing and byteLength) received by the transmuxer for the
  45804. * gops appended in the last call to appendBuffer
  45805. *
  45806. * @param {Array} buffer
  45807. * The current buffer of gop information
  45808. * @param {Array} gops
  45809. * List of new gop information
  45810. * @param {boolean} replace
  45811. * If true, replace the buffer with the new gop information. If false, append the
  45812. * new gop information to the buffer in the right location of time.
  45813. * @return {Array}
  45814. * Updated list of gop information
  45815. */
  45816. const updateGopBuffer = (buffer, gops, replace) => {
  45817. if (!gops.length) {
  45818. return buffer;
  45819. }
  45820. if (replace) {
  45821. // If we are in safe append mode, then completely overwrite the gop buffer
  45822. // with the most recent appeneded data. This will make sure that when appending
  45823. // future segments, we only try to align with gops that are both ahead of current
  45824. // time and in the last segment appended.
  45825. return gops.slice();
  45826. }
  45827. const start = gops[0].pts;
  45828. let i = 0;
  45829. for (i; i < buffer.length; i++) {
  45830. if (buffer[i].pts >= start) {
  45831. break;
  45832. }
  45833. }
  45834. return buffer.slice(0, i).concat(gops);
  45835. };
  45836. /**
  45837. * Removes gop information in buffer that overlaps with provided start and end
  45838. *
  45839. * @param {Array} buffer
  45840. * The current buffer of gop information
  45841. * @param {Double} start
  45842. * position to start the remove at
  45843. * @param {Double} end
  45844. * position to end the remove at
  45845. * @param {Double} mapping
  45846. * Offset to map display time to stream presentation time
  45847. */
  45848. const removeGopBuffer = (buffer, start, end, mapping) => {
  45849. const startPts = Math.ceil((start - mapping) * clock_1);
  45850. const endPts = Math.ceil((end - mapping) * clock_1);
  45851. const updatedBuffer = buffer.slice();
  45852. let i = buffer.length;
  45853. while (i--) {
  45854. if (buffer[i].pts <= endPts) {
  45855. break;
  45856. }
  45857. }
  45858. if (i === -1) {
  45859. // no removal because end of remove range is before start of buffer
  45860. return updatedBuffer;
  45861. }
  45862. let j = i + 1;
  45863. while (j--) {
  45864. if (buffer[j].pts <= startPts) {
  45865. break;
  45866. }
  45867. } // clamp remove range start to 0 index
  45868. j = Math.max(j, 0);
  45869. updatedBuffer.splice(j, i - j + 1);
  45870. return updatedBuffer;
  45871. };
  45872. const shallowEqual = function (a, b) {
  45873. // if both are undefined
  45874. // or one or the other is undefined
  45875. // they are not equal
  45876. if (!a && !b || !a && b || a && !b) {
  45877. return false;
  45878. } // they are the same object and thus, equal
  45879. if (a === b) {
  45880. return true;
  45881. } // sort keys so we can make sure they have
  45882. // all the same keys later.
  45883. const akeys = Object.keys(a).sort();
  45884. const bkeys = Object.keys(b).sort(); // different number of keys, not equal
  45885. if (akeys.length !== bkeys.length) {
  45886. return false;
  45887. }
  45888. for (let i = 0; i < akeys.length; i++) {
  45889. const key = akeys[i]; // different sorted keys, not equal
  45890. if (key !== bkeys[i]) {
  45891. return false;
  45892. } // different values, not equal
  45893. if (a[key] !== b[key]) {
  45894. return false;
  45895. }
  45896. }
  45897. return true;
  45898. };
  45899. // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  45900. const QUOTA_EXCEEDED_ERR = 22;
  45901. /**
  45902. * The segment loader has no recourse except to fetch a segment in the
  45903. * current playlist and use the internal timestamps in that segment to
  45904. * generate a syncPoint. This function returns a good candidate index
  45905. * for that process.
  45906. *
  45907. * @param {Array} segments - the segments array from a playlist.
  45908. * @return {number} An index of a segment from the playlist to load
  45909. */
  45910. const getSyncSegmentCandidate = function (currentTimeline, segments, targetTime) {
  45911. segments = segments || [];
  45912. const timelineSegments = [];
  45913. let time = 0;
  45914. for (let i = 0; i < segments.length; i++) {
  45915. const segment = segments[i];
  45916. if (currentTimeline === segment.timeline) {
  45917. timelineSegments.push(i);
  45918. time += segment.duration;
  45919. if (time > targetTime) {
  45920. return i;
  45921. }
  45922. }
  45923. }
  45924. if (timelineSegments.length === 0) {
  45925. return 0;
  45926. } // default to the last timeline segment
  45927. return timelineSegments[timelineSegments.length - 1];
  45928. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  45929. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  45930. // as a start to prevent any potential issues with removing content too close to the
  45931. // playhead.
  45932. const MIN_BACK_BUFFER = 1; // in ms
  45933. const CHECK_BUFFER_DELAY = 500;
  45934. const finite = num => typeof num === 'number' && isFinite(num); // With most content hovering around 30fps, if a segment has a duration less than a half
  45935. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  45936. // not accurately reflect the rest of the content.
  45937. const MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  45938. const illegalMediaSwitch = (loaderType, startingMedia, trackInfo) => {
  45939. // Although these checks should most likely cover non 'main' types, for now it narrows
  45940. // the scope of our checks.
  45941. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  45942. return null;
  45943. }
  45944. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  45945. return 'Neither audio nor video found in segment.';
  45946. }
  45947. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  45948. 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.';
  45949. }
  45950. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  45951. 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.';
  45952. }
  45953. return null;
  45954. };
  45955. /**
  45956. * Calculates a time value that is safe to remove from the back buffer without interrupting
  45957. * playback.
  45958. *
  45959. * @param {TimeRange} seekable
  45960. * The current seekable range
  45961. * @param {number} currentTime
  45962. * The current time of the player
  45963. * @param {number} targetDuration
  45964. * The target duration of the current playlist
  45965. * @return {number}
  45966. * Time that is safe to remove from the back buffer without interrupting playback
  45967. */
  45968. const safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {
  45969. // 30 seconds before the playhead provides a safe default for trimming.
  45970. //
  45971. // Choosing a reasonable default is particularly important for high bitrate content and
  45972. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  45973. // throw an APPEND_BUFFER_ERR.
  45974. let trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  45975. if (seekable.length) {
  45976. // Some live playlists may have a shorter window of content than the full allowed back
  45977. // buffer. For these playlists, don't save content that's no longer within the window.
  45978. trimTime = Math.max(trimTime, seekable.start(0));
  45979. } // Don't remove within target duration of the current time to avoid the possibility of
  45980. // removing the GOP currently being played, as removing it can cause playback stalls.
  45981. const maxTrimTime = currentTime - targetDuration;
  45982. return Math.min(maxTrimTime, trimTime);
  45983. };
  45984. const segmentInfoString = segmentInfo => {
  45985. const {
  45986. startOfSegment,
  45987. duration,
  45988. segment,
  45989. part,
  45990. playlist: {
  45991. mediaSequence: seq,
  45992. id,
  45993. segments = []
  45994. },
  45995. mediaIndex: index,
  45996. partIndex,
  45997. timeline
  45998. } = segmentInfo;
  45999. const segmentLen = segments.length - 1;
  46000. let selection = 'mediaIndex/partIndex increment';
  46001. if (segmentInfo.getMediaInfoForTime) {
  46002. selection = `getMediaInfoForTime (${segmentInfo.getMediaInfoForTime})`;
  46003. } else if (segmentInfo.isSyncRequest) {
  46004. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  46005. }
  46006. if (segmentInfo.independent) {
  46007. selection += ` with independent ${segmentInfo.independent}`;
  46008. }
  46009. const hasPartIndex = typeof partIndex === 'number';
  46010. const name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  46011. const zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  46012. preloadSegment: segment
  46013. }) - 1 : 0;
  46014. 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}]`;
  46015. };
  46016. const timingInfoPropertyForMedia = mediaType => `${mediaType}TimingInfo`;
  46017. /**
  46018. * Returns the timestamp offset to use for the segment.
  46019. *
  46020. * @param {number} segmentTimeline
  46021. * The timeline of the segment
  46022. * @param {number} currentTimeline
  46023. * The timeline currently being followed by the loader
  46024. * @param {number} startOfSegment
  46025. * The estimated segment start
  46026. * @param {TimeRange[]} buffered
  46027. * The loader's buffer
  46028. * @param {boolean} overrideCheck
  46029. * If true, no checks are made to see if the timestamp offset value should be set,
  46030. * but sets it directly to a value.
  46031. *
  46032. * @return {number|null}
  46033. * Either a number representing a new timestamp offset, or null if the segment is
  46034. * part of the same timeline
  46035. */
  46036. const timestampOffsetForSegment = ({
  46037. segmentTimeline,
  46038. currentTimeline,
  46039. startOfSegment,
  46040. buffered,
  46041. overrideCheck
  46042. }) => {
  46043. // Check to see if we are crossing a discontinuity to see if we need to set the
  46044. // timestamp offset on the transmuxer and source buffer.
  46045. //
  46046. // Previously, we changed the timestampOffset if the start of this segment was less than
  46047. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  46048. // behavior, especially around long running live streams.
  46049. if (!overrideCheck && segmentTimeline === currentTimeline) {
  46050. return null;
  46051. } // When changing renditions, it's possible to request a segment on an older timeline. For
  46052. // instance, given two renditions with the following:
  46053. //
  46054. // #EXTINF:10
  46055. // segment1
  46056. // #EXT-X-DISCONTINUITY
  46057. // #EXTINF:10
  46058. // segment2
  46059. // #EXTINF:10
  46060. // segment3
  46061. //
  46062. // And the current player state:
  46063. //
  46064. // current time: 8
  46065. // buffer: 0 => 20
  46066. //
  46067. // The next segment on the current rendition would be segment3, filling the buffer from
  46068. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  46069. // then the next segment to be requested will be segment1 from the new rendition in
  46070. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  46071. // content (since it would position segment1 of the new rendition starting at 20s). This
  46072. // case can be identified when the new segment's timeline is a prior value. Instead of
  46073. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  46074. // more accurate to the actual start time of the segment.
  46075. if (segmentTimeline < currentTimeline) {
  46076. return startOfSegment;
  46077. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  46078. // value uses the end of the last segment if it is available. While this value
  46079. // should often be correct, it's better to rely on the buffered end, as the new
  46080. // content post discontinuity should line up with the buffered end as if it were
  46081. // time 0 for the new content.
  46082. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  46083. };
  46084. /**
  46085. * Returns whether or not the loader should wait for a timeline change from the timeline
  46086. * change controller before processing the segment.
  46087. *
  46088. * Primary timing in VHS goes by video. This is different from most media players, as
  46089. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  46090. * will continue to use video as the primary timing source, due to the current logic and
  46091. * expectations built around it.
  46092. * Since the timing follows video, in order to maintain sync, the video loader is
  46093. * responsible for setting both audio and video source buffer timestamp offsets.
  46094. *
  46095. * Setting different values for audio and video source buffers could lead to
  46096. * desyncing. The following examples demonstrate some of the situations where this
  46097. * distinction is important. Note that all of these cases involve demuxed content. When
  46098. * content is muxed, the audio and video are packaged together, therefore syncing
  46099. * separate media playlists is not an issue.
  46100. *
  46101. * CASE 1: Audio prepares to load a new timeline before video:
  46102. *
  46103. * Timeline: 0 1
  46104. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  46105. * Audio Loader: ^
  46106. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  46107. * Video Loader ^
  46108. *
  46109. * In the above example, the audio loader is preparing to load the 6th segment, the first
  46110. * after a discontinuity, while the video loader is still loading the 5th segment, before
  46111. * the discontinuity.
  46112. *
  46113. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  46114. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  46115. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  46116. * the audio loader must provide the audioAppendStart value to trim the content in the
  46117. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  46118. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  46119. * segment until that value is provided.
  46120. *
  46121. * CASE 2: Video prepares to load a new timeline before audio:
  46122. *
  46123. * Timeline: 0 1
  46124. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  46125. * Audio Loader: ^
  46126. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  46127. * Video Loader ^
  46128. *
  46129. * In the above example, the video loader is preparing to load the 6th segment, the first
  46130. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  46131. * the discontinuity.
  46132. *
  46133. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  46134. * segment is loaded and processed, both the video and audio timestamp offsets will be
  46135. * set, since video is used as the primary timing source. This is to ensure content lines
  46136. * up appropriately, as any modifications to the video timing are reflected by audio when
  46137. * the video loader sets the audio and video timestamp offsets to the same value. However,
  46138. * setting the timestamp offset for audio before audio has had a chance to change
  46139. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  46140. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  46141. *
  46142. * CASE 3: When seeking, audio prepares to load a new timeline before video
  46143. *
  46144. * Timeline: 0 1
  46145. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  46146. * Audio Loader: ^
  46147. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  46148. * Video Loader ^
  46149. *
  46150. * In the above example, both audio and video loaders are loading segments from timeline
  46151. * 0, but imagine that the seek originated from timeline 1.
  46152. *
  46153. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  46154. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  46155. * must wait for the video loader to load its segment and update both the audio and video
  46156. * timestamp offsets before it may load and append its own segment. This is the case
  46157. * whether the seek results in a mismatched segment request (e.g., the audio loader
  46158. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  46159. * loaders choose to load the same segment index from each playlist, as the segments may
  46160. * not be aligned perfectly, even for matching segment indexes.
  46161. *
  46162. * @param {Object} timelinechangeController
  46163. * @param {number} currentTimeline
  46164. * The timeline currently being followed by the loader
  46165. * @param {number} segmentTimeline
  46166. * The timeline of the segment being loaded
  46167. * @param {('main'|'audio')} loaderType
  46168. * The loader type
  46169. * @param {boolean} audioDisabled
  46170. * Whether the audio is disabled for the loader. This should only be true when the
  46171. * loader may have muxed audio in its segment, but should not append it, e.g., for
  46172. * the main loader when an alternate audio playlist is active.
  46173. *
  46174. * @return {boolean}
  46175. * Whether the loader should wait for a timeline change from the timeline change
  46176. * controller before processing the segment
  46177. */
  46178. const shouldWaitForTimelineChange = ({
  46179. timelineChangeController,
  46180. currentTimeline,
  46181. segmentTimeline,
  46182. loaderType,
  46183. audioDisabled
  46184. }) => {
  46185. if (currentTimeline === segmentTimeline) {
  46186. return false;
  46187. }
  46188. if (loaderType === 'audio') {
  46189. const lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  46190. type: 'main'
  46191. }); // Audio loader should wait if:
  46192. //
  46193. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  46194. // * main hasn't yet changed to the timeline audio is looking to load
  46195. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  46196. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  46197. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  46198. // loader's segments (or the content is audio/video only and handled by the main
  46199. // loader).
  46200. if (loaderType === 'main' && audioDisabled) {
  46201. const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  46202. type: 'audio'
  46203. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  46204. // change to the current timeline.
  46205. //
  46206. // Since the main loader is responsible for setting the timestamp offset for both
  46207. // audio and video, the main loader must wait for audio to be about to change to its
  46208. // timeline before setting the offset, otherwise, if audio is behind in loading,
  46209. // segments from the previous timeline would be adjusted by the new timestamp offset.
  46210. //
  46211. // This requirement means that video will not cross a timeline until the audio is
  46212. // about to cross to it, so that way audio and video will always cross the timeline
  46213. // together.
  46214. //
  46215. // In addition to normal timeline changes, these rules also apply to the start of a
  46216. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  46217. // that these rules apply to the first timeline change because if they did not, it's
  46218. // possible that the main loader will cross two timelines before the audio loader has
  46219. // crossed one. Logic may be implemented to handle the startup as a special case, but
  46220. // it's easier to simply treat all timeline changes the same.
  46221. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  46222. return false;
  46223. }
  46224. return true;
  46225. }
  46226. return false;
  46227. };
  46228. const mediaDuration = timingInfos => {
  46229. let maxDuration = 0;
  46230. ['video', 'audio'].forEach(function (type) {
  46231. const typeTimingInfo = timingInfos[`${type}TimingInfo`];
  46232. if (!typeTimingInfo) {
  46233. return;
  46234. }
  46235. const {
  46236. start,
  46237. end
  46238. } = typeTimingInfo;
  46239. let duration;
  46240. if (typeof start === 'bigint' || typeof end === 'bigint') {
  46241. duration = window.BigInt(end) - window.BigInt(start);
  46242. } else if (typeof start === 'number' && typeof end === 'number') {
  46243. duration = end - start;
  46244. }
  46245. if (typeof duration !== 'undefined' && duration > maxDuration) {
  46246. maxDuration = duration;
  46247. }
  46248. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  46249. // as we only need BigInt when we are above that.
  46250. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  46251. maxDuration = Number(maxDuration);
  46252. }
  46253. return maxDuration;
  46254. };
  46255. const segmentTooLong = ({
  46256. segmentDuration,
  46257. maxDuration
  46258. }) => {
  46259. // 0 duration segments are most likely due to metadata only segments or a lack of
  46260. // information.
  46261. if (!segmentDuration) {
  46262. return false;
  46263. } // For HLS:
  46264. //
  46265. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  46266. // The EXTINF duration of each Media Segment in the Playlist
  46267. // file, when rounded to the nearest integer, MUST be less than or equal
  46268. // to the target duration; longer segments can trigger playback stalls
  46269. // or other errors.
  46270. //
  46271. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  46272. // duration. Although that reported duration is occasionally approximate (i.e., not
  46273. // exact), a strict check may report that a segment is too long more often in DASH.
  46274. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  46275. };
  46276. const getTroublesomeSegmentDurationMessage = (segmentInfo, sourceType) => {
  46277. // Right now we aren't following DASH's timing model exactly, so only perform
  46278. // this check for HLS content.
  46279. if (sourceType !== 'hls') {
  46280. return null;
  46281. }
  46282. const segmentDuration = mediaDuration({
  46283. audioTimingInfo: segmentInfo.audioTimingInfo,
  46284. videoTimingInfo: segmentInfo.videoTimingInfo
  46285. }); // Don't report if we lack information.
  46286. //
  46287. // If the segment has a duration of 0 it is either a lack of information or a
  46288. // metadata only segment and shouldn't be reported here.
  46289. if (!segmentDuration) {
  46290. return null;
  46291. }
  46292. const targetDuration = segmentInfo.playlist.targetDuration;
  46293. const isSegmentWayTooLong = segmentTooLong({
  46294. segmentDuration,
  46295. maxDuration: targetDuration * 2
  46296. });
  46297. const isSegmentSlightlyTooLong = segmentTooLong({
  46298. segmentDuration,
  46299. maxDuration: targetDuration
  46300. });
  46301. const 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';
  46302. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  46303. return {
  46304. severity: isSegmentWayTooLong ? 'warn' : 'info',
  46305. message: segmentTooLongMessage
  46306. };
  46307. }
  46308. return null;
  46309. };
  46310. /**
  46311. * An object that manages segment loading and appending.
  46312. *
  46313. * @class SegmentLoader
  46314. * @param {Object} options required and optional options
  46315. * @extends videojs.EventTarget
  46316. */
  46317. class SegmentLoader extends videojs.EventTarget {
  46318. constructor(settings, options = {}) {
  46319. super(); // check pre-conditions
  46320. if (!settings) {
  46321. throw new TypeError('Initialization settings are required');
  46322. }
  46323. if (typeof settings.currentTime !== 'function') {
  46324. throw new TypeError('No currentTime getter specified');
  46325. }
  46326. if (!settings.mediaSource) {
  46327. throw new TypeError('No MediaSource specified');
  46328. } // public properties
  46329. this.bandwidth = settings.bandwidth;
  46330. this.throughput = {
  46331. rate: 0,
  46332. count: 0
  46333. };
  46334. this.roundTrip = NaN;
  46335. this.resetStats_();
  46336. this.mediaIndex = null;
  46337. this.partIndex = null; // private settings
  46338. this.hasPlayed_ = settings.hasPlayed;
  46339. this.currentTime_ = settings.currentTime;
  46340. this.seekable_ = settings.seekable;
  46341. this.seeking_ = settings.seeking;
  46342. this.duration_ = settings.duration;
  46343. this.mediaSource_ = settings.mediaSource;
  46344. this.vhs_ = settings.vhs;
  46345. this.loaderType_ = settings.loaderType;
  46346. this.currentMediaInfo_ = void 0;
  46347. this.startingMediaInfo_ = void 0;
  46348. this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  46349. this.goalBufferLength_ = settings.goalBufferLength;
  46350. this.sourceType_ = settings.sourceType;
  46351. this.sourceUpdater_ = settings.sourceUpdater;
  46352. this.inbandTextTracks_ = settings.inbandTextTracks;
  46353. this.state_ = 'INIT';
  46354. this.timelineChangeController_ = settings.timelineChangeController;
  46355. this.shouldSaveSegmentTimingInfo_ = true;
  46356. this.parse708captions_ = settings.parse708captions;
  46357. this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  46358. this.captionServices_ = settings.captionServices;
  46359. this.exactManifestTimings = settings.exactManifestTimings; // private instance variables
  46360. this.checkBufferTimeout_ = null;
  46361. this.error_ = void 0;
  46362. this.currentTimeline_ = -1;
  46363. this.pendingSegment_ = null;
  46364. this.xhrOptions_ = null;
  46365. this.pendingSegments_ = [];
  46366. this.audioDisabled_ = false;
  46367. this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  46368. this.gopBuffer_ = [];
  46369. this.timeMapping_ = 0;
  46370. this.safeAppend_ = videojs.browser.IE_VERSION >= 11;
  46371. this.appendInitSegment_ = {
  46372. audio: true,
  46373. video: true
  46374. };
  46375. this.playlistOfLastInitSegment_ = {
  46376. audio: null,
  46377. video: null
  46378. };
  46379. this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  46380. // information yet to start the loading process (e.g., if the audio loader wants to
  46381. // load a segment from the next timeline but the main loader hasn't yet crossed that
  46382. // timeline), then the load call will be added to the queue until it is ready to be
  46383. // processed.
  46384. this.loadQueue_ = [];
  46385. this.metadataQueue_ = {
  46386. id3: [],
  46387. caption: []
  46388. };
  46389. this.waitingOnRemove_ = false;
  46390. this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  46391. this.activeInitSegmentId_ = null;
  46392. this.initSegments_ = {}; // HLSe playback
  46393. this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  46394. this.keyCache_ = {};
  46395. this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  46396. // between a time in the display time and a segment index within
  46397. // a playlist
  46398. this.syncController_ = settings.syncController;
  46399. this.syncPoint_ = {
  46400. segmentIndex: 0,
  46401. time: 0
  46402. };
  46403. this.transmuxer_ = this.createTransmuxer_();
  46404. this.triggerSyncInfoUpdate_ = () => this.trigger('syncinfoupdate');
  46405. this.syncController_.on('syncinfoupdate', this.triggerSyncInfoUpdate_);
  46406. this.mediaSource_.addEventListener('sourceopen', () => {
  46407. if (!this.isEndOfStream_()) {
  46408. this.ended_ = false;
  46409. }
  46410. }); // ...for determining the fetch location
  46411. this.fetchAtBuffer_ = false;
  46412. this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);
  46413. Object.defineProperty(this, 'state', {
  46414. get() {
  46415. return this.state_;
  46416. },
  46417. set(newState) {
  46418. if (newState !== this.state_) {
  46419. this.logger_(`${this.state_} -> ${newState}`);
  46420. this.state_ = newState;
  46421. this.trigger('statechange');
  46422. }
  46423. }
  46424. });
  46425. this.sourceUpdater_.on('ready', () => {
  46426. if (this.hasEnoughInfoToAppend_()) {
  46427. this.processCallQueue_();
  46428. }
  46429. }); // Only the main loader needs to listen for pending timeline changes, as the main
  46430. // loader should wait for audio to be ready to change its timeline so that both main
  46431. // and audio timelines change together. For more details, see the
  46432. // shouldWaitForTimelineChange function.
  46433. if (this.loaderType_ === 'main') {
  46434. this.timelineChangeController_.on('pendingtimelinechange', () => {
  46435. if (this.hasEnoughInfoToAppend_()) {
  46436. this.processCallQueue_();
  46437. }
  46438. });
  46439. } // The main loader only listens on pending timeline changes, but the audio loader,
  46440. // since its loads follow main, needs to listen on timeline changes. For more details,
  46441. // see the shouldWaitForTimelineChange function.
  46442. if (this.loaderType_ === 'audio') {
  46443. this.timelineChangeController_.on('timelinechange', () => {
  46444. if (this.hasEnoughInfoToLoad_()) {
  46445. this.processLoadQueue_();
  46446. }
  46447. if (this.hasEnoughInfoToAppend_()) {
  46448. this.processCallQueue_();
  46449. }
  46450. });
  46451. }
  46452. }
  46453. createTransmuxer_() {
  46454. return segmentTransmuxer.createTransmuxer({
  46455. remux: false,
  46456. alignGopsAtEnd: this.safeAppend_,
  46457. keepOriginalTimestamps: true,
  46458. parse708captions: this.parse708captions_,
  46459. captionServices: this.captionServices_
  46460. });
  46461. }
  46462. /**
  46463. * reset all of our media stats
  46464. *
  46465. * @private
  46466. */
  46467. resetStats_() {
  46468. this.mediaBytesTransferred = 0;
  46469. this.mediaRequests = 0;
  46470. this.mediaRequestsAborted = 0;
  46471. this.mediaRequestsTimedout = 0;
  46472. this.mediaRequestsErrored = 0;
  46473. this.mediaTransferDuration = 0;
  46474. this.mediaSecondsLoaded = 0;
  46475. this.mediaAppends = 0;
  46476. }
  46477. /**
  46478. * dispose of the SegmentLoader and reset to the default state
  46479. */
  46480. dispose() {
  46481. this.trigger('dispose');
  46482. this.state = 'DISPOSED';
  46483. this.pause();
  46484. this.abort_();
  46485. if (this.transmuxer_) {
  46486. this.transmuxer_.terminate();
  46487. }
  46488. this.resetStats_();
  46489. if (this.checkBufferTimeout_) {
  46490. window.clearTimeout(this.checkBufferTimeout_);
  46491. }
  46492. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  46493. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  46494. }
  46495. this.off();
  46496. }
  46497. setAudio(enable) {
  46498. this.audioDisabled_ = !enable;
  46499. if (enable) {
  46500. this.appendInitSegment_.audio = true;
  46501. } else {
  46502. // remove current track audio if it gets disabled
  46503. this.sourceUpdater_.removeAudio(0, this.duration_());
  46504. }
  46505. }
  46506. /**
  46507. * abort anything that is currently doing on with the SegmentLoader
  46508. * and reset to a default state
  46509. */
  46510. abort() {
  46511. if (this.state !== 'WAITING') {
  46512. if (this.pendingSegment_) {
  46513. this.pendingSegment_ = null;
  46514. }
  46515. return;
  46516. }
  46517. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  46518. // since we are no longer "waiting" on any requests. XHR callback is not always run
  46519. // when the request is aborted. This will prevent the loader from being stuck in the
  46520. // WAITING state indefinitely.
  46521. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  46522. // next segment
  46523. if (!this.paused()) {
  46524. this.monitorBuffer_();
  46525. }
  46526. }
  46527. /**
  46528. * abort all pending xhr requests and null any pending segements
  46529. *
  46530. * @private
  46531. */
  46532. abort_() {
  46533. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  46534. this.pendingSegment_.abortRequests();
  46535. } // clear out the segment being processed
  46536. this.pendingSegment_ = null;
  46537. this.callQueue_ = [];
  46538. this.loadQueue_ = [];
  46539. this.metadataQueue_.id3 = [];
  46540. this.metadataQueue_.caption = [];
  46541. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  46542. this.waitingOnRemove_ = false;
  46543. window.clearTimeout(this.quotaExceededErrorRetryTimeout_);
  46544. this.quotaExceededErrorRetryTimeout_ = null;
  46545. }
  46546. checkForAbort_(requestId) {
  46547. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  46548. // callback that happens should reset the state to READY so that loading can continue.
  46549. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  46550. this.state = 'READY';
  46551. return true;
  46552. }
  46553. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  46554. return true;
  46555. }
  46556. return false;
  46557. }
  46558. /**
  46559. * set an error on the segment loader and null out any pending segements
  46560. *
  46561. * @param {Error} error the error to set on the SegmentLoader
  46562. * @return {Error} the error that was set or that is currently set
  46563. */
  46564. error(error) {
  46565. if (typeof error !== 'undefined') {
  46566. this.logger_('error occurred:', error);
  46567. this.error_ = error;
  46568. }
  46569. this.pendingSegment_ = null;
  46570. return this.error_;
  46571. }
  46572. endOfStream() {
  46573. this.ended_ = true;
  46574. if (this.transmuxer_) {
  46575. // need to clear out any cached data to prepare for the new segment
  46576. segmentTransmuxer.reset(this.transmuxer_);
  46577. }
  46578. this.gopBuffer_.length = 0;
  46579. this.pause();
  46580. this.trigger('ended');
  46581. }
  46582. /**
  46583. * Indicates which time ranges are buffered
  46584. *
  46585. * @return {TimeRange}
  46586. * TimeRange object representing the current buffered ranges
  46587. */
  46588. buffered_() {
  46589. const trackInfo = this.getMediaInfo_();
  46590. if (!this.sourceUpdater_ || !trackInfo) {
  46591. return createTimeRanges();
  46592. }
  46593. if (this.loaderType_ === 'main') {
  46594. const {
  46595. hasAudio,
  46596. hasVideo,
  46597. isMuxed
  46598. } = trackInfo;
  46599. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  46600. return this.sourceUpdater_.buffered();
  46601. }
  46602. if (hasVideo) {
  46603. return this.sourceUpdater_.videoBuffered();
  46604. }
  46605. } // One case that can be ignored for now is audio only with alt audio,
  46606. // as we don't yet have proper support for that.
  46607. return this.sourceUpdater_.audioBuffered();
  46608. }
  46609. /**
  46610. * Gets and sets init segment for the provided map
  46611. *
  46612. * @param {Object} map
  46613. * The map object representing the init segment to get or set
  46614. * @param {boolean=} set
  46615. * If true, the init segment for the provided map should be saved
  46616. * @return {Object}
  46617. * map object for desired init segment
  46618. */
  46619. initSegmentForMap(map, set = false) {
  46620. if (!map) {
  46621. return null;
  46622. }
  46623. const id = initSegmentId(map);
  46624. let storedMap = this.initSegments_[id];
  46625. if (set && !storedMap && map.bytes) {
  46626. this.initSegments_[id] = storedMap = {
  46627. resolvedUri: map.resolvedUri,
  46628. byterange: map.byterange,
  46629. bytes: map.bytes,
  46630. tracks: map.tracks,
  46631. timescales: map.timescales
  46632. };
  46633. }
  46634. return storedMap || map;
  46635. }
  46636. /**
  46637. * Gets and sets key for the provided key
  46638. *
  46639. * @param {Object} key
  46640. * The key object representing the key to get or set
  46641. * @param {boolean=} set
  46642. * If true, the key for the provided key should be saved
  46643. * @return {Object}
  46644. * Key object for desired key
  46645. */
  46646. segmentKey(key, set = false) {
  46647. if (!key) {
  46648. return null;
  46649. }
  46650. const id = segmentKeyId(key);
  46651. let storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  46652. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  46653. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  46654. this.keyCache_[id] = storedKey = {
  46655. resolvedUri: key.resolvedUri,
  46656. bytes: key.bytes
  46657. };
  46658. }
  46659. const result = {
  46660. resolvedUri: (storedKey || key).resolvedUri
  46661. };
  46662. if (storedKey) {
  46663. result.bytes = storedKey.bytes;
  46664. }
  46665. return result;
  46666. }
  46667. /**
  46668. * Returns true if all configuration required for loading is present, otherwise false.
  46669. *
  46670. * @return {boolean} True if the all configuration is ready for loading
  46671. * @private
  46672. */
  46673. couldBeginLoading_() {
  46674. return this.playlist_ && !this.paused();
  46675. }
  46676. /**
  46677. * load a playlist and start to fill the buffer
  46678. */
  46679. load() {
  46680. // un-pause
  46681. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  46682. // specified
  46683. if (!this.playlist_) {
  46684. return;
  46685. } // if all the configuration is ready, initialize and begin loading
  46686. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  46687. return this.init_();
  46688. } // if we're in the middle of processing a segment already, don't
  46689. // kick off an additional segment request
  46690. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  46691. return;
  46692. }
  46693. this.state = 'READY';
  46694. }
  46695. /**
  46696. * Once all the starting parameters have been specified, begin
  46697. * operation. This method should only be invoked from the INIT
  46698. * state.
  46699. *
  46700. * @private
  46701. */
  46702. init_() {
  46703. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  46704. // audio data from the muxed content should be removed
  46705. this.resetEverything();
  46706. return this.monitorBuffer_();
  46707. }
  46708. /**
  46709. * set a playlist on the segment loader
  46710. *
  46711. * @param {PlaylistLoader} media the playlist to set on the segment loader
  46712. */
  46713. playlist(newPlaylist, options = {}) {
  46714. if (!newPlaylist) {
  46715. return;
  46716. }
  46717. const oldPlaylist = this.playlist_;
  46718. const segmentInfo = this.pendingSegment_;
  46719. this.playlist_ = newPlaylist;
  46720. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  46721. // is always our zero-time so force a sync update each time the playlist
  46722. // is refreshed from the server
  46723. //
  46724. // Use the INIT state to determine if playback has started, as the playlist sync info
  46725. // should be fixed once requests begin (as sync points are generated based on sync
  46726. // info), but not before then.
  46727. if (this.state === 'INIT') {
  46728. newPlaylist.syncInfo = {
  46729. mediaSequence: newPlaylist.mediaSequence,
  46730. time: 0
  46731. }; // Setting the date time mapping means mapping the program date time (if available)
  46732. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  46733. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  46734. // be updated as the playlist is refreshed before the loader starts loading, the
  46735. // program date time mapping needs to be updated as well.
  46736. //
  46737. // This mapping is only done for the main loader because a program date time should
  46738. // map equivalently between playlists.
  46739. if (this.loaderType_ === 'main') {
  46740. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  46741. }
  46742. }
  46743. let oldId = null;
  46744. if (oldPlaylist) {
  46745. if (oldPlaylist.id) {
  46746. oldId = oldPlaylist.id;
  46747. } else if (oldPlaylist.uri) {
  46748. oldId = oldPlaylist.uri;
  46749. }
  46750. }
  46751. this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  46752. // in LIVE, we always want to update with new playlists (including refreshes)
  46753. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  46754. // buffering now
  46755. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  46756. return this.init_();
  46757. }
  46758. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  46759. if (this.mediaIndex !== null) {
  46760. // we must reset/resync the segment loader when we switch renditions and
  46761. // the segment loader is already synced to the previous rendition
  46762. // on playlist changes we want it to be possible to fetch
  46763. // at the buffer for vod but not for live. So we use resetLoader
  46764. // for live and resyncLoader for vod. We want this because
  46765. // if a playlist uses independent and non-independent segments/parts the
  46766. // buffer may not accurately reflect the next segment that we should try
  46767. // downloading.
  46768. if (!newPlaylist.endList) {
  46769. this.resetLoader();
  46770. } else {
  46771. this.resyncLoader();
  46772. }
  46773. }
  46774. this.currentMediaInfo_ = void 0;
  46775. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  46776. return;
  46777. } // we reloaded the same playlist so we are in a live scenario
  46778. // and we will likely need to adjust the mediaIndex
  46779. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  46780. this.logger_(`live window shift [${mediaSequenceDiff}]`); // update the mediaIndex on the SegmentLoader
  46781. // this is important because we can abort a request and this value must be
  46782. // equal to the last appended mediaIndex
  46783. if (this.mediaIndex !== null) {
  46784. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  46785. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  46786. // new playlist was incremented by 1.
  46787. if (this.mediaIndex < 0) {
  46788. this.mediaIndex = null;
  46789. this.partIndex = null;
  46790. } else {
  46791. const segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  46792. // unless parts fell off of the playlist for this segment.
  46793. // In that case we need to reset partIndex and resync
  46794. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  46795. const mediaIndex = this.mediaIndex;
  46796. this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`);
  46797. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  46798. // as the part was dropped from our current playlists segment.
  46799. // The mediaIndex will still be valid so keep that around.
  46800. this.mediaIndex = mediaIndex;
  46801. }
  46802. }
  46803. } // update the mediaIndex on the SegmentInfo object
  46804. // this is important because we will update this.mediaIndex with this value
  46805. // in `handleAppendsDone_` after the segment has been successfully appended
  46806. if (segmentInfo) {
  46807. segmentInfo.mediaIndex -= mediaSequenceDiff;
  46808. if (segmentInfo.mediaIndex < 0) {
  46809. segmentInfo.mediaIndex = null;
  46810. segmentInfo.partIndex = null;
  46811. } else {
  46812. // we need to update the referenced segment so that timing information is
  46813. // saved for the new playlist's segment, however, if the segment fell off the
  46814. // playlist, we can leave the old reference and just lose the timing info
  46815. if (segmentInfo.mediaIndex >= 0) {
  46816. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  46817. }
  46818. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  46819. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  46820. }
  46821. }
  46822. }
  46823. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  46824. }
  46825. /**
  46826. * Prevent the loader from fetching additional segments. If there
  46827. * is a segment request outstanding, it will finish processing
  46828. * before the loader halts. A segment loader can be unpaused by
  46829. * calling load().
  46830. */
  46831. pause() {
  46832. if (this.checkBufferTimeout_) {
  46833. window.clearTimeout(this.checkBufferTimeout_);
  46834. this.checkBufferTimeout_ = null;
  46835. }
  46836. }
  46837. /**
  46838. * Returns whether the segment loader is fetching additional
  46839. * segments when given the opportunity. This property can be
  46840. * modified through calls to pause() and load().
  46841. */
  46842. paused() {
  46843. return this.checkBufferTimeout_ === null;
  46844. }
  46845. /**
  46846. * Delete all the buffered data and reset the SegmentLoader
  46847. *
  46848. * @param {Function} [done] an optional callback to be executed when the remove
  46849. * operation is complete
  46850. */
  46851. resetEverything(done) {
  46852. this.ended_ = false;
  46853. this.activeInitSegmentId_ = null;
  46854. this.appendInitSegment_ = {
  46855. audio: true,
  46856. video: true
  46857. };
  46858. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  46859. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  46860. // we then clamp the value to duration if necessary.
  46861. this.remove(0, Infinity, done); // clears fmp4 captions
  46862. if (this.transmuxer_) {
  46863. this.transmuxer_.postMessage({
  46864. action: 'clearAllMp4Captions'
  46865. }); // reset the cache in the transmuxer
  46866. this.transmuxer_.postMessage({
  46867. action: 'reset'
  46868. });
  46869. }
  46870. }
  46871. /**
  46872. * Force the SegmentLoader to resync and start loading around the currentTime instead
  46873. * of starting at the end of the buffer
  46874. *
  46875. * Useful for fast quality changes
  46876. */
  46877. resetLoader() {
  46878. this.fetchAtBuffer_ = false;
  46879. this.resyncLoader();
  46880. }
  46881. /**
  46882. * Force the SegmentLoader to restart synchronization and make a conservative guess
  46883. * before returning to the simple walk-forward method
  46884. */
  46885. resyncLoader() {
  46886. if (this.transmuxer_) {
  46887. // need to clear out any cached data to prepare for the new segment
  46888. segmentTransmuxer.reset(this.transmuxer_);
  46889. }
  46890. this.mediaIndex = null;
  46891. this.partIndex = null;
  46892. this.syncPoint_ = null;
  46893. this.isPendingTimestampOffset_ = false;
  46894. this.callQueue_ = [];
  46895. this.loadQueue_ = [];
  46896. this.metadataQueue_.id3 = [];
  46897. this.metadataQueue_.caption = [];
  46898. this.abort();
  46899. if (this.transmuxer_) {
  46900. this.transmuxer_.postMessage({
  46901. action: 'clearParsedMp4Captions'
  46902. });
  46903. }
  46904. }
  46905. /**
  46906. * Remove any data in the source buffer between start and end times
  46907. *
  46908. * @param {number} start - the start time of the region to remove from the buffer
  46909. * @param {number} end - the end time of the region to remove from the buffer
  46910. * @param {Function} [done] - an optional callback to be executed when the remove
  46911. * @param {boolean} force - force all remove operations to happen
  46912. * operation is complete
  46913. */
  46914. remove(start, end, done = () => {}, force = false) {
  46915. // clamp end to duration if we need to remove everything.
  46916. // This is due to a browser bug that causes issues if we remove to Infinity.
  46917. // videojs/videojs-contrib-hls#1225
  46918. if (end === Infinity) {
  46919. end = this.duration_();
  46920. } // skip removes that would throw an error
  46921. // commonly happens during a rendition switch at the start of a video
  46922. // from start 0 to end 0
  46923. if (end <= start) {
  46924. this.logger_('skipping remove because end ${end} is <= start ${start}');
  46925. return;
  46926. }
  46927. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  46928. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  46929. return;
  46930. } // set it to one to complete this function's removes
  46931. let removesRemaining = 1;
  46932. const removeFinished = () => {
  46933. removesRemaining--;
  46934. if (removesRemaining === 0) {
  46935. done();
  46936. }
  46937. };
  46938. if (force || !this.audioDisabled_) {
  46939. removesRemaining++;
  46940. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  46941. } // While it would be better to only remove video if the main loader has video, this
  46942. // should be safe with audio only as removeVideo will call back even if there's no
  46943. // video buffer.
  46944. //
  46945. // In theory we can check to see if there's video before calling the remove, but in
  46946. // the event that we're switching between renditions and from video to audio only
  46947. // (when we add support for that), we may need to clear the video contents despite
  46948. // what the new media will contain.
  46949. if (force || this.loaderType_ === 'main') {
  46950. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  46951. removesRemaining++;
  46952. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  46953. } // remove any captions and ID3 tags
  46954. for (const track in this.inbandTextTracks_) {
  46955. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  46956. }
  46957. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  46958. removeFinished();
  46959. }
  46960. /**
  46961. * (re-)schedule monitorBufferTick_ to run as soon as possible
  46962. *
  46963. * @private
  46964. */
  46965. monitorBuffer_() {
  46966. if (this.checkBufferTimeout_) {
  46967. window.clearTimeout(this.checkBufferTimeout_);
  46968. }
  46969. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), 1);
  46970. }
  46971. /**
  46972. * As long as the SegmentLoader is in the READY state, periodically
  46973. * invoke fillBuffer_().
  46974. *
  46975. * @private
  46976. */
  46977. monitorBufferTick_() {
  46978. if (this.state === 'READY') {
  46979. this.fillBuffer_();
  46980. }
  46981. if (this.checkBufferTimeout_) {
  46982. window.clearTimeout(this.checkBufferTimeout_);
  46983. }
  46984. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  46985. }
  46986. /**
  46987. * fill the buffer with segements unless the sourceBuffers are
  46988. * currently updating
  46989. *
  46990. * Note: this function should only ever be called by monitorBuffer_
  46991. * and never directly
  46992. *
  46993. * @private
  46994. */
  46995. fillBuffer_() {
  46996. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  46997. // except when we're ready for the next segment, this check can most likely be removed
  46998. if (this.sourceUpdater_.updating()) {
  46999. return;
  47000. } // see if we need to begin loading immediately
  47001. const segmentInfo = this.chooseNextRequest_();
  47002. if (!segmentInfo) {
  47003. return;
  47004. }
  47005. if (typeof segmentInfo.timestampOffset === 'number') {
  47006. this.isPendingTimestampOffset_ = false;
  47007. this.timelineChangeController_.pendingTimelineChange({
  47008. type: this.loaderType_,
  47009. from: this.currentTimeline_,
  47010. to: segmentInfo.timeline
  47011. });
  47012. }
  47013. this.loadSegment_(segmentInfo);
  47014. }
  47015. /**
  47016. * Determines if we should call endOfStream on the media source based
  47017. * on the state of the buffer or if appened segment was the final
  47018. * segment in the playlist.
  47019. *
  47020. * @param {number} [mediaIndex] the media index of segment we last appended
  47021. * @param {Object} [playlist] a media playlist object
  47022. * @return {boolean} do we need to call endOfStream on the MediaSource
  47023. */
  47024. isEndOfStream_(mediaIndex = this.mediaIndex, playlist = this.playlist_, partIndex = this.partIndex) {
  47025. if (!playlist || !this.mediaSource_) {
  47026. return false;
  47027. }
  47028. const segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  47029. const appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  47030. const appendedLastPart = !segment || !segment.parts || partIndex + 1 === segment.parts.length; // if we've buffered to the end of the video, we need to call endOfStream
  47031. // so that MediaSources can trigger the `ended` event when it runs out of
  47032. // buffered data instead of waiting for me
  47033. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  47034. }
  47035. /**
  47036. * Determines what request should be made given current segment loader state.
  47037. *
  47038. * @return {Object} a request object that describes the segment/part to load
  47039. */
  47040. chooseNextRequest_() {
  47041. const buffered = this.buffered_();
  47042. const bufferedEnd = lastBufferedEnd(buffered) || 0;
  47043. const bufferedTime = timeAheadOf(buffered, this.currentTime_());
  47044. const preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  47045. const haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  47046. const segments = this.playlist_.segments; // return no segment if:
  47047. // 1. we don't have segments
  47048. // 2. The video has not yet played and we already downloaded a segment
  47049. // 3. we already have enough buffered time
  47050. if (!segments.length || preloaded || haveEnoughBuffer) {
  47051. return null;
  47052. }
  47053. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
  47054. const next = {
  47055. partIndex: null,
  47056. mediaIndex: null,
  47057. startOfSegment: null,
  47058. playlist: this.playlist_,
  47059. isSyncRequest: Boolean(!this.syncPoint_)
  47060. };
  47061. if (next.isSyncRequest) {
  47062. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  47063. } else if (this.mediaIndex !== null) {
  47064. const segment = segments[this.mediaIndex];
  47065. const partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  47066. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  47067. if (segment.parts && segment.parts[partIndex + 1]) {
  47068. next.mediaIndex = this.mediaIndex;
  47069. next.partIndex = partIndex + 1;
  47070. } else {
  47071. next.mediaIndex = this.mediaIndex + 1;
  47072. }
  47073. } else {
  47074. // Find the segment containing the end of the buffer or current time.
  47075. const {
  47076. segmentIndex,
  47077. startTime,
  47078. partIndex
  47079. } = Playlist.getMediaInfoForTime({
  47080. exactManifestTimings: this.exactManifestTimings,
  47081. playlist: this.playlist_,
  47082. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  47083. startingPartIndex: this.syncPoint_.partIndex,
  47084. startingSegmentIndex: this.syncPoint_.segmentIndex,
  47085. startTime: this.syncPoint_.time
  47086. });
  47087. next.getMediaInfoForTime = this.fetchAtBuffer_ ? `bufferedEnd ${bufferedEnd}` : `currentTime ${this.currentTime_()}`;
  47088. next.mediaIndex = segmentIndex;
  47089. next.startOfSegment = startTime;
  47090. next.partIndex = partIndex;
  47091. }
  47092. const nextSegment = segments[next.mediaIndex];
  47093. let nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  47094. // the next partIndex is invalid do not choose a next segment.
  47095. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  47096. return null;
  47097. } // if the next segment has parts, and we don't have a partIndex.
  47098. // Set partIndex to 0
  47099. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  47100. next.partIndex = 0;
  47101. nextPart = nextSegment.parts[0];
  47102. } // if we have no buffered data then we need to make sure
  47103. // that the next part we append is "independent" if possible.
  47104. // So we check if the previous part is independent, and request
  47105. // it if it is.
  47106. if (!bufferedTime && nextPart && !nextPart.independent) {
  47107. if (next.partIndex === 0) {
  47108. const lastSegment = segments[next.mediaIndex - 1];
  47109. const lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  47110. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  47111. next.mediaIndex -= 1;
  47112. next.partIndex = lastSegment.parts.length - 1;
  47113. next.independent = 'previous segment';
  47114. }
  47115. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  47116. next.partIndex -= 1;
  47117. next.independent = 'previous part';
  47118. }
  47119. }
  47120. const ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  47121. // 1. this is the last segment in the playlist
  47122. // 2. end of stream has been called on the media source already
  47123. // 3. the player is not seeking
  47124. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  47125. return null;
  47126. }
  47127. return this.generateSegmentInfo_(next);
  47128. }
  47129. generateSegmentInfo_(options) {
  47130. const {
  47131. independent,
  47132. playlist,
  47133. mediaIndex,
  47134. startOfSegment,
  47135. isSyncRequest,
  47136. partIndex,
  47137. forceTimestampOffset,
  47138. getMediaInfoForTime
  47139. } = options;
  47140. const segment = playlist.segments[mediaIndex];
  47141. const part = typeof partIndex === 'number' && segment.parts[partIndex];
  47142. const segmentInfo = {
  47143. requestId: 'segment-loader-' + Math.random(),
  47144. // resolve the segment URL relative to the playlist
  47145. uri: part && part.resolvedUri || segment.resolvedUri,
  47146. // the segment's mediaIndex at the time it was requested
  47147. mediaIndex,
  47148. partIndex: part ? partIndex : null,
  47149. // whether or not to update the SegmentLoader's state with this
  47150. // segment's mediaIndex
  47151. isSyncRequest,
  47152. startOfSegment,
  47153. // the segment's playlist
  47154. playlist,
  47155. // unencrypted bytes of the segment
  47156. bytes: null,
  47157. // when a key is defined for this segment, the encrypted bytes
  47158. encryptedBytes: null,
  47159. // The target timestampOffset for this segment when we append it
  47160. // to the source buffer
  47161. timestampOffset: null,
  47162. // The timeline that the segment is in
  47163. timeline: segment.timeline,
  47164. // The expected duration of the segment in seconds
  47165. duration: part && part.duration || segment.duration,
  47166. // retain the segment in case the playlist updates while doing an async process
  47167. segment,
  47168. part,
  47169. byteLength: 0,
  47170. transmuxer: this.transmuxer_,
  47171. // type of getMediaInfoForTime that was used to get this segment
  47172. getMediaInfoForTime,
  47173. independent
  47174. };
  47175. const overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  47176. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  47177. segmentTimeline: segment.timeline,
  47178. currentTimeline: this.currentTimeline_,
  47179. startOfSegment,
  47180. buffered: this.buffered_(),
  47181. overrideCheck
  47182. });
  47183. const audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  47184. if (typeof audioBufferedEnd === 'number') {
  47185. // since the transmuxer is using the actual timing values, but the buffer is
  47186. // adjusted by the timestamp offset, we must adjust the value here
  47187. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  47188. }
  47189. if (this.sourceUpdater_.videoBuffered().length) {
  47190. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_,
  47191. // since the transmuxer is using the actual timing values, but the time is
  47192. // adjusted by the timestmap offset, we must adjust the value here
  47193. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  47194. }
  47195. return segmentInfo;
  47196. } // get the timestampoffset for a segment,
  47197. // added so that vtt segment loader can override and prevent
  47198. // adding timestamp offsets.
  47199. timestampOffsetForSegment_(options) {
  47200. return timestampOffsetForSegment(options);
  47201. }
  47202. /**
  47203. * Determines if the network has enough bandwidth to complete the current segment
  47204. * request in a timely manner. If not, the request will be aborted early and bandwidth
  47205. * updated to trigger a playlist switch.
  47206. *
  47207. * @param {Object} stats
  47208. * Object containing stats about the request timing and size
  47209. * @private
  47210. */
  47211. earlyAbortWhenNeeded_(stats) {
  47212. if (this.vhs_.tech_.paused() ||
  47213. // Don't abort if the current playlist is on the lowestEnabledRendition
  47214. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  47215. // the lowestEnabledRendition.
  47216. !this.xhrOptions_.timeout ||
  47217. // Don't abort if we have no bandwidth information to estimate segment sizes
  47218. !this.playlist_.attributes.BANDWIDTH) {
  47219. return;
  47220. } // Wait at least 1 second since the first byte of data has been received before
  47221. // using the calculated bandwidth from the progress event to allow the bitrate
  47222. // to stabilize
  47223. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  47224. return;
  47225. }
  47226. const currentTime = this.currentTime_();
  47227. const measuredBandwidth = stats.bandwidth;
  47228. const segmentDuration = this.pendingSegment_.duration;
  47229. const requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  47230. // if we are only left with less than 1 second when the request completes.
  47231. // A negative timeUntilRebuffering indicates we are already rebuffering
  47232. const timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  47233. // is larger than the estimated time until the player runs out of forward buffer
  47234. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  47235. return;
  47236. }
  47237. const switchCandidate = minRebufferMaxBandwidthSelector({
  47238. main: this.vhs_.playlists.main,
  47239. currentTime,
  47240. bandwidth: measuredBandwidth,
  47241. duration: this.duration_(),
  47242. segmentDuration,
  47243. timeUntilRebuffer: timeUntilRebuffer$1,
  47244. currentTimeline: this.currentTimeline_,
  47245. syncController: this.syncController_
  47246. });
  47247. if (!switchCandidate) {
  47248. return;
  47249. }
  47250. const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  47251. const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  47252. let minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  47253. // potential round trip time of the new request so that we are not too aggressive
  47254. // with switching to a playlist that might save us a fraction of a second.
  47255. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  47256. minimumTimeSaving = 1;
  47257. }
  47258. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  47259. return;
  47260. } // set the bandwidth to that of the desired playlist being sure to scale by
  47261. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  47262. // don't trigger a bandwidthupdate as the bandwidth is artifial
  47263. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  47264. this.trigger('earlyabort');
  47265. }
  47266. handleAbort_(segmentInfo) {
  47267. this.logger_(`Aborting ${segmentInfoString(segmentInfo)}`);
  47268. this.mediaRequestsAborted += 1;
  47269. }
  47270. /**
  47271. * XHR `progress` event handler
  47272. *
  47273. * @param {Event}
  47274. * The XHR `progress` event
  47275. * @param {Object} simpleSegment
  47276. * A simplified segment object copy
  47277. * @private
  47278. */
  47279. handleProgress_(event, simpleSegment) {
  47280. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  47281. if (this.checkForAbort_(simpleSegment.requestId)) {
  47282. return;
  47283. }
  47284. this.trigger('progress');
  47285. }
  47286. handleTrackInfo_(simpleSegment, trackInfo) {
  47287. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  47288. if (this.checkForAbort_(simpleSegment.requestId)) {
  47289. return;
  47290. }
  47291. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  47292. return;
  47293. }
  47294. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  47295. // Guard against cases where we're not getting track info at all until we are
  47296. // certain that all streams will provide it.
  47297. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  47298. this.appendInitSegment_ = {
  47299. audio: true,
  47300. video: true
  47301. };
  47302. this.startingMediaInfo_ = trackInfo;
  47303. this.currentMediaInfo_ = trackInfo;
  47304. this.logger_('trackinfo update', trackInfo);
  47305. this.trigger('trackinfo');
  47306. } // trackinfo may cause an abort if the trackinfo
  47307. // causes a codec change to an unsupported codec.
  47308. if (this.checkForAbort_(simpleSegment.requestId)) {
  47309. return;
  47310. } // set trackinfo on the pending segment so that
  47311. // it can append.
  47312. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  47313. if (this.hasEnoughInfoToAppend_()) {
  47314. this.processCallQueue_();
  47315. }
  47316. }
  47317. handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  47318. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  47319. if (this.checkForAbort_(simpleSegment.requestId)) {
  47320. return;
  47321. }
  47322. const segmentInfo = this.pendingSegment_;
  47323. const timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  47324. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  47325. segmentInfo[timingInfoProperty][timeType] = time;
  47326. this.logger_(`timinginfo: ${mediaType} - ${timeType} - ${time}`); // check if any calls were waiting on the timing info
  47327. if (this.hasEnoughInfoToAppend_()) {
  47328. this.processCallQueue_();
  47329. }
  47330. }
  47331. handleCaptions_(simpleSegment, captionData) {
  47332. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  47333. if (this.checkForAbort_(simpleSegment.requestId)) {
  47334. return;
  47335. } // This could only happen with fmp4 segments, but
  47336. // should still not happen in general
  47337. if (captionData.length === 0) {
  47338. this.logger_('SegmentLoader received no captions from a caption event');
  47339. return;
  47340. }
  47341. const segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  47342. // can be adjusted by the timestamp offset
  47343. if (!segmentInfo.hasAppendedData_) {
  47344. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  47345. return;
  47346. }
  47347. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  47348. const captionTracks = {}; // get total start/end and captions for each track/stream
  47349. captionData.forEach(caption => {
  47350. // caption.stream is actually a track name...
  47351. // set to the existing values in tracks or default values
  47352. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  47353. // Infinity, as any other value will be less than this
  47354. startTime: Infinity,
  47355. captions: [],
  47356. // 0 as an other value will be more than this
  47357. endTime: 0
  47358. };
  47359. const captionTrack = captionTracks[caption.stream];
  47360. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  47361. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  47362. captionTrack.captions.push(caption);
  47363. });
  47364. Object.keys(captionTracks).forEach(trackName => {
  47365. const {
  47366. startTime,
  47367. endTime,
  47368. captions
  47369. } = captionTracks[trackName];
  47370. const inbandTextTracks = this.inbandTextTracks_;
  47371. this.logger_(`adding cues from ${startTime} -> ${endTime} for ${trackName}`);
  47372. createCaptionsTrackIfNotExists(inbandTextTracks, this.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  47373. // We do this because a rendition change that also changes the timescale for captions
  47374. // will result in captions being re-parsed for certain segments. If we add them again
  47375. // without clearing we will have two of the same captions visible.
  47376. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  47377. addCaptionData({
  47378. captionArray: captions,
  47379. inbandTextTracks,
  47380. timestampOffset
  47381. });
  47382. }); // Reset stored captions since we added parsed
  47383. // captions to a text track at this point
  47384. if (this.transmuxer_) {
  47385. this.transmuxer_.postMessage({
  47386. action: 'clearParsedMp4Captions'
  47387. });
  47388. }
  47389. }
  47390. handleId3_(simpleSegment, id3Frames, dispatchType) {
  47391. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  47392. if (this.checkForAbort_(simpleSegment.requestId)) {
  47393. return;
  47394. }
  47395. const segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  47396. if (!segmentInfo.hasAppendedData_) {
  47397. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  47398. return;
  47399. }
  47400. const 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
  47401. // audio/video source with a metadata track, and an alt audio with a metadata track.
  47402. // However, this probably won't happen, and if it does it can be handled then.
  47403. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
  47404. addMetadata({
  47405. inbandTextTracks: this.inbandTextTracks_,
  47406. metadataArray: id3Frames,
  47407. timestampOffset,
  47408. videoDuration: this.duration_()
  47409. });
  47410. }
  47411. processMetadataQueue_() {
  47412. this.metadataQueue_.id3.forEach(fn => fn());
  47413. this.metadataQueue_.caption.forEach(fn => fn());
  47414. this.metadataQueue_.id3 = [];
  47415. this.metadataQueue_.caption = [];
  47416. }
  47417. processCallQueue_() {
  47418. const callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  47419. // functions may check the length of the load queue and default to pushing themselves
  47420. // back onto the queue.
  47421. this.callQueue_ = [];
  47422. callQueue.forEach(fun => fun());
  47423. }
  47424. processLoadQueue_() {
  47425. const loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  47426. // functions may check the length of the load queue and default to pushing themselves
  47427. // back onto the queue.
  47428. this.loadQueue_ = [];
  47429. loadQueue.forEach(fun => fun());
  47430. }
  47431. /**
  47432. * Determines whether the loader has enough info to load the next segment.
  47433. *
  47434. * @return {boolean}
  47435. * Whether or not the loader has enough info to load the next segment
  47436. */
  47437. hasEnoughInfoToLoad_() {
  47438. // Since primary timing goes by video, only the audio loader potentially needs to wait
  47439. // to load.
  47440. if (this.loaderType_ !== 'audio') {
  47441. return true;
  47442. }
  47443. const segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  47444. // enough info to load.
  47445. if (!segmentInfo) {
  47446. return false;
  47447. } // The first segment can and should be loaded immediately so that source buffers are
  47448. // created together (before appending). Source buffer creation uses the presence of
  47449. // audio and video data to determine whether to create audio/video source buffers, and
  47450. // uses processed (transmuxed or parsed) media to determine the types required.
  47451. if (!this.getCurrentMediaInfo_()) {
  47452. return true;
  47453. }
  47454. if (
  47455. // Technically, instead of waiting to load a segment on timeline changes, a segment
  47456. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  47457. // But in practice, there are a few reasons why it is better to wait until a loader
  47458. // is ready to append that segment before requesting and downloading:
  47459. //
  47460. // 1. Because audio and main loaders cross discontinuities together, if this loader
  47461. // is waiting for the other to catch up, then instead of requesting another
  47462. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  47463. // allotted to the loader currently behind.
  47464. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  47465. // is ready to be processed or not, isolating the queueing behavior to the loader.
  47466. // 3. The audio loader bases some of its segment properties on timing information
  47467. // provided by the main loader, meaning that, if the logic for waiting on
  47468. // processing was in media-segment-request, then it would also need to know how
  47469. // to re-generate the segment information after the main loader caught up.
  47470. shouldWaitForTimelineChange({
  47471. timelineChangeController: this.timelineChangeController_,
  47472. currentTimeline: this.currentTimeline_,
  47473. segmentTimeline: segmentInfo.timeline,
  47474. loaderType: this.loaderType_,
  47475. audioDisabled: this.audioDisabled_
  47476. })) {
  47477. return false;
  47478. }
  47479. return true;
  47480. }
  47481. getCurrentMediaInfo_(segmentInfo = this.pendingSegment_) {
  47482. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  47483. }
  47484. getMediaInfo_(segmentInfo = this.pendingSegment_) {
  47485. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  47486. }
  47487. getPendingSegmentPlaylist() {
  47488. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  47489. }
  47490. hasEnoughInfoToAppend_() {
  47491. if (!this.sourceUpdater_.ready()) {
  47492. return false;
  47493. } // If content needs to be removed or the loader is waiting on an append reattempt,
  47494. // then no additional content should be appended until the prior append is resolved.
  47495. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  47496. return false;
  47497. }
  47498. const segmentInfo = this.pendingSegment_;
  47499. const trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  47500. // we do not have information on this specific
  47501. // segment yet
  47502. if (!segmentInfo || !trackInfo) {
  47503. return false;
  47504. }
  47505. const {
  47506. hasAudio,
  47507. hasVideo,
  47508. isMuxed
  47509. } = trackInfo;
  47510. if (hasVideo && !segmentInfo.videoTimingInfo) {
  47511. return false;
  47512. } // muxed content only relies on video timing information for now.
  47513. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  47514. return false;
  47515. }
  47516. if (shouldWaitForTimelineChange({
  47517. timelineChangeController: this.timelineChangeController_,
  47518. currentTimeline: this.currentTimeline_,
  47519. segmentTimeline: segmentInfo.timeline,
  47520. loaderType: this.loaderType_,
  47521. audioDisabled: this.audioDisabled_
  47522. })) {
  47523. return false;
  47524. }
  47525. return true;
  47526. }
  47527. handleData_(simpleSegment, result) {
  47528. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  47529. if (this.checkForAbort_(simpleSegment.requestId)) {
  47530. return;
  47531. } // If there's anything in the call queue, then this data came later and should be
  47532. // executed after the calls currently queued.
  47533. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  47534. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  47535. return;
  47536. }
  47537. const segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  47538. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  47539. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  47540. // logic may change behavior depending on the state, and changing state too early may
  47541. // inflate our estimates of bandwidth. In the future this should be re-examined to
  47542. // note more granular states.
  47543. // don't process and append data if the mediaSource is closed
  47544. if (this.mediaSource_.readyState === 'closed') {
  47545. return;
  47546. } // if this request included an initialization segment, save that data
  47547. // to the initSegment cache
  47548. if (simpleSegment.map) {
  47549. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  47550. segmentInfo.segment.map = simpleSegment.map;
  47551. } // if this request included a segment key, save that data in the cache
  47552. if (simpleSegment.key) {
  47553. this.segmentKey(simpleSegment.key, true);
  47554. }
  47555. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  47556. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  47557. if (segmentInfo.isFmp4) {
  47558. this.trigger('fmp4');
  47559. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  47560. } else {
  47561. const trackInfo = this.getCurrentMediaInfo_();
  47562. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  47563. let firstVideoFrameTimeForData;
  47564. if (useVideoTimingInfo) {
  47565. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  47566. } // Segment loader knows more about segment timing than the transmuxer (in certain
  47567. // aspects), so make any changes required for a more accurate start time.
  47568. // Don't set the end time yet, as the segment may not be finished processing.
  47569. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  47570. currentStart: segmentInfo.timingInfo.start,
  47571. playlist: segmentInfo.playlist,
  47572. mediaIndex: segmentInfo.mediaIndex,
  47573. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  47574. useVideoTimingInfo,
  47575. firstVideoFrameTimeForData,
  47576. videoTimingInfo: segmentInfo.videoTimingInfo,
  47577. audioTimingInfo: segmentInfo.audioTimingInfo
  47578. });
  47579. } // Init segments for audio and video only need to be appended in certain cases. Now
  47580. // that data is about to be appended, we can check the final cases to determine
  47581. // whether we should append an init segment.
  47582. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  47583. // as we use the start of the segment to offset the best guess (playlist provided)
  47584. // timestamp offset.
  47585. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  47586. // be appended or not.
  47587. if (segmentInfo.isSyncRequest) {
  47588. // first save/update our timing info for this segment.
  47589. // this is what allows us to choose an accurate segment
  47590. // and the main reason we make a sync request.
  47591. this.updateTimingInfoEnd_(segmentInfo);
  47592. this.syncController_.saveSegmentTimingInfo({
  47593. segmentInfo,
  47594. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  47595. });
  47596. const next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  47597. // after taking into account its timing info, do not append it.
  47598. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  47599. this.logger_('sync segment was incorrect, not appending');
  47600. return;
  47601. } // otherwise append it like any other segment as our guess was correct.
  47602. this.logger_('sync segment was correct, appending');
  47603. } // Save some state so that in the future anything waiting on first append (and/or
  47604. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  47605. // we need some notion of whether the timestamp offset or other relevant information
  47606. // has had a chance to be set.
  47607. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  47608. this.processMetadataQueue_();
  47609. this.appendData_(segmentInfo, result);
  47610. }
  47611. updateAppendInitSegmentStatus(segmentInfo, type) {
  47612. // alt audio doesn't manage timestamp offset
  47613. if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' &&
  47614. // in the case that we're handling partial data, we don't want to append an init
  47615. // segment for each chunk
  47616. !segmentInfo.changedTimestampOffset) {
  47617. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  47618. // append init segments
  47619. this.appendInitSegment_ = {
  47620. audio: true,
  47621. video: true
  47622. };
  47623. }
  47624. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  47625. // make sure we append init segment on playlist changes, in case the media config
  47626. // changed
  47627. this.appendInitSegment_[type] = true;
  47628. }
  47629. }
  47630. getInitSegmentAndUpdateState_({
  47631. type,
  47632. initSegment,
  47633. map,
  47634. playlist
  47635. }) {
  47636. // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  47637. // (Section 3) required to parse the applicable Media Segments. It applies to every
  47638. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  47639. // or until the end of the playlist."
  47640. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  47641. if (map) {
  47642. const id = initSegmentId(map);
  47643. if (this.activeInitSegmentId_ === id) {
  47644. // don't need to re-append the init segment if the ID matches
  47645. return null;
  47646. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  47647. // obtained) init segment
  47648. //
  47649. // this also caches the init segment for later use
  47650. initSegment = this.initSegmentForMap(map, true).bytes;
  47651. this.activeInitSegmentId_ = id;
  47652. } // We used to always prepend init segments for video, however, that shouldn't be
  47653. // necessary. Instead, we should only append on changes, similar to what we've always
  47654. // done for audio. This is more important (though may not be that important) for
  47655. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  47656. // appends.
  47657. if (initSegment && this.appendInitSegment_[type]) {
  47658. // Make sure we track the playlist that we last used for the init segment, so that
  47659. // we can re-append the init segment in the event that we get data from a new
  47660. // playlist. Discontinuities and track changes are handled in other sections.
  47661. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  47662. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  47663. // we are appending the muxer init segment
  47664. this.activeInitSegmentId_ = null;
  47665. return initSegment;
  47666. }
  47667. return null;
  47668. }
  47669. handleQuotaExceededError_({
  47670. segmentInfo,
  47671. type,
  47672. bytes
  47673. }, error) {
  47674. const audioBuffered = this.sourceUpdater_.audioBuffered();
  47675. const videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  47676. // should be cleared out during the buffer removals. However, log in case it helps
  47677. // debug.
  47678. if (audioBuffered.length > 1) {
  47679. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  47680. }
  47681. if (videoBuffered.length > 1) {
  47682. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  47683. }
  47684. const audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  47685. const audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  47686. const videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  47687. const videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  47688. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  47689. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  47690. // allow for appends of segments this size). In the future, it may be possible to
  47691. // split up the segment and append in pieces, but for now, error out this playlist
  47692. // in an attempt to switch to a more manageable rendition.
  47693. 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(', ')}, `);
  47694. this.error({
  47695. message: 'Quota exceeded error with append of a single segment of content',
  47696. excludeUntil: Infinity
  47697. });
  47698. this.trigger('error');
  47699. return;
  47700. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  47701. // that the segment-loader should block on future events until this one is handled, so
  47702. // that it doesn't keep moving onto further segments. Adding the call to the call
  47703. // queue will prevent further appends until waitingOnRemove_ and
  47704. // quotaExceededErrorRetryTimeout_ are cleared.
  47705. //
  47706. // Note that this will only block the current loader. In the case of demuxed content,
  47707. // the other load may keep filling as fast as possible. In practice, this should be
  47708. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  47709. // source buffer, or video fills without enough room for audio to append (and without
  47710. // the availability of clearing out seconds of back buffer to make room for audio).
  47711. // But it might still be good to handle this case in the future as a TODO.
  47712. this.waitingOnRemove_ = true;
  47713. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  47714. segmentInfo,
  47715. type,
  47716. bytes
  47717. }));
  47718. const currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  47719. // before retrying.
  47720. const timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  47721. this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${timeToRemoveUntil}`);
  47722. this.remove(0, timeToRemoveUntil, () => {
  47723. this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${MIN_BACK_BUFFER}s`);
  47724. this.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  47725. // attempts (since we can't clear less than the minimum)
  47726. this.quotaExceededErrorRetryTimeout_ = window.setTimeout(() => {
  47727. this.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  47728. this.quotaExceededErrorRetryTimeout_ = null;
  47729. this.processCallQueue_();
  47730. }, MIN_BACK_BUFFER * 1000);
  47731. }, true);
  47732. }
  47733. handleAppendError_({
  47734. segmentInfo,
  47735. type,
  47736. bytes
  47737. }, error) {
  47738. // if there's no error, nothing to do
  47739. if (!error) {
  47740. return;
  47741. }
  47742. if (error.code === QUOTA_EXCEEDED_ERR) {
  47743. this.handleQuotaExceededError_({
  47744. segmentInfo,
  47745. type,
  47746. bytes
  47747. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  47748. // to trigger an append error.
  47749. return;
  47750. }
  47751. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  47752. 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.
  47753. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  47754. //
  47755. // Trigger a special error so that it can be handled separately from normal,
  47756. // recoverable errors.
  47757. this.trigger('appenderror');
  47758. }
  47759. appendToSourceBuffer_({
  47760. segmentInfo,
  47761. type,
  47762. initSegment,
  47763. data,
  47764. bytes
  47765. }) {
  47766. // If this is a re-append, bytes were already created and don't need to be recreated
  47767. if (!bytes) {
  47768. const segments = [data];
  47769. let byteLength = data.byteLength;
  47770. if (initSegment) {
  47771. // if the media initialization segment is changing, append it before the content
  47772. // segment
  47773. segments.unshift(initSegment);
  47774. byteLength += initSegment.byteLength;
  47775. } // Technically we should be OK appending the init segment separately, however, we
  47776. // haven't yet tested that, and prepending is how we have always done things.
  47777. bytes = concatSegments({
  47778. bytes: byteLength,
  47779. segments
  47780. });
  47781. }
  47782. this.sourceUpdater_.appendBuffer({
  47783. segmentInfo,
  47784. type,
  47785. bytes
  47786. }, this.handleAppendError_.bind(this, {
  47787. segmentInfo,
  47788. type,
  47789. bytes
  47790. }));
  47791. }
  47792. handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  47793. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  47794. return;
  47795. }
  47796. const segment = this.pendingSegment_.segment;
  47797. const timingInfoProperty = `${type}TimingInfo`;
  47798. if (!segment[timingInfoProperty]) {
  47799. segment[timingInfoProperty] = {};
  47800. }
  47801. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  47802. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  47803. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  47804. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  47805. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  47806. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  47807. }
  47808. appendData_(segmentInfo, result) {
  47809. const {
  47810. type,
  47811. data
  47812. } = result;
  47813. if (!data || !data.byteLength) {
  47814. return;
  47815. }
  47816. if (type === 'audio' && this.audioDisabled_) {
  47817. return;
  47818. }
  47819. const initSegment = this.getInitSegmentAndUpdateState_({
  47820. type,
  47821. initSegment: result.initSegment,
  47822. playlist: segmentInfo.playlist,
  47823. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  47824. });
  47825. this.appendToSourceBuffer_({
  47826. segmentInfo,
  47827. type,
  47828. initSegment,
  47829. data
  47830. });
  47831. }
  47832. /**
  47833. * load a specific segment from a request into the buffer
  47834. *
  47835. * @private
  47836. */
  47837. loadSegment_(segmentInfo) {
  47838. this.state = 'WAITING';
  47839. this.pendingSegment_ = segmentInfo;
  47840. this.trimBackBuffer_(segmentInfo);
  47841. if (typeof segmentInfo.timestampOffset === 'number') {
  47842. if (this.transmuxer_) {
  47843. this.transmuxer_.postMessage({
  47844. action: 'clearAllMp4Captions'
  47845. });
  47846. }
  47847. }
  47848. if (!this.hasEnoughInfoToLoad_()) {
  47849. this.loadQueue_.push(() => {
  47850. // regenerate the audioAppendStart, timestampOffset, etc as they
  47851. // may have changed since this function was added to the queue.
  47852. const options = _extends$1({}, segmentInfo, {
  47853. forceTimestampOffset: true
  47854. });
  47855. _extends$1(segmentInfo, this.generateSegmentInfo_(options));
  47856. this.isPendingTimestampOffset_ = false;
  47857. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  47858. });
  47859. return;
  47860. }
  47861. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  47862. }
  47863. updateTransmuxerAndRequestSegment_(segmentInfo) {
  47864. // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  47865. // the transmuxer still needs to be updated before then.
  47866. //
  47867. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  47868. // offset must be passed to the transmuxer for stream correcting adjustments.
  47869. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  47870. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  47871. segmentInfo.gopsToAlignWith = [];
  47872. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  47873. this.transmuxer_.postMessage({
  47874. action: 'reset'
  47875. });
  47876. this.transmuxer_.postMessage({
  47877. action: 'setTimestampOffset',
  47878. timestampOffset: segmentInfo.timestampOffset
  47879. });
  47880. }
  47881. const simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  47882. const isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  47883. const isWalkingForward = this.mediaIndex !== null;
  47884. const isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ &&
  47885. // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  47886. // the first timeline
  47887. segmentInfo.timeline > 0;
  47888. const isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  47889. 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),
  47890. // then this init segment has never been seen before and should be appended.
  47891. //
  47892. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  47893. // both to true and leave the decision of whether to append the init segment to append time.
  47894. if (simpleSegment.map && !simpleSegment.map.bytes) {
  47895. this.logger_('going to request init segment.');
  47896. this.appendInitSegment_ = {
  47897. video: true,
  47898. audio: true
  47899. };
  47900. }
  47901. segmentInfo.abortRequests = mediaSegmentRequest({
  47902. xhr: this.vhs_.xhr,
  47903. xhrOptions: this.xhrOptions_,
  47904. decryptionWorker: this.decrypter_,
  47905. segment: simpleSegment,
  47906. abortFn: this.handleAbort_.bind(this, segmentInfo),
  47907. progressFn: this.handleProgress_.bind(this),
  47908. trackInfoFn: this.handleTrackInfo_.bind(this),
  47909. timingInfoFn: this.handleTimingInfo_.bind(this),
  47910. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  47911. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  47912. captionsFn: this.handleCaptions_.bind(this),
  47913. isEndOfTimeline,
  47914. endedTimelineFn: () => {
  47915. this.logger_('received endedtimeline callback');
  47916. },
  47917. id3Fn: this.handleId3_.bind(this),
  47918. dataFn: this.handleData_.bind(this),
  47919. doneFn: this.segmentRequestFinished_.bind(this),
  47920. onTransmuxerLog: ({
  47921. message,
  47922. level,
  47923. stream
  47924. }) => {
  47925. this.logger_(`${segmentInfoString(segmentInfo)} logged from transmuxer stream ${stream} as a ${level}: ${message}`);
  47926. }
  47927. });
  47928. }
  47929. /**
  47930. * trim the back buffer so that we don't have too much data
  47931. * in the source buffer
  47932. *
  47933. * @private
  47934. *
  47935. * @param {Object} segmentInfo - the current segment
  47936. */
  47937. trimBackBuffer_(segmentInfo) {
  47938. const removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  47939. // buffer and a very conservative "garbage collector"
  47940. // We manually clear out the old buffer to ensure
  47941. // we don't trigger the QuotaExceeded error
  47942. // on the source buffer during subsequent appends
  47943. if (removeToTime > 0) {
  47944. this.remove(0, removeToTime);
  47945. }
  47946. }
  47947. /**
  47948. * created a simplified copy of the segment object with just the
  47949. * information necessary to perform the XHR and decryption
  47950. *
  47951. * @private
  47952. *
  47953. * @param {Object} segmentInfo - the current segment
  47954. * @return {Object} a simplified segment object copy
  47955. */
  47956. createSimplifiedSegmentObj_(segmentInfo) {
  47957. const segment = segmentInfo.segment;
  47958. const part = segmentInfo.part;
  47959. const simpleSegment = {
  47960. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  47961. byterange: part ? part.byterange : segment.byterange,
  47962. requestId: segmentInfo.requestId,
  47963. transmuxer: segmentInfo.transmuxer,
  47964. audioAppendStart: segmentInfo.audioAppendStart,
  47965. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  47966. part: segmentInfo.part
  47967. };
  47968. const previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  47969. if (previousSegment && previousSegment.timeline === segment.timeline) {
  47970. // The baseStartTime of a segment is used to handle rollover when probing the TS
  47971. // segment to retrieve timing information. Since the probe only looks at the media's
  47972. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  47973. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  47974. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  47975. // seconds of media time, so should be used here. The previous segment is used since
  47976. // the end of the previous segment should represent the beginning of the current
  47977. // segment, so long as they are on the same timeline.
  47978. if (previousSegment.videoTimingInfo) {
  47979. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  47980. } else if (previousSegment.audioTimingInfo) {
  47981. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  47982. }
  47983. }
  47984. if (segment.key) {
  47985. // if the media sequence is greater than 2^32, the IV will be incorrect
  47986. // assuming 10s segments, that would be about 1300 years
  47987. const iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  47988. simpleSegment.key = this.segmentKey(segment.key);
  47989. simpleSegment.key.iv = iv;
  47990. }
  47991. if (segment.map) {
  47992. simpleSegment.map = this.initSegmentForMap(segment.map);
  47993. }
  47994. return simpleSegment;
  47995. }
  47996. saveTransferStats_(stats) {
  47997. // every request counts as a media request even if it has been aborted
  47998. // or canceled due to a timeout
  47999. this.mediaRequests += 1;
  48000. if (stats) {
  48001. this.mediaBytesTransferred += stats.bytesReceived;
  48002. this.mediaTransferDuration += stats.roundTripTime;
  48003. }
  48004. }
  48005. saveBandwidthRelatedStats_(duration, stats) {
  48006. // byteLength will be used for throughput, and should be based on bytes receieved,
  48007. // which we only know at the end of the request and should reflect total bytes
  48008. // downloaded rather than just bytes processed from components of the segment
  48009. this.pendingSegment_.byteLength = stats.bytesReceived;
  48010. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  48011. this.logger_(`Ignoring segment's bandwidth because its duration of ${duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
  48012. return;
  48013. }
  48014. this.bandwidth = stats.bandwidth;
  48015. this.roundTrip = stats.roundTripTime;
  48016. }
  48017. handleTimeout_() {
  48018. // although the VTT segment loader bandwidth isn't really used, it's good to
  48019. // maintain functinality between segment loaders
  48020. this.mediaRequestsTimedout += 1;
  48021. this.bandwidth = 1;
  48022. this.roundTrip = NaN;
  48023. this.trigger('bandwidthupdate');
  48024. this.trigger('timeout');
  48025. }
  48026. /**
  48027. * Handle the callback from the segmentRequest function and set the
  48028. * associated SegmentLoader state and errors if necessary
  48029. *
  48030. * @private
  48031. */
  48032. segmentRequestFinished_(error, simpleSegment, result) {
  48033. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  48034. // check the call queue directly since this function doesn't need to deal with any
  48035. // data, and can continue even if the source buffers are not set up and we didn't get
  48036. // any data from the segment
  48037. if (this.callQueue_.length) {
  48038. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  48039. return;
  48040. }
  48041. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  48042. if (!this.pendingSegment_) {
  48043. return;
  48044. } // the request was aborted and the SegmentLoader has already started
  48045. // another request. this can happen when the timeout for an aborted
  48046. // request triggers due to a limitation in the XHR library
  48047. // do not count this as any sort of request or we risk double-counting
  48048. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  48049. return;
  48050. } // an error occurred from the active pendingSegment_ so reset everything
  48051. if (error) {
  48052. this.pendingSegment_ = null;
  48053. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  48054. if (error.code === REQUEST_ERRORS.ABORTED) {
  48055. return;
  48056. }
  48057. this.pause(); // the error is really just that at least one of the requests timed-out
  48058. // set the bandwidth to a very low value and trigger an ABR switch to
  48059. // take emergency action
  48060. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  48061. this.handleTimeout_();
  48062. return;
  48063. } // if control-flow has arrived here, then the error is real
  48064. // emit an error event to exclude the current playlist
  48065. this.mediaRequestsErrored += 1;
  48066. this.error(error);
  48067. this.trigger('error');
  48068. return;
  48069. }
  48070. const segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  48071. // generated for ABR purposes
  48072. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  48073. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  48074. if (result.gopInfo) {
  48075. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  48076. } // Although we may have already started appending on progress, we shouldn't switch the
  48077. // state away from loading until we are officially done loading the segment data.
  48078. this.state = 'APPENDING'; // used for testing
  48079. this.trigger('appending');
  48080. this.waitForAppendsToComplete_(segmentInfo);
  48081. }
  48082. setTimeMapping_(timeline) {
  48083. const timelineMapping = this.syncController_.mappingForTimeline(timeline);
  48084. if (timelineMapping !== null) {
  48085. this.timeMapping_ = timelineMapping;
  48086. }
  48087. }
  48088. updateMediaSecondsLoaded_(segment) {
  48089. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  48090. this.mediaSecondsLoaded += segment.end - segment.start;
  48091. } else {
  48092. this.mediaSecondsLoaded += segment.duration;
  48093. }
  48094. }
  48095. shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  48096. if (timestampOffset === null) {
  48097. return false;
  48098. } // note that we're potentially using the same timestamp offset for both video and
  48099. // audio
  48100. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  48101. return true;
  48102. }
  48103. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  48104. return true;
  48105. }
  48106. return false;
  48107. }
  48108. trueSegmentStart_({
  48109. currentStart,
  48110. playlist,
  48111. mediaIndex,
  48112. firstVideoFrameTimeForData,
  48113. currentVideoTimestampOffset,
  48114. useVideoTimingInfo,
  48115. videoTimingInfo,
  48116. audioTimingInfo
  48117. }) {
  48118. if (typeof currentStart !== 'undefined') {
  48119. // if start was set once, keep using it
  48120. return currentStart;
  48121. }
  48122. if (!useVideoTimingInfo) {
  48123. return audioTimingInfo.start;
  48124. }
  48125. const previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  48126. // within that segment. Since the transmuxer maintains a cache of incomplete data
  48127. // from and/or the last frame seen, the start time may reflect a frame that starts
  48128. // in the previous segment. Check for that case and ensure the start time is
  48129. // accurate for the segment.
  48130. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  48131. return firstVideoFrameTimeForData;
  48132. }
  48133. return videoTimingInfo.start;
  48134. }
  48135. waitForAppendsToComplete_(segmentInfo) {
  48136. const trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  48137. if (!trackInfo) {
  48138. this.error({
  48139. message: 'No starting media returned, likely due to an unsupported media format.',
  48140. playlistExclusionDuration: Infinity
  48141. });
  48142. this.trigger('error');
  48143. return;
  48144. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  48145. // on each queue this loader is responsible for to ensure that the appends are
  48146. // complete.
  48147. const {
  48148. hasAudio,
  48149. hasVideo,
  48150. isMuxed
  48151. } = trackInfo;
  48152. const waitForVideo = this.loaderType_ === 'main' && hasVideo;
  48153. const waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  48154. segmentInfo.waitingOnAppends = 0; // segments with no data
  48155. if (!segmentInfo.hasAppendedData_) {
  48156. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  48157. // When there's no audio or video data in the segment, there's no audio or video
  48158. // timing information.
  48159. //
  48160. // If there's no audio or video timing information, then the timestamp offset
  48161. // can't be adjusted to the appropriate value for the transmuxer and source
  48162. // buffers.
  48163. //
  48164. // Therefore, the next segment should be used to set the timestamp offset.
  48165. this.isPendingTimestampOffset_ = true;
  48166. } // override settings for metadata only segments
  48167. segmentInfo.timingInfo = {
  48168. start: 0
  48169. };
  48170. segmentInfo.waitingOnAppends++;
  48171. if (!this.isPendingTimestampOffset_) {
  48172. // update the timestampoffset
  48173. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  48174. // no video/audio data.
  48175. this.processMetadataQueue_();
  48176. } // append is "done" instantly with no data.
  48177. this.checkAppendsDone_(segmentInfo);
  48178. return;
  48179. } // Since source updater could call back synchronously, do the increments first.
  48180. if (waitForVideo) {
  48181. segmentInfo.waitingOnAppends++;
  48182. }
  48183. if (waitForAudio) {
  48184. segmentInfo.waitingOnAppends++;
  48185. }
  48186. if (waitForVideo) {
  48187. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  48188. }
  48189. if (waitForAudio) {
  48190. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  48191. }
  48192. }
  48193. checkAppendsDone_(segmentInfo) {
  48194. if (this.checkForAbort_(segmentInfo.requestId)) {
  48195. return;
  48196. }
  48197. segmentInfo.waitingOnAppends--;
  48198. if (segmentInfo.waitingOnAppends === 0) {
  48199. this.handleAppendsDone_();
  48200. }
  48201. }
  48202. checkForIllegalMediaSwitch(trackInfo) {
  48203. const illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  48204. if (illegalMediaSwitchError) {
  48205. this.error({
  48206. message: illegalMediaSwitchError,
  48207. playlistExclusionDuration: Infinity
  48208. });
  48209. this.trigger('error');
  48210. return true;
  48211. }
  48212. return false;
  48213. }
  48214. updateSourceBufferTimestampOffset_(segmentInfo) {
  48215. if (segmentInfo.timestampOffset === null ||
  48216. // we don't yet have the start for whatever media type (video or audio) has
  48217. // priority, timing-wise, so we must wait
  48218. typeof segmentInfo.timingInfo.start !== 'number' ||
  48219. // already updated the timestamp offset for this segment
  48220. segmentInfo.changedTimestampOffset ||
  48221. // the alt audio loader should not be responsible for setting the timestamp offset
  48222. this.loaderType_ !== 'main') {
  48223. return;
  48224. }
  48225. let didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  48226. // the timing info here comes from video. In the event that the audio is longer than
  48227. // the video, this will trim the start of the audio.
  48228. // This also trims any offset from 0 at the beginning of the media
  48229. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  48230. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  48231. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  48232. timingInfo: segmentInfo.timingInfo
  48233. }); // In the event that there are part segment downloads, each will try to update the
  48234. // timestamp offset. Retaining this bit of state prevents us from updating in the
  48235. // future (within the same segment), however, there may be a better way to handle it.
  48236. segmentInfo.changedTimestampOffset = true;
  48237. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  48238. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  48239. didChange = true;
  48240. }
  48241. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  48242. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  48243. didChange = true;
  48244. }
  48245. if (didChange) {
  48246. this.trigger('timestampoffset');
  48247. }
  48248. }
  48249. getSegmentStartTimeForTimestampOffsetCalculation_({
  48250. videoTimingInfo,
  48251. audioTimingInfo,
  48252. timingInfo
  48253. }) {
  48254. if (!this.useDtsForTimestampOffset_) {
  48255. return timingInfo.start;
  48256. }
  48257. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  48258. return videoTimingInfo.transmuxedDecodeStart;
  48259. } // handle audio only
  48260. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  48261. return audioTimingInfo.transmuxedDecodeStart;
  48262. } // handle content not transmuxed (e.g., MP4)
  48263. return timingInfo.start;
  48264. }
  48265. updateTimingInfoEnd_(segmentInfo) {
  48266. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  48267. const trackInfo = this.getMediaInfo_();
  48268. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  48269. const prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  48270. if (!prioritizedTimingInfo) {
  48271. return;
  48272. }
  48273. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ?
  48274. // End time may not exist in a case where we aren't parsing the full segment (one
  48275. // current example is the case of fmp4), so use the rough duration to calculate an
  48276. // end time.
  48277. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  48278. }
  48279. /**
  48280. * callback to run when appendBuffer is finished. detects if we are
  48281. * in a good state to do things with the data we got, or if we need
  48282. * to wait for more
  48283. *
  48284. * @private
  48285. */
  48286. handleAppendsDone_() {
  48287. // appendsdone can cause an abort
  48288. if (this.pendingSegment_) {
  48289. this.trigger('appendsdone');
  48290. }
  48291. if (!this.pendingSegment_) {
  48292. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  48293. // all appending cases?
  48294. if (!this.paused()) {
  48295. this.monitorBuffer_();
  48296. }
  48297. return;
  48298. }
  48299. const segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  48300. // best to wait until all appends are done so we're sure that the primary media is
  48301. // finished (and we have its end time).
  48302. this.updateTimingInfoEnd_(segmentInfo);
  48303. if (this.shouldSaveSegmentTimingInfo_) {
  48304. // Timeline mappings should only be saved for the main loader. This is for multiple
  48305. // reasons:
  48306. //
  48307. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  48308. // and the main loader try to save the timeline mapping, whichever comes later
  48309. // will overwrite the first. In theory this is OK, as the mappings should be the
  48310. // same, however, it breaks for (2)
  48311. // 2) In the event of a live stream, the initial live point will make for a somewhat
  48312. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  48313. // the mapping will be off for one of the streams, dependent on which one was
  48314. // first saved (see (1)).
  48315. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  48316. //
  48317. // Since the audio loader will wait for the main loader to load the first segment,
  48318. // the main loader will save the first timeline mapping, and ensure that there won't
  48319. // be a case where audio loads two segments without saving a mapping (thus leading
  48320. // to missing segment timing info).
  48321. this.syncController_.saveSegmentTimingInfo({
  48322. segmentInfo,
  48323. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  48324. });
  48325. }
  48326. const segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  48327. if (segmentDurationMessage) {
  48328. if (segmentDurationMessage.severity === 'warn') {
  48329. videojs.log.warn(segmentDurationMessage.message);
  48330. } else {
  48331. this.logger_(segmentDurationMessage.message);
  48332. }
  48333. }
  48334. this.recordThroughput_(segmentInfo);
  48335. this.pendingSegment_ = null;
  48336. this.state = 'READY';
  48337. if (segmentInfo.isSyncRequest) {
  48338. this.trigger('syncinfoupdate'); // if the sync request was not appended
  48339. // then it was not the correct segment.
  48340. // throw it away and use the data it gave us
  48341. // to get the correct one.
  48342. if (!segmentInfo.hasAppendedData_) {
  48343. this.logger_(`Throwing away un-appended sync request ${segmentInfoString(segmentInfo)}`);
  48344. return;
  48345. }
  48346. }
  48347. this.logger_(`Appended ${segmentInfoString(segmentInfo)}`);
  48348. this.addSegmentMetadataCue_(segmentInfo);
  48349. this.fetchAtBuffer_ = true;
  48350. if (this.currentTimeline_ !== segmentInfo.timeline) {
  48351. this.timelineChangeController_.lastTimelineChange({
  48352. type: this.loaderType_,
  48353. from: this.currentTimeline_,
  48354. to: segmentInfo.timeline
  48355. }); // If audio is not disabled, the main segment loader is responsible for updating
  48356. // the audio timeline as well. If the content is video only, this won't have any
  48357. // impact.
  48358. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  48359. this.timelineChangeController_.lastTimelineChange({
  48360. type: 'audio',
  48361. from: this.currentTimeline_,
  48362. to: segmentInfo.timeline
  48363. });
  48364. }
  48365. }
  48366. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  48367. // the following conditional otherwise it may consider this a bad "guess"
  48368. // and attempt to resync when the post-update seekable window and live
  48369. // point would mean that this was the perfect segment to fetch
  48370. this.trigger('syncinfoupdate');
  48371. const segment = segmentInfo.segment;
  48372. const part = segmentInfo.part;
  48373. const badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  48374. const 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
  48375. // the currentTime_ that means that our conservative guess was too conservative.
  48376. // In that case, reset the loader state so that we try to use any information gained
  48377. // from the previous request to create a new, more accurate, sync-point.
  48378. if (badSegmentGuess || badPartGuess) {
  48379. this.logger_(`bad ${badSegmentGuess ? 'segment' : 'part'} ${segmentInfoString(segmentInfo)}`);
  48380. this.resetEverything();
  48381. return;
  48382. }
  48383. const isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  48384. // and conservatively guess
  48385. if (isWalkingForward) {
  48386. this.trigger('bandwidthupdate');
  48387. }
  48388. this.trigger('progress');
  48389. this.mediaIndex = segmentInfo.mediaIndex;
  48390. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  48391. // buffer, end the stream. this ensures the "ended" event will
  48392. // fire if playback reaches that point.
  48393. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  48394. this.endOfStream();
  48395. } // used for testing
  48396. this.trigger('appended');
  48397. if (segmentInfo.hasAppendedData_) {
  48398. this.mediaAppends++;
  48399. }
  48400. if (!this.paused()) {
  48401. this.monitorBuffer_();
  48402. }
  48403. }
  48404. /**
  48405. * Records the current throughput of the decrypt, transmux, and append
  48406. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  48407. * moving average of the throughput. `throughput.count` is the number of
  48408. * data points in the average.
  48409. *
  48410. * @private
  48411. * @param {Object} segmentInfo the object returned by loadSegment
  48412. */
  48413. recordThroughput_(segmentInfo) {
  48414. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  48415. 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}`);
  48416. return;
  48417. }
  48418. const rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  48419. // by zero in the case where the throughput is ridiculously high
  48420. const segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  48421. const segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  48422. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  48423. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  48424. }
  48425. /**
  48426. * Adds a cue to the segment-metadata track with some metadata information about the
  48427. * segment
  48428. *
  48429. * @private
  48430. * @param {Object} segmentInfo
  48431. * the object returned by loadSegment
  48432. * @method addSegmentMetadataCue_
  48433. */
  48434. addSegmentMetadataCue_(segmentInfo) {
  48435. if (!this.segmentMetadataTrack_) {
  48436. return;
  48437. }
  48438. const segment = segmentInfo.segment;
  48439. const start = segment.start;
  48440. const end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  48441. if (!finite(start) || !finite(end)) {
  48442. return;
  48443. }
  48444. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  48445. const Cue = window.WebKitDataCue || window.VTTCue;
  48446. const value = {
  48447. custom: segment.custom,
  48448. dateTimeObject: segment.dateTimeObject,
  48449. dateTimeString: segment.dateTimeString,
  48450. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  48451. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  48452. codecs: segmentInfo.playlist.attributes.CODECS,
  48453. byteLength: segmentInfo.byteLength,
  48454. uri: segmentInfo.uri,
  48455. timeline: segmentInfo.timeline,
  48456. playlist: segmentInfo.playlist.id,
  48457. start,
  48458. end
  48459. };
  48460. const data = JSON.stringify(value);
  48461. const cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  48462. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  48463. cue.value = value;
  48464. this.segmentMetadataTrack_.addCue(cue);
  48465. }
  48466. }
  48467. function noop() {}
  48468. const toTitleCase = function (string) {
  48469. if (typeof string !== 'string') {
  48470. return string;
  48471. }
  48472. return string.replace(/./, w => w.toUpperCase());
  48473. };
  48474. /**
  48475. * @file source-updater.js
  48476. */
  48477. const bufferTypes = ['video', 'audio'];
  48478. const updating = (type, sourceUpdater) => {
  48479. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  48480. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  48481. };
  48482. const nextQueueIndexOfType = (type, queue) => {
  48483. for (let i = 0; i < queue.length; i++) {
  48484. const queueEntry = queue[i];
  48485. if (queueEntry.type === 'mediaSource') {
  48486. // If the next entry is a media source entry (uses multiple source buffers), block
  48487. // processing to allow it to go through first.
  48488. return null;
  48489. }
  48490. if (queueEntry.type === type) {
  48491. return i;
  48492. }
  48493. }
  48494. return null;
  48495. };
  48496. const shiftQueue = (type, sourceUpdater) => {
  48497. if (sourceUpdater.queue.length === 0) {
  48498. return;
  48499. }
  48500. let queueIndex = 0;
  48501. let queueEntry = sourceUpdater.queue[queueIndex];
  48502. if (queueEntry.type === 'mediaSource') {
  48503. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  48504. sourceUpdater.queue.shift();
  48505. queueEntry.action(sourceUpdater);
  48506. if (queueEntry.doneFn) {
  48507. queueEntry.doneFn();
  48508. } // Only specific source buffer actions must wait for async updateend events. Media
  48509. // Source actions process synchronously. Therefore, both audio and video source
  48510. // buffers are now clear to process the next queue entries.
  48511. shiftQueue('audio', sourceUpdater);
  48512. shiftQueue('video', sourceUpdater);
  48513. } // Media Source actions require both source buffers, so if the media source action
  48514. // couldn't process yet (because one or both source buffers are busy), block other
  48515. // queue actions until both are available and the media source action can process.
  48516. return;
  48517. }
  48518. if (type === 'mediaSource') {
  48519. // If the queue was shifted by a media source action (this happens when pushing a
  48520. // media source action onto the queue), then it wasn't from an updateend event from an
  48521. // audio or video source buffer, so there's no change from previous state, and no
  48522. // processing should be done.
  48523. return;
  48524. } // Media source queue entries don't need to consider whether the source updater is
  48525. // started (i.e., source buffers are created) as they don't need the source buffers, but
  48526. // source buffer queue entries do.
  48527. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || updating(type, sourceUpdater)) {
  48528. return;
  48529. }
  48530. if (queueEntry.type !== type) {
  48531. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  48532. if (queueIndex === null) {
  48533. // Either there's no queue entry that uses this source buffer type in the queue, or
  48534. // there's a media source queue entry before the next entry of this type, in which
  48535. // case wait for that action to process first.
  48536. return;
  48537. }
  48538. queueEntry = sourceUpdater.queue[queueIndex];
  48539. }
  48540. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  48541. //
  48542. // The queue pending operation must be set before the action is performed in the event
  48543. // that the action results in a synchronous event that is acted upon. For instance, if
  48544. // an exception is thrown that can be handled, it's possible that new actions will be
  48545. // appended to an empty queue and immediately executed, but would not have the correct
  48546. // pending information if this property was set after the action was performed.
  48547. sourceUpdater.queuePending[type] = queueEntry;
  48548. queueEntry.action(type, sourceUpdater);
  48549. if (!queueEntry.doneFn) {
  48550. // synchronous operation, process next entry
  48551. sourceUpdater.queuePending[type] = null;
  48552. shiftQueue(type, sourceUpdater);
  48553. return;
  48554. }
  48555. };
  48556. const cleanupBuffer = (type, sourceUpdater) => {
  48557. const buffer = sourceUpdater[`${type}Buffer`];
  48558. const titleType = toTitleCase(type);
  48559. if (!buffer) {
  48560. return;
  48561. }
  48562. buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  48563. buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  48564. sourceUpdater.codecs[type] = null;
  48565. sourceUpdater[`${type}Buffer`] = null;
  48566. };
  48567. const inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  48568. const actions = {
  48569. appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {
  48570. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  48571. // or the media source does not contain this source buffer.
  48572. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  48573. return;
  48574. }
  48575. sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);
  48576. try {
  48577. sourceBuffer.appendBuffer(bytes);
  48578. } catch (e) {
  48579. sourceUpdater.logger_(`Error with code ${e.code} ` + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);
  48580. sourceUpdater.queuePending[type] = null;
  48581. onError(e);
  48582. }
  48583. },
  48584. remove: (start, end) => (type, sourceUpdater) => {
  48585. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  48586. // or the media source does not contain this source buffer.
  48587. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  48588. return;
  48589. }
  48590. sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);
  48591. try {
  48592. sourceBuffer.remove(start, end);
  48593. } catch (e) {
  48594. sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);
  48595. }
  48596. },
  48597. timestampOffset: offset => (type, sourceUpdater) => {
  48598. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  48599. // or the media source does not contain this source buffer.
  48600. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  48601. return;
  48602. }
  48603. sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);
  48604. sourceBuffer.timestampOffset = offset;
  48605. },
  48606. callback: callback => (type, sourceUpdater) => {
  48607. callback();
  48608. },
  48609. endOfStream: error => sourceUpdater => {
  48610. if (sourceUpdater.mediaSource.readyState !== 'open') {
  48611. return;
  48612. }
  48613. sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);
  48614. try {
  48615. sourceUpdater.mediaSource.endOfStream(error);
  48616. } catch (e) {
  48617. videojs.log.warn('Failed to call media source endOfStream', e);
  48618. }
  48619. },
  48620. duration: duration => sourceUpdater => {
  48621. sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);
  48622. try {
  48623. sourceUpdater.mediaSource.duration = duration;
  48624. } catch (e) {
  48625. videojs.log.warn('Failed to set media source duration', e);
  48626. }
  48627. },
  48628. abort: () => (type, sourceUpdater) => {
  48629. if (sourceUpdater.mediaSource.readyState !== 'open') {
  48630. return;
  48631. }
  48632. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  48633. // or the media source does not contain this source buffer.
  48634. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  48635. return;
  48636. }
  48637. sourceUpdater.logger_(`calling abort on ${type}Buffer`);
  48638. try {
  48639. sourceBuffer.abort();
  48640. } catch (e) {
  48641. videojs.log.warn(`Failed to abort on ${type}Buffer`, e);
  48642. }
  48643. },
  48644. addSourceBuffer: (type, codec) => sourceUpdater => {
  48645. const titleType = toTitleCase(type);
  48646. const mime = getMimeForCodec(codec);
  48647. sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);
  48648. const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  48649. sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  48650. sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  48651. sourceUpdater.codecs[type] = codec;
  48652. sourceUpdater[`${type}Buffer`] = sourceBuffer;
  48653. },
  48654. removeSourceBuffer: type => sourceUpdater => {
  48655. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  48656. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  48657. // or the media source does not contain this source buffer.
  48658. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  48659. return;
  48660. }
  48661. sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);
  48662. try {
  48663. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  48664. } catch (e) {
  48665. videojs.log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);
  48666. }
  48667. },
  48668. changeType: codec => (type, sourceUpdater) => {
  48669. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  48670. const mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  48671. // or the media source does not contain this source buffer.
  48672. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  48673. return;
  48674. } // do not update codec if we don't need to.
  48675. if (sourceUpdater.codecs[type] === codec) {
  48676. return;
  48677. }
  48678. sourceUpdater.logger_(`changing ${type}Buffer codec from ${sourceUpdater.codecs[type]} to ${codec}`);
  48679. sourceBuffer.changeType(mime);
  48680. sourceUpdater.codecs[type] = codec;
  48681. }
  48682. };
  48683. const pushQueue = ({
  48684. type,
  48685. sourceUpdater,
  48686. action,
  48687. doneFn,
  48688. name
  48689. }) => {
  48690. sourceUpdater.queue.push({
  48691. type,
  48692. action,
  48693. doneFn,
  48694. name
  48695. });
  48696. shiftQueue(type, sourceUpdater);
  48697. };
  48698. const onUpdateend = (type, sourceUpdater) => e => {
  48699. // Although there should, in theory, be a pending action for any updateend receieved,
  48700. // there are some actions that may trigger updateend events without set definitions in
  48701. // the w3c spec. For instance, setting the duration on the media source may trigger
  48702. // updateend events on source buffers. This does not appear to be in the spec. As such,
  48703. // if we encounter an updateend without a corresponding pending action from our queue
  48704. // for that source buffer type, process the next action.
  48705. if (sourceUpdater.queuePending[type]) {
  48706. const doneFn = sourceUpdater.queuePending[type].doneFn;
  48707. sourceUpdater.queuePending[type] = null;
  48708. if (doneFn) {
  48709. // if there's an error, report it
  48710. doneFn(sourceUpdater[`${type}Error_`]);
  48711. }
  48712. }
  48713. shiftQueue(type, sourceUpdater);
  48714. };
  48715. /**
  48716. * A queue of callbacks to be serialized and applied when a
  48717. * MediaSource and its associated SourceBuffers are not in the
  48718. * updating state. It is used by the segment loader to update the
  48719. * underlying SourceBuffers when new data is loaded, for instance.
  48720. *
  48721. * @class SourceUpdater
  48722. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  48723. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  48724. */
  48725. class SourceUpdater extends videojs.EventTarget {
  48726. constructor(mediaSource) {
  48727. super();
  48728. this.mediaSource = mediaSource;
  48729. this.sourceopenListener_ = () => shiftQueue('mediaSource', this);
  48730. this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);
  48731. this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  48732. this.audioTimestampOffset_ = 0;
  48733. this.videoTimestampOffset_ = 0;
  48734. this.queue = [];
  48735. this.queuePending = {
  48736. audio: null,
  48737. video: null
  48738. };
  48739. this.delayedAudioAppendQueue_ = [];
  48740. this.videoAppendQueued_ = false;
  48741. this.codecs = {};
  48742. this.onVideoUpdateEnd_ = onUpdateend('video', this);
  48743. this.onAudioUpdateEnd_ = onUpdateend('audio', this);
  48744. this.onVideoError_ = e => {
  48745. // used for debugging
  48746. this.videoError_ = e;
  48747. };
  48748. this.onAudioError_ = e => {
  48749. // used for debugging
  48750. this.audioError_ = e;
  48751. };
  48752. this.createdSourceBuffers_ = false;
  48753. this.initializedEme_ = false;
  48754. this.triggeredReady_ = false;
  48755. }
  48756. initializedEme() {
  48757. this.initializedEme_ = true;
  48758. this.triggerReady();
  48759. }
  48760. hasCreatedSourceBuffers() {
  48761. // if false, likely waiting on one of the segment loaders to get enough data to create
  48762. // source buffers
  48763. return this.createdSourceBuffers_;
  48764. }
  48765. hasInitializedAnyEme() {
  48766. return this.initializedEme_;
  48767. }
  48768. ready() {
  48769. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  48770. }
  48771. createSourceBuffers(codecs) {
  48772. if (this.hasCreatedSourceBuffers()) {
  48773. // already created them before
  48774. return;
  48775. } // the intial addOrChangeSourceBuffers will always be
  48776. // two add buffers.
  48777. this.addOrChangeSourceBuffers(codecs);
  48778. this.createdSourceBuffers_ = true;
  48779. this.trigger('createdsourcebuffers');
  48780. this.triggerReady();
  48781. }
  48782. triggerReady() {
  48783. // only allow ready to be triggered once, this prevents the case
  48784. // where:
  48785. // 1. we trigger createdsourcebuffers
  48786. // 2. ie 11 synchronously initializates eme
  48787. // 3. the synchronous initialization causes us to trigger ready
  48788. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  48789. if (this.ready() && !this.triggeredReady_) {
  48790. this.triggeredReady_ = true;
  48791. this.trigger('ready');
  48792. }
  48793. }
  48794. /**
  48795. * Add a type of source buffer to the media source.
  48796. *
  48797. * @param {string} type
  48798. * The type of source buffer to add.
  48799. *
  48800. * @param {string} codec
  48801. * The codec to add the source buffer with.
  48802. */
  48803. addSourceBuffer(type, codec) {
  48804. pushQueue({
  48805. type: 'mediaSource',
  48806. sourceUpdater: this,
  48807. action: actions.addSourceBuffer(type, codec),
  48808. name: 'addSourceBuffer'
  48809. });
  48810. }
  48811. /**
  48812. * call abort on a source buffer.
  48813. *
  48814. * @param {string} type
  48815. * The type of source buffer to call abort on.
  48816. */
  48817. abort(type) {
  48818. pushQueue({
  48819. type,
  48820. sourceUpdater: this,
  48821. action: actions.abort(type),
  48822. name: 'abort'
  48823. });
  48824. }
  48825. /**
  48826. * Call removeSourceBuffer and remove a specific type
  48827. * of source buffer on the mediaSource.
  48828. *
  48829. * @param {string} type
  48830. * The type of source buffer to remove.
  48831. */
  48832. removeSourceBuffer(type) {
  48833. if (!this.canRemoveSourceBuffer()) {
  48834. videojs.log.error('removeSourceBuffer is not supported!');
  48835. return;
  48836. }
  48837. pushQueue({
  48838. type: 'mediaSource',
  48839. sourceUpdater: this,
  48840. action: actions.removeSourceBuffer(type),
  48841. name: 'removeSourceBuffer'
  48842. });
  48843. }
  48844. /**
  48845. * Whether or not the removeSourceBuffer function is supported
  48846. * on the mediaSource.
  48847. *
  48848. * @return {boolean}
  48849. * if removeSourceBuffer can be called.
  48850. */
  48851. canRemoveSourceBuffer() {
  48852. // IE reports that it supports removeSourceBuffer, but often throws
  48853. // errors when attempting to use the function. So we report that it
  48854. // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
  48855. // throws errors, so we report that it does not support this as well.
  48856. return !videojs.browser.IE_VERSION && !videojs.browser.IS_FIREFOX && window.MediaSource && window.MediaSource.prototype && typeof window.MediaSource.prototype.removeSourceBuffer === 'function';
  48857. }
  48858. /**
  48859. * Whether or not the changeType function is supported
  48860. * on our SourceBuffers.
  48861. *
  48862. * @return {boolean}
  48863. * if changeType can be called.
  48864. */
  48865. static canChangeType() {
  48866. return window.SourceBuffer && window.SourceBuffer.prototype && typeof window.SourceBuffer.prototype.changeType === 'function';
  48867. }
  48868. /**
  48869. * Whether or not the changeType function is supported
  48870. * on our SourceBuffers.
  48871. *
  48872. * @return {boolean}
  48873. * if changeType can be called.
  48874. */
  48875. canChangeType() {
  48876. return this.constructor.canChangeType();
  48877. }
  48878. /**
  48879. * Call the changeType function on a source buffer, given the code and type.
  48880. *
  48881. * @param {string} type
  48882. * The type of source buffer to call changeType on.
  48883. *
  48884. * @param {string} codec
  48885. * The codec string to change type with on the source buffer.
  48886. */
  48887. changeType(type, codec) {
  48888. if (!this.canChangeType()) {
  48889. videojs.log.error('changeType is not supported!');
  48890. return;
  48891. }
  48892. pushQueue({
  48893. type,
  48894. sourceUpdater: this,
  48895. action: actions.changeType(codec),
  48896. name: 'changeType'
  48897. });
  48898. }
  48899. /**
  48900. * Add source buffers with a codec or, if they are already created,
  48901. * call changeType on source buffers using changeType.
  48902. *
  48903. * @param {Object} codecs
  48904. * Codecs to switch to
  48905. */
  48906. addOrChangeSourceBuffers(codecs) {
  48907. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  48908. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  48909. }
  48910. Object.keys(codecs).forEach(type => {
  48911. const codec = codecs[type];
  48912. if (!this.hasCreatedSourceBuffers()) {
  48913. return this.addSourceBuffer(type, codec);
  48914. }
  48915. if (this.canChangeType()) {
  48916. this.changeType(type, codec);
  48917. }
  48918. });
  48919. }
  48920. /**
  48921. * Queue an update to append an ArrayBuffer.
  48922. *
  48923. * @param {MediaObject} object containing audioBytes and/or videoBytes
  48924. * @param {Function} done the function to call when done
  48925. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  48926. */
  48927. appendBuffer(options, doneFn) {
  48928. const {
  48929. segmentInfo,
  48930. type,
  48931. bytes
  48932. } = options;
  48933. this.processedAppend_ = true;
  48934. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  48935. this.delayedAudioAppendQueue_.push([options, doneFn]);
  48936. this.logger_(`delayed audio append of ${bytes.length} until video append`);
  48937. return;
  48938. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  48939. // not be fired. This means that the queue will be blocked until the next action
  48940. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  48941. // these errors by calling the doneFn with the specific error.
  48942. const onError = doneFn;
  48943. pushQueue({
  48944. type,
  48945. sourceUpdater: this,
  48946. action: actions.appendBuffer(bytes, segmentInfo || {
  48947. mediaIndex: -1
  48948. }, onError),
  48949. doneFn,
  48950. name: 'appendBuffer'
  48951. });
  48952. if (type === 'video') {
  48953. this.videoAppendQueued_ = true;
  48954. if (!this.delayedAudioAppendQueue_.length) {
  48955. return;
  48956. }
  48957. const queue = this.delayedAudioAppendQueue_.slice();
  48958. this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);
  48959. this.delayedAudioAppendQueue_.length = 0;
  48960. queue.forEach(que => {
  48961. this.appendBuffer.apply(this, que);
  48962. });
  48963. }
  48964. }
  48965. /**
  48966. * Get the audio buffer's buffered timerange.
  48967. *
  48968. * @return {TimeRange}
  48969. * The audio buffer's buffered time range
  48970. */
  48971. audioBuffered() {
  48972. // no media source/source buffer or it isn't in the media sources
  48973. // source buffer list
  48974. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  48975. return createTimeRanges();
  48976. }
  48977. return this.audioBuffer.buffered ? this.audioBuffer.buffered : createTimeRanges();
  48978. }
  48979. /**
  48980. * Get the video buffer's buffered timerange.
  48981. *
  48982. * @return {TimeRange}
  48983. * The video buffer's buffered time range
  48984. */
  48985. videoBuffered() {
  48986. // no media source/source buffer or it isn't in the media sources
  48987. // source buffer list
  48988. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  48989. return createTimeRanges();
  48990. }
  48991. return this.videoBuffer.buffered ? this.videoBuffer.buffered : createTimeRanges();
  48992. }
  48993. /**
  48994. * Get a combined video/audio buffer's buffered timerange.
  48995. *
  48996. * @return {TimeRange}
  48997. * the combined time range
  48998. */
  48999. buffered() {
  49000. const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  49001. const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  49002. if (audio && !video) {
  49003. return this.audioBuffered();
  49004. }
  49005. if (video && !audio) {
  49006. return this.videoBuffered();
  49007. }
  49008. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  49009. }
  49010. /**
  49011. * Add a callback to the queue that will set duration on the mediaSource.
  49012. *
  49013. * @param {number} duration
  49014. * The duration to set
  49015. *
  49016. * @param {Function} [doneFn]
  49017. * function to run after duration has been set.
  49018. */
  49019. setDuration(duration, doneFn = noop) {
  49020. // In order to set the duration on the media source, it's necessary to wait for all
  49021. // source buffers to no longer be updating. "If the updating attribute equals true on
  49022. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  49023. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  49024. pushQueue({
  49025. type: 'mediaSource',
  49026. sourceUpdater: this,
  49027. action: actions.duration(duration),
  49028. name: 'duration',
  49029. doneFn
  49030. });
  49031. }
  49032. /**
  49033. * Add a mediaSource endOfStream call to the queue
  49034. *
  49035. * @param {Error} [error]
  49036. * Call endOfStream with an error
  49037. *
  49038. * @param {Function} [doneFn]
  49039. * A function that should be called when the
  49040. * endOfStream call has finished.
  49041. */
  49042. endOfStream(error = null, doneFn = noop) {
  49043. if (typeof error !== 'string') {
  49044. error = undefined;
  49045. } // In order to set the duration on the media source, it's necessary to wait for all
  49046. // source buffers to no longer be updating. "If the updating attribute equals true on
  49047. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  49048. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  49049. pushQueue({
  49050. type: 'mediaSource',
  49051. sourceUpdater: this,
  49052. action: actions.endOfStream(error),
  49053. name: 'endOfStream',
  49054. doneFn
  49055. });
  49056. }
  49057. /**
  49058. * Queue an update to remove a time range from the buffer.
  49059. *
  49060. * @param {number} start where to start the removal
  49061. * @param {number} end where to end the removal
  49062. * @param {Function} [done=noop] optional callback to be executed when the remove
  49063. * operation is complete
  49064. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  49065. */
  49066. removeAudio(start, end, done = noop) {
  49067. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  49068. done();
  49069. return;
  49070. }
  49071. pushQueue({
  49072. type: 'audio',
  49073. sourceUpdater: this,
  49074. action: actions.remove(start, end),
  49075. doneFn: done,
  49076. name: 'remove'
  49077. });
  49078. }
  49079. /**
  49080. * Queue an update to remove a time range from the buffer.
  49081. *
  49082. * @param {number} start where to start the removal
  49083. * @param {number} end where to end the removal
  49084. * @param {Function} [done=noop] optional callback to be executed when the remove
  49085. * operation is complete
  49086. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  49087. */
  49088. removeVideo(start, end, done = noop) {
  49089. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  49090. done();
  49091. return;
  49092. }
  49093. pushQueue({
  49094. type: 'video',
  49095. sourceUpdater: this,
  49096. action: actions.remove(start, end),
  49097. doneFn: done,
  49098. name: 'remove'
  49099. });
  49100. }
  49101. /**
  49102. * Whether the underlying sourceBuffer is updating or not
  49103. *
  49104. * @return {boolean} the updating status of the SourceBuffer
  49105. */
  49106. updating() {
  49107. // the audio/video source buffer is updating
  49108. if (updating('audio', this) || updating('video', this)) {
  49109. return true;
  49110. }
  49111. return false;
  49112. }
  49113. /**
  49114. * Set/get the timestampoffset on the audio SourceBuffer
  49115. *
  49116. * @return {number} the timestamp offset
  49117. */
  49118. audioTimestampOffset(offset) {
  49119. if (typeof offset !== 'undefined' && this.audioBuffer &&
  49120. // no point in updating if it's the same
  49121. this.audioTimestampOffset_ !== offset) {
  49122. pushQueue({
  49123. type: 'audio',
  49124. sourceUpdater: this,
  49125. action: actions.timestampOffset(offset),
  49126. name: 'timestampOffset'
  49127. });
  49128. this.audioTimestampOffset_ = offset;
  49129. }
  49130. return this.audioTimestampOffset_;
  49131. }
  49132. /**
  49133. * Set/get the timestampoffset on the video SourceBuffer
  49134. *
  49135. * @return {number} the timestamp offset
  49136. */
  49137. videoTimestampOffset(offset) {
  49138. if (typeof offset !== 'undefined' && this.videoBuffer &&
  49139. // no point in updating if it's the same
  49140. this.videoTimestampOffset !== offset) {
  49141. pushQueue({
  49142. type: 'video',
  49143. sourceUpdater: this,
  49144. action: actions.timestampOffset(offset),
  49145. name: 'timestampOffset'
  49146. });
  49147. this.videoTimestampOffset_ = offset;
  49148. }
  49149. return this.videoTimestampOffset_;
  49150. }
  49151. /**
  49152. * Add a function to the queue that will be called
  49153. * when it is its turn to run in the audio queue.
  49154. *
  49155. * @param {Function} callback
  49156. * The callback to queue.
  49157. */
  49158. audioQueueCallback(callback) {
  49159. if (!this.audioBuffer) {
  49160. return;
  49161. }
  49162. pushQueue({
  49163. type: 'audio',
  49164. sourceUpdater: this,
  49165. action: actions.callback(callback),
  49166. name: 'callback'
  49167. });
  49168. }
  49169. /**
  49170. * Add a function to the queue that will be called
  49171. * when it is its turn to run in the video queue.
  49172. *
  49173. * @param {Function} callback
  49174. * The callback to queue.
  49175. */
  49176. videoQueueCallback(callback) {
  49177. if (!this.videoBuffer) {
  49178. return;
  49179. }
  49180. pushQueue({
  49181. type: 'video',
  49182. sourceUpdater: this,
  49183. action: actions.callback(callback),
  49184. name: 'callback'
  49185. });
  49186. }
  49187. /**
  49188. * dispose of the source updater and the underlying sourceBuffer
  49189. */
  49190. dispose() {
  49191. this.trigger('dispose');
  49192. bufferTypes.forEach(type => {
  49193. this.abort(type);
  49194. if (this.canRemoveSourceBuffer()) {
  49195. this.removeSourceBuffer(type);
  49196. } else {
  49197. this[`${type}QueueCallback`](() => cleanupBuffer(type, this));
  49198. }
  49199. });
  49200. this.videoAppendQueued_ = false;
  49201. this.delayedAudioAppendQueue_.length = 0;
  49202. if (this.sourceopenListener_) {
  49203. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  49204. }
  49205. this.off();
  49206. }
  49207. }
  49208. const uint8ToUtf8 = uintArray => decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  49209. /**
  49210. * @file vtt-segment-loader.js
  49211. */
  49212. const VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(char => char.charCodeAt(0)));
  49213. class NoVttJsError extends Error {
  49214. constructor() {
  49215. super('Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.');
  49216. }
  49217. }
  49218. /**
  49219. * An object that manages segment loading and appending.
  49220. *
  49221. * @class VTTSegmentLoader
  49222. * @param {Object} options required and optional options
  49223. * @extends videojs.EventTarget
  49224. */
  49225. class VTTSegmentLoader extends SegmentLoader {
  49226. constructor(settings, options = {}) {
  49227. super(settings, options); // SegmentLoader requires a MediaSource be specified or it will throw an error;
  49228. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  49229. this.mediaSource_ = null;
  49230. this.subtitlesTrack_ = null;
  49231. this.loaderType_ = 'subtitle';
  49232. this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  49233. this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  49234. // the sync controller leads to improper behavior.
  49235. this.shouldSaveSegmentTimingInfo_ = false;
  49236. }
  49237. createTransmuxer_() {
  49238. // don't need to transmux any subtitles
  49239. return null;
  49240. }
  49241. /**
  49242. * Indicates which time ranges are buffered
  49243. *
  49244. * @return {TimeRange}
  49245. * TimeRange object representing the current buffered ranges
  49246. */
  49247. buffered_() {
  49248. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  49249. return createTimeRanges();
  49250. }
  49251. const cues = this.subtitlesTrack_.cues;
  49252. const start = cues[0].startTime;
  49253. const end = cues[cues.length - 1].startTime;
  49254. return createTimeRanges([[start, end]]);
  49255. }
  49256. /**
  49257. * Gets and sets init segment for the provided map
  49258. *
  49259. * @param {Object} map
  49260. * The map object representing the init segment to get or set
  49261. * @param {boolean=} set
  49262. * If true, the init segment for the provided map should be saved
  49263. * @return {Object}
  49264. * map object for desired init segment
  49265. */
  49266. initSegmentForMap(map, set = false) {
  49267. if (!map) {
  49268. return null;
  49269. }
  49270. const id = initSegmentId(map);
  49271. let storedMap = this.initSegments_[id];
  49272. if (set && !storedMap && map.bytes) {
  49273. // append WebVTT line terminators to the media initialization segment if it exists
  49274. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  49275. // requires two or more WebVTT line terminators between the WebVTT header and the
  49276. // rest of the file
  49277. const combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  49278. const combinedSegment = new Uint8Array(combinedByteLength);
  49279. combinedSegment.set(map.bytes);
  49280. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  49281. this.initSegments_[id] = storedMap = {
  49282. resolvedUri: map.resolvedUri,
  49283. byterange: map.byterange,
  49284. bytes: combinedSegment
  49285. };
  49286. }
  49287. return storedMap || map;
  49288. }
  49289. /**
  49290. * Returns true if all configuration required for loading is present, otherwise false.
  49291. *
  49292. * @return {boolean} True if the all configuration is ready for loading
  49293. * @private
  49294. */
  49295. couldBeginLoading_() {
  49296. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  49297. }
  49298. /**
  49299. * Once all the starting parameters have been specified, begin
  49300. * operation. This method should only be invoked from the INIT
  49301. * state.
  49302. *
  49303. * @private
  49304. */
  49305. init_() {
  49306. this.state = 'READY';
  49307. this.resetEverything();
  49308. return this.monitorBuffer_();
  49309. }
  49310. /**
  49311. * Set a subtitle track on the segment loader to add subtitles to
  49312. *
  49313. * @param {TextTrack=} track
  49314. * The text track to add loaded subtitles to
  49315. * @return {TextTrack}
  49316. * Returns the subtitles track
  49317. */
  49318. track(track) {
  49319. if (typeof track === 'undefined') {
  49320. return this.subtitlesTrack_;
  49321. }
  49322. this.subtitlesTrack_ = track; // if we were unpaused but waiting for a sourceUpdater, start
  49323. // buffering now
  49324. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  49325. this.init_();
  49326. }
  49327. return this.subtitlesTrack_;
  49328. }
  49329. /**
  49330. * Remove any data in the source buffer between start and end times
  49331. *
  49332. * @param {number} start - the start time of the region to remove from the buffer
  49333. * @param {number} end - the end time of the region to remove from the buffer
  49334. */
  49335. remove(start, end) {
  49336. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  49337. }
  49338. /**
  49339. * fill the buffer with segements unless the sourceBuffers are
  49340. * currently updating
  49341. *
  49342. * Note: this function should only ever be called by monitorBuffer_
  49343. * and never directly
  49344. *
  49345. * @private
  49346. */
  49347. fillBuffer_() {
  49348. // see if we need to begin loading immediately
  49349. const segmentInfo = this.chooseNextRequest_();
  49350. if (!segmentInfo) {
  49351. return;
  49352. }
  49353. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  49354. // We don't have the timestamp offset that we need to sync subtitles.
  49355. // Rerun on a timestamp offset or user interaction.
  49356. const checkTimestampOffset = () => {
  49357. this.state = 'READY';
  49358. if (!this.paused()) {
  49359. // if not paused, queue a buffer check as soon as possible
  49360. this.monitorBuffer_();
  49361. }
  49362. };
  49363. this.syncController_.one('timestampoffset', checkTimestampOffset);
  49364. this.state = 'WAITING_ON_TIMELINE';
  49365. return;
  49366. }
  49367. this.loadSegment_(segmentInfo);
  49368. } // never set a timestamp offset for vtt segments.
  49369. timestampOffsetForSegment_() {
  49370. return null;
  49371. }
  49372. chooseNextRequest_() {
  49373. return this.skipEmptySegments_(super.chooseNextRequest_());
  49374. }
  49375. /**
  49376. * Prevents the segment loader from requesting segments we know contain no subtitles
  49377. * by walking forward until we find the next segment that we don't know whether it is
  49378. * empty or not.
  49379. *
  49380. * @param {Object} segmentInfo
  49381. * a segment info object that describes the current segment
  49382. * @return {Object}
  49383. * a segment info object that describes the current segment
  49384. */
  49385. skipEmptySegments_(segmentInfo) {
  49386. while (segmentInfo && segmentInfo.segment.empty) {
  49387. // stop at the last possible segmentInfo
  49388. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  49389. segmentInfo = null;
  49390. break;
  49391. }
  49392. segmentInfo = this.generateSegmentInfo_({
  49393. playlist: segmentInfo.playlist,
  49394. mediaIndex: segmentInfo.mediaIndex + 1,
  49395. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  49396. isSyncRequest: segmentInfo.isSyncRequest
  49397. });
  49398. }
  49399. return segmentInfo;
  49400. }
  49401. stopForError(error) {
  49402. this.error(error);
  49403. this.state = 'READY';
  49404. this.pause();
  49405. this.trigger('error');
  49406. }
  49407. /**
  49408. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  49409. *
  49410. * @private
  49411. */
  49412. segmentRequestFinished_(error, simpleSegment, result) {
  49413. if (!this.subtitlesTrack_) {
  49414. this.state = 'READY';
  49415. return;
  49416. }
  49417. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  49418. if (!this.pendingSegment_) {
  49419. this.state = 'READY';
  49420. this.mediaRequestsAborted += 1;
  49421. return;
  49422. }
  49423. if (error) {
  49424. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  49425. this.handleTimeout_();
  49426. }
  49427. if (error.code === REQUEST_ERRORS.ABORTED) {
  49428. this.mediaRequestsAborted += 1;
  49429. } else {
  49430. this.mediaRequestsErrored += 1;
  49431. }
  49432. this.stopForError(error);
  49433. return;
  49434. }
  49435. const segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  49436. // maintain functionality between segment loaders
  49437. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  49438. if (simpleSegment.key) {
  49439. this.segmentKey(simpleSegment.key, true);
  49440. }
  49441. this.state = 'APPENDING'; // used for tests
  49442. this.trigger('appending');
  49443. const segment = segmentInfo.segment;
  49444. if (segment.map) {
  49445. segment.map.bytes = simpleSegment.map.bytes;
  49446. }
  49447. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  49448. if (typeof window.WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  49449. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  49450. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  49451. this.loadVttJs().then(() => this.segmentRequestFinished_(error, simpleSegment, result), () => this.stopForError({
  49452. message: 'Error loading vtt.js'
  49453. }));
  49454. return;
  49455. }
  49456. segment.requested = true;
  49457. try {
  49458. this.parseVTTCues_(segmentInfo);
  49459. } catch (e) {
  49460. this.stopForError({
  49461. message: e.message
  49462. });
  49463. return;
  49464. }
  49465. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  49466. if (segmentInfo.cues.length) {
  49467. segmentInfo.timingInfo = {
  49468. start: segmentInfo.cues[0].startTime,
  49469. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  49470. };
  49471. } else {
  49472. segmentInfo.timingInfo = {
  49473. start: segmentInfo.startOfSegment,
  49474. end: segmentInfo.startOfSegment + segmentInfo.duration
  49475. };
  49476. }
  49477. if (segmentInfo.isSyncRequest) {
  49478. this.trigger('syncinfoupdate');
  49479. this.pendingSegment_ = null;
  49480. this.state = 'READY';
  49481. return;
  49482. }
  49483. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  49484. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  49485. // the subtitle track
  49486. segmentInfo.cues.forEach(cue => {
  49487. this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_ ? new window.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  49488. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  49489. // cues to have identical time-intervals, but if the text is also identical
  49490. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  49491. // "overlaps" VTT segments)
  49492. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  49493. this.handleAppendsDone_();
  49494. }
  49495. handleData_() {// noop as we shouldn't be getting video/audio data captions
  49496. // that we do not support here.
  49497. }
  49498. updateTimingInfoEnd_() {// noop
  49499. }
  49500. /**
  49501. * Uses the WebVTT parser to parse the segment response
  49502. *
  49503. * @throws NoVttJsError
  49504. *
  49505. * @param {Object} segmentInfo
  49506. * a segment info object that describes the current segment
  49507. * @private
  49508. */
  49509. parseVTTCues_(segmentInfo) {
  49510. let decoder;
  49511. let decodeBytesToString = false;
  49512. if (typeof window.WebVTT !== 'function') {
  49513. // caller is responsible for exception handling.
  49514. throw new NoVttJsError();
  49515. }
  49516. if (typeof window.TextDecoder === 'function') {
  49517. decoder = new window.TextDecoder('utf8');
  49518. } else {
  49519. decoder = window.WebVTT.StringDecoder();
  49520. decodeBytesToString = true;
  49521. }
  49522. const parser = new window.WebVTT.Parser(window, window.vttjs, decoder);
  49523. segmentInfo.cues = [];
  49524. segmentInfo.timestampmap = {
  49525. MPEGTS: 0,
  49526. LOCAL: 0
  49527. };
  49528. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  49529. parser.ontimestampmap = map => {
  49530. segmentInfo.timestampmap = map;
  49531. };
  49532. parser.onparsingerror = error => {
  49533. videojs.log.warn('Error encountered when parsing cues: ' + error.message);
  49534. };
  49535. if (segmentInfo.segment.map) {
  49536. let mapData = segmentInfo.segment.map.bytes;
  49537. if (decodeBytesToString) {
  49538. mapData = uint8ToUtf8(mapData);
  49539. }
  49540. parser.parse(mapData);
  49541. }
  49542. let segmentData = segmentInfo.bytes;
  49543. if (decodeBytesToString) {
  49544. segmentData = uint8ToUtf8(segmentData);
  49545. }
  49546. parser.parse(segmentData);
  49547. parser.flush();
  49548. }
  49549. /**
  49550. * Updates the start and end times of any cues parsed by the WebVTT parser using
  49551. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  49552. * from the SyncController
  49553. *
  49554. * @param {Object} segmentInfo
  49555. * a segment info object that describes the current segment
  49556. * @param {Object} mappingObj
  49557. * object containing a mapping from TS to media time
  49558. * @param {Object} playlist
  49559. * the playlist object containing the segment
  49560. * @private
  49561. */
  49562. updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  49563. const segment = segmentInfo.segment;
  49564. if (!mappingObj) {
  49565. // If the sync controller does not have a mapping of TS to Media Time for the
  49566. // timeline, then we don't have enough information to update the cue
  49567. // start/end times
  49568. return;
  49569. }
  49570. if (!segmentInfo.cues.length) {
  49571. // If there are no cues, we also do not have enough information to figure out
  49572. // segment timing. Mark that the segment contains no cues so we don't re-request
  49573. // an empty segment.
  49574. segment.empty = true;
  49575. return;
  49576. }
  49577. const timestampmap = segmentInfo.timestampmap;
  49578. const diff = timestampmap.MPEGTS / clock_1 - timestampmap.LOCAL + mappingObj.mapping;
  49579. segmentInfo.cues.forEach(cue => {
  49580. // First convert cue time to TS time using the timestamp-map provided within the vtt
  49581. cue.startTime += diff;
  49582. cue.endTime += diff;
  49583. });
  49584. if (!playlist.syncInfo) {
  49585. const firstStart = segmentInfo.cues[0].startTime;
  49586. const lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  49587. playlist.syncInfo = {
  49588. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  49589. time: Math.min(firstStart, lastStart - segment.duration)
  49590. };
  49591. }
  49592. }
  49593. }
  49594. /**
  49595. * @file ad-cue-tags.js
  49596. */
  49597. /**
  49598. * Searches for an ad cue that overlaps with the given mediaTime
  49599. *
  49600. * @param {Object} track
  49601. * the track to find the cue for
  49602. *
  49603. * @param {number} mediaTime
  49604. * the time to find the cue at
  49605. *
  49606. * @return {Object|null}
  49607. * the found cue or null
  49608. */
  49609. const findAdCue = function (track, mediaTime) {
  49610. const cues = track.cues;
  49611. for (let i = 0; i < cues.length; i++) {
  49612. const cue = cues[i];
  49613. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  49614. return cue;
  49615. }
  49616. }
  49617. return null;
  49618. };
  49619. const updateAdCues = function (media, track, offset = 0) {
  49620. if (!media.segments) {
  49621. return;
  49622. }
  49623. let mediaTime = offset;
  49624. let cue;
  49625. for (let i = 0; i < media.segments.length; i++) {
  49626. const segment = media.segments[i];
  49627. if (!cue) {
  49628. // Since the cues will span for at least the segment duration, adding a fudge
  49629. // factor of half segment duration will prevent duplicate cues from being
  49630. // created when timing info is not exact (e.g. cue start time initialized
  49631. // at 10.006677, but next call mediaTime is 10.003332 )
  49632. cue = findAdCue(track, mediaTime + segment.duration / 2);
  49633. }
  49634. if (cue) {
  49635. if ('cueIn' in segment) {
  49636. // Found a CUE-IN so end the cue
  49637. cue.endTime = mediaTime;
  49638. cue.adEndTime = mediaTime;
  49639. mediaTime += segment.duration;
  49640. cue = null;
  49641. continue;
  49642. }
  49643. if (mediaTime < cue.endTime) {
  49644. // Already processed this mediaTime for this cue
  49645. mediaTime += segment.duration;
  49646. continue;
  49647. } // otherwise extend cue until a CUE-IN is found
  49648. cue.endTime += segment.duration;
  49649. } else {
  49650. if ('cueOut' in segment) {
  49651. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  49652. cue.adStartTime = mediaTime; // Assumes tag format to be
  49653. // #EXT-X-CUE-OUT:30
  49654. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  49655. track.addCue(cue);
  49656. }
  49657. if ('cueOutCont' in segment) {
  49658. // Entered into the middle of an ad cue
  49659. // Assumes tag formate to be
  49660. // #EXT-X-CUE-OUT-CONT:10/30
  49661. const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);
  49662. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, '');
  49663. cue.adStartTime = mediaTime - adOffset;
  49664. cue.adEndTime = cue.adStartTime + adTotal;
  49665. track.addCue(cue);
  49666. }
  49667. }
  49668. mediaTime += segment.duration;
  49669. }
  49670. };
  49671. /**
  49672. * @file sync-controller.js
  49673. */
  49674. // synchronize expired playlist segments.
  49675. // the max media sequence diff is 48 hours of live stream
  49676. // content with two second segments. Anything larger than that
  49677. // will likely be invalid.
  49678. const MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  49679. const syncPointStrategies = [
  49680. // Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  49681. // the equivalence display-time 0 === segment-index 0
  49682. {
  49683. name: 'VOD',
  49684. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  49685. if (duration !== Infinity) {
  49686. const syncPoint = {
  49687. time: 0,
  49688. segmentIndex: 0,
  49689. partIndex: null
  49690. };
  49691. return syncPoint;
  49692. }
  49693. return null;
  49694. }
  49695. },
  49696. // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  49697. {
  49698. name: 'ProgramDateTime',
  49699. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  49700. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  49701. return null;
  49702. }
  49703. let syncPoint = null;
  49704. let lastDistance = null;
  49705. const partsAndSegments = getPartsAndSegments(playlist);
  49706. currentTime = currentTime || 0;
  49707. for (let i = 0; i < partsAndSegments.length; i++) {
  49708. // start from the end and loop backwards for live
  49709. // or start from the front and loop forwards for non-live
  49710. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  49711. const partAndSegment = partsAndSegments[index];
  49712. const segment = partAndSegment.segment;
  49713. const datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  49714. if (!datetimeMapping || !segment.dateTimeObject) {
  49715. continue;
  49716. }
  49717. const segmentTime = segment.dateTimeObject.getTime() / 1000;
  49718. let start = segmentTime + datetimeMapping; // take part duration into account.
  49719. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  49720. for (let z = 0; z < partAndSegment.partIndex; z++) {
  49721. start += segment.parts[z].duration;
  49722. }
  49723. }
  49724. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  49725. // currentTime and can stop looking for better candidates
  49726. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  49727. break;
  49728. }
  49729. lastDistance = distance;
  49730. syncPoint = {
  49731. time: start,
  49732. segmentIndex: partAndSegment.segmentIndex,
  49733. partIndex: partAndSegment.partIndex
  49734. };
  49735. }
  49736. return syncPoint;
  49737. }
  49738. },
  49739. // Stategy "Segment": We have a known time mapping for a timeline and a
  49740. // segment in the current timeline with timing data
  49741. {
  49742. name: 'Segment',
  49743. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  49744. let syncPoint = null;
  49745. let lastDistance = null;
  49746. currentTime = currentTime || 0;
  49747. const partsAndSegments = getPartsAndSegments(playlist);
  49748. for (let i = 0; i < partsAndSegments.length; i++) {
  49749. // start from the end and loop backwards for live
  49750. // or start from the front and loop forwards for non-live
  49751. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  49752. const partAndSegment = partsAndSegments[index];
  49753. const segment = partAndSegment.segment;
  49754. const start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  49755. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  49756. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  49757. // currentTime and can stop looking for better candidates
  49758. if (lastDistance !== null && lastDistance < distance) {
  49759. break;
  49760. }
  49761. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  49762. lastDistance = distance;
  49763. syncPoint = {
  49764. time: start,
  49765. segmentIndex: partAndSegment.segmentIndex,
  49766. partIndex: partAndSegment.partIndex
  49767. };
  49768. }
  49769. }
  49770. }
  49771. return syncPoint;
  49772. }
  49773. },
  49774. // Stategy "Discontinuity": We have a discontinuity with a known
  49775. // display-time
  49776. {
  49777. name: 'Discontinuity',
  49778. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  49779. let syncPoint = null;
  49780. currentTime = currentTime || 0;
  49781. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  49782. let lastDistance = null;
  49783. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  49784. const segmentIndex = playlist.discontinuityStarts[i];
  49785. const discontinuity = playlist.discontinuitySequence + i + 1;
  49786. const discontinuitySync = syncController.discontinuities[discontinuity];
  49787. if (discontinuitySync) {
  49788. const distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  49789. // currentTime and can stop looking for better candidates
  49790. if (lastDistance !== null && lastDistance < distance) {
  49791. break;
  49792. }
  49793. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  49794. lastDistance = distance;
  49795. syncPoint = {
  49796. time: discontinuitySync.time,
  49797. segmentIndex,
  49798. partIndex: null
  49799. };
  49800. }
  49801. }
  49802. }
  49803. }
  49804. return syncPoint;
  49805. }
  49806. },
  49807. // Stategy "Playlist": We have a playlist with a known mapping of
  49808. // segment index to display time
  49809. {
  49810. name: 'Playlist',
  49811. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  49812. if (playlist.syncInfo) {
  49813. const syncPoint = {
  49814. time: playlist.syncInfo.time,
  49815. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  49816. partIndex: null
  49817. };
  49818. return syncPoint;
  49819. }
  49820. return null;
  49821. }
  49822. }];
  49823. class SyncController extends videojs.EventTarget {
  49824. constructor(options = {}) {
  49825. super(); // ...for synching across variants
  49826. this.timelines = [];
  49827. this.discontinuities = [];
  49828. this.timelineToDatetimeMappings = {};
  49829. this.logger_ = logger('SyncController');
  49830. }
  49831. /**
  49832. * Find a sync-point for the playlist specified
  49833. *
  49834. * A sync-point is defined as a known mapping from display-time to
  49835. * a segment-index in the current playlist.
  49836. *
  49837. * @param {Playlist} playlist
  49838. * The playlist that needs a sync-point
  49839. * @param {number} duration
  49840. * Duration of the MediaSource (Infinite if playing a live source)
  49841. * @param {number} currentTimeline
  49842. * The last timeline from which a segment was loaded
  49843. * @return {Object}
  49844. * A sync-point object
  49845. */
  49846. getSyncPoint(playlist, duration, currentTimeline, currentTime) {
  49847. const syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
  49848. if (!syncPoints.length) {
  49849. // Signal that we need to attempt to get a sync-point manually
  49850. // by fetching a segment in the playlist and constructing
  49851. // a sync-point from that information
  49852. return null;
  49853. } // Now find the sync-point that is closest to the currentTime because
  49854. // that should result in the most accurate guess about which segment
  49855. // to fetch
  49856. return this.selectSyncPoint_(syncPoints, {
  49857. key: 'time',
  49858. value: currentTime
  49859. });
  49860. }
  49861. /**
  49862. * Calculate the amount of time that has expired off the playlist during playback
  49863. *
  49864. * @param {Playlist} playlist
  49865. * Playlist object to calculate expired from
  49866. * @param {number} duration
  49867. * Duration of the MediaSource (Infinity if playling a live source)
  49868. * @return {number|null}
  49869. * The amount of time that has expired off the playlist during playback. Null
  49870. * if no sync-points for the playlist can be found.
  49871. */
  49872. getExpiredTime(playlist, duration) {
  49873. if (!playlist || !playlist.segments) {
  49874. return null;
  49875. }
  49876. const syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
  49877. if (!syncPoints.length) {
  49878. return null;
  49879. }
  49880. const syncPoint = this.selectSyncPoint_(syncPoints, {
  49881. key: 'segmentIndex',
  49882. value: 0
  49883. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  49884. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  49885. if (syncPoint.segmentIndex > 0) {
  49886. syncPoint.time *= -1;
  49887. }
  49888. return Math.abs(syncPoint.time + sumDurations({
  49889. defaultDuration: playlist.targetDuration,
  49890. durationList: playlist.segments,
  49891. startIndex: syncPoint.segmentIndex,
  49892. endIndex: 0
  49893. }));
  49894. }
  49895. /**
  49896. * Runs each sync-point strategy and returns a list of sync-points returned by the
  49897. * strategies
  49898. *
  49899. * @private
  49900. * @param {Playlist} playlist
  49901. * The playlist that needs a sync-point
  49902. * @param {number} duration
  49903. * Duration of the MediaSource (Infinity if playing a live source)
  49904. * @param {number} currentTimeline
  49905. * The last timeline from which a segment was loaded
  49906. * @return {Array}
  49907. * A list of sync-point objects
  49908. */
  49909. runStrategies_(playlist, duration, currentTimeline, currentTime) {
  49910. const syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  49911. for (let i = 0; i < syncPointStrategies.length; i++) {
  49912. const strategy = syncPointStrategies[i];
  49913. const syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
  49914. if (syncPoint) {
  49915. syncPoint.strategy = strategy.name;
  49916. syncPoints.push({
  49917. strategy: strategy.name,
  49918. syncPoint
  49919. });
  49920. }
  49921. }
  49922. return syncPoints;
  49923. }
  49924. /**
  49925. * Selects the sync-point nearest the specified target
  49926. *
  49927. * @private
  49928. * @param {Array} syncPoints
  49929. * List of sync-points to select from
  49930. * @param {Object} target
  49931. * Object specifying the property and value we are targeting
  49932. * @param {string} target.key
  49933. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  49934. * @param {number} target.value
  49935. * The value to target for the specified key.
  49936. * @return {Object}
  49937. * The sync-point nearest the target
  49938. */
  49939. selectSyncPoint_(syncPoints, target) {
  49940. let bestSyncPoint = syncPoints[0].syncPoint;
  49941. let bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  49942. let bestStrategy = syncPoints[0].strategy;
  49943. for (let i = 1; i < syncPoints.length; i++) {
  49944. const newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  49945. if (newDistance < bestDistance) {
  49946. bestDistance = newDistance;
  49947. bestSyncPoint = syncPoints[i].syncPoint;
  49948. bestStrategy = syncPoints[i].strategy;
  49949. }
  49950. }
  49951. 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}` : '') + ']');
  49952. return bestSyncPoint;
  49953. }
  49954. /**
  49955. * Save any meta-data present on the segments when segments leave
  49956. * the live window to the playlist to allow for synchronization at the
  49957. * playlist level later.
  49958. *
  49959. * @param {Playlist} oldPlaylist - The previous active playlist
  49960. * @param {Playlist} newPlaylist - The updated and most current playlist
  49961. */
  49962. saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  49963. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  49964. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  49965. videojs.log.warn(`Not saving expired segment info. Media sequence gap ${mediaSequenceDiff} is too large.`);
  49966. return;
  49967. } // When a segment expires from the playlist and it has a start time
  49968. // save that information as a possible sync-point reference in future
  49969. for (let i = mediaSequenceDiff - 1; i >= 0; i--) {
  49970. const lastRemovedSegment = oldPlaylist.segments[i];
  49971. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  49972. newPlaylist.syncInfo = {
  49973. mediaSequence: oldPlaylist.mediaSequence + i,
  49974. time: lastRemovedSegment.start
  49975. };
  49976. this.logger_(`playlist refresh sync: [time:${newPlaylist.syncInfo.time},` + ` mediaSequence: ${newPlaylist.syncInfo.mediaSequence}]`);
  49977. this.trigger('syncinfoupdate');
  49978. break;
  49979. }
  49980. }
  49981. }
  49982. /**
  49983. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  49984. * before segments start to load.
  49985. *
  49986. * @param {Playlist} playlist - The currently active playlist
  49987. */
  49988. setDateTimeMappingForStart(playlist) {
  49989. // It's possible for the playlist to be updated before playback starts, meaning time
  49990. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  49991. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  49992. // unless the mappings are cleared.
  49993. this.timelineToDatetimeMappings = {};
  49994. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  49995. const firstSegment = playlist.segments[0];
  49996. const playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  49997. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  49998. }
  49999. }
  50000. /**
  50001. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  50002. * based on the latest timing information.
  50003. *
  50004. * @param {Object} options
  50005. * Options object
  50006. * @param {SegmentInfo} options.segmentInfo
  50007. * The current active request information
  50008. * @param {boolean} options.shouldSaveTimelineMapping
  50009. * If there's a timeline change, determines if the timeline mapping should be
  50010. * saved for timeline mapping and program date time mappings.
  50011. */
  50012. saveSegmentTimingInfo({
  50013. segmentInfo,
  50014. shouldSaveTimelineMapping
  50015. }) {
  50016. const didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  50017. const segment = segmentInfo.segment;
  50018. if (didCalculateSegmentTimeMapping) {
  50019. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  50020. // now with segment timing information
  50021. if (!segmentInfo.playlist.syncInfo) {
  50022. segmentInfo.playlist.syncInfo = {
  50023. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  50024. time: segment.start
  50025. };
  50026. }
  50027. }
  50028. const dateTime = segment.dateTimeObject;
  50029. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  50030. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  50031. }
  50032. }
  50033. timestampOffsetForTimeline(timeline) {
  50034. if (typeof this.timelines[timeline] === 'undefined') {
  50035. return null;
  50036. }
  50037. return this.timelines[timeline].time;
  50038. }
  50039. mappingForTimeline(timeline) {
  50040. if (typeof this.timelines[timeline] === 'undefined') {
  50041. return null;
  50042. }
  50043. return this.timelines[timeline].mapping;
  50044. }
  50045. /**
  50046. * Use the "media time" for a segment to generate a mapping to "display time" and
  50047. * save that display time to the segment.
  50048. *
  50049. * @private
  50050. * @param {SegmentInfo} segmentInfo
  50051. * The current active request information
  50052. * @param {Object} timingInfo
  50053. * The start and end time of the current segment in "media time"
  50054. * @param {boolean} shouldSaveTimelineMapping
  50055. * If there's a timeline change, determines if the timeline mapping should be
  50056. * saved in timelines.
  50057. * @return {boolean}
  50058. * Returns false if segment time mapping could not be calculated
  50059. */
  50060. calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  50061. // TODO: remove side effects
  50062. const segment = segmentInfo.segment;
  50063. const part = segmentInfo.part;
  50064. let mappingObj = this.timelines[segmentInfo.timeline];
  50065. let start;
  50066. let end;
  50067. if (typeof segmentInfo.timestampOffset === 'number') {
  50068. mappingObj = {
  50069. time: segmentInfo.startOfSegment,
  50070. mapping: segmentInfo.startOfSegment - timingInfo.start
  50071. };
  50072. if (shouldSaveTimelineMapping) {
  50073. this.timelines[segmentInfo.timeline] = mappingObj;
  50074. this.trigger('timestampoffset');
  50075. this.logger_(`time mapping for timeline ${segmentInfo.timeline}: ` + `[time: ${mappingObj.time}] [mapping: ${mappingObj.mapping}]`);
  50076. }
  50077. start = segmentInfo.startOfSegment;
  50078. end = timingInfo.end + mappingObj.mapping;
  50079. } else if (mappingObj) {
  50080. start = timingInfo.start + mappingObj.mapping;
  50081. end = timingInfo.end + mappingObj.mapping;
  50082. } else {
  50083. return false;
  50084. }
  50085. if (part) {
  50086. part.start = start;
  50087. part.end = end;
  50088. } // If we don't have a segment start yet or the start value we got
  50089. // is less than our current segment.start value, save a new start value.
  50090. // We have to do this because parts will have segment timing info saved
  50091. // multiple times and we want segment start to be the earliest part start
  50092. // value for that segment.
  50093. if (!segment.start || start < segment.start) {
  50094. segment.start = start;
  50095. }
  50096. segment.end = end;
  50097. return true;
  50098. }
  50099. /**
  50100. * Each time we have discontinuity in the playlist, attempt to calculate the location
  50101. * in display of the start of the discontinuity and save that. We also save an accuracy
  50102. * value so that we save values with the most accuracy (closest to 0.)
  50103. *
  50104. * @private
  50105. * @param {SegmentInfo} segmentInfo - The current active request information
  50106. */
  50107. saveDiscontinuitySyncInfo_(segmentInfo) {
  50108. const playlist = segmentInfo.playlist;
  50109. const segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  50110. // the start of the range and it's accuracy is 0 (greater accuracy values
  50111. // mean more approximation)
  50112. if (segment.discontinuity) {
  50113. this.discontinuities[segment.timeline] = {
  50114. time: segment.start,
  50115. accuracy: 0
  50116. };
  50117. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  50118. // Search for future discontinuities that we can provide better timing
  50119. // information for and save that information for sync purposes
  50120. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  50121. const segmentIndex = playlist.discontinuityStarts[i];
  50122. const discontinuity = playlist.discontinuitySequence + i + 1;
  50123. const mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  50124. const accuracy = Math.abs(mediaIndexDiff);
  50125. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  50126. let time;
  50127. if (mediaIndexDiff < 0) {
  50128. time = segment.start - sumDurations({
  50129. defaultDuration: playlist.targetDuration,
  50130. durationList: playlist.segments,
  50131. startIndex: segmentInfo.mediaIndex,
  50132. endIndex: segmentIndex
  50133. });
  50134. } else {
  50135. time = segment.end + sumDurations({
  50136. defaultDuration: playlist.targetDuration,
  50137. durationList: playlist.segments,
  50138. startIndex: segmentInfo.mediaIndex + 1,
  50139. endIndex: segmentIndex
  50140. });
  50141. }
  50142. this.discontinuities[discontinuity] = {
  50143. time,
  50144. accuracy
  50145. };
  50146. }
  50147. }
  50148. }
  50149. }
  50150. dispose() {
  50151. this.trigger('dispose');
  50152. this.off();
  50153. }
  50154. }
  50155. /**
  50156. * The TimelineChangeController acts as a source for segment loaders to listen for and
  50157. * keep track of latest and pending timeline changes. This is useful to ensure proper
  50158. * sync, as each loader may need to make a consideration for what timeline the other
  50159. * loader is on before making changes which could impact the other loader's media.
  50160. *
  50161. * @class TimelineChangeController
  50162. * @extends videojs.EventTarget
  50163. */
  50164. class TimelineChangeController extends videojs.EventTarget {
  50165. constructor() {
  50166. super();
  50167. this.pendingTimelineChanges_ = {};
  50168. this.lastTimelineChanges_ = {};
  50169. }
  50170. clearPendingTimelineChange(type) {
  50171. this.pendingTimelineChanges_[type] = null;
  50172. this.trigger('pendingtimelinechange');
  50173. }
  50174. pendingTimelineChange({
  50175. type,
  50176. from,
  50177. to
  50178. }) {
  50179. if (typeof from === 'number' && typeof to === 'number') {
  50180. this.pendingTimelineChanges_[type] = {
  50181. type,
  50182. from,
  50183. to
  50184. };
  50185. this.trigger('pendingtimelinechange');
  50186. }
  50187. return this.pendingTimelineChanges_[type];
  50188. }
  50189. lastTimelineChange({
  50190. type,
  50191. from,
  50192. to
  50193. }) {
  50194. if (typeof from === 'number' && typeof to === 'number') {
  50195. this.lastTimelineChanges_[type] = {
  50196. type,
  50197. from,
  50198. to
  50199. };
  50200. delete this.pendingTimelineChanges_[type];
  50201. this.trigger('timelinechange');
  50202. }
  50203. return this.lastTimelineChanges_[type];
  50204. }
  50205. dispose() {
  50206. this.trigger('dispose');
  50207. this.pendingTimelineChanges_ = {};
  50208. this.lastTimelineChanges_ = {};
  50209. this.off();
  50210. }
  50211. }
  50212. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  50213. const workerCode = transform(getWorkerString(function () {
  50214. /**
  50215. * @file stream.js
  50216. */
  50217. /**
  50218. * A lightweight readable stream implemention that handles event dispatching.
  50219. *
  50220. * @class Stream
  50221. */
  50222. var Stream = /*#__PURE__*/function () {
  50223. function Stream() {
  50224. this.listeners = {};
  50225. }
  50226. /**
  50227. * Add a listener for a specified event type.
  50228. *
  50229. * @param {string} type the event name
  50230. * @param {Function} listener the callback to be invoked when an event of
  50231. * the specified type occurs
  50232. */
  50233. var _proto = Stream.prototype;
  50234. _proto.on = function on(type, listener) {
  50235. if (!this.listeners[type]) {
  50236. this.listeners[type] = [];
  50237. }
  50238. this.listeners[type].push(listener);
  50239. }
  50240. /**
  50241. * Remove a listener for a specified event type.
  50242. *
  50243. * @param {string} type the event name
  50244. * @param {Function} listener a function previously registered for this
  50245. * type of event through `on`
  50246. * @return {boolean} if we could turn it off or not
  50247. */;
  50248. _proto.off = function off(type, listener) {
  50249. if (!this.listeners[type]) {
  50250. return false;
  50251. }
  50252. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  50253. // In Video.js we slice listener functions
  50254. // on trigger so that it does not mess up the order
  50255. // while we loop through.
  50256. //
  50257. // Here we slice on off so that the loop in trigger
  50258. // can continue using it's old reference to loop without
  50259. // messing up the order.
  50260. this.listeners[type] = this.listeners[type].slice(0);
  50261. this.listeners[type].splice(index, 1);
  50262. return index > -1;
  50263. }
  50264. /**
  50265. * Trigger an event of the specified type on this stream. Any additional
  50266. * arguments to this function are passed as parameters to event listeners.
  50267. *
  50268. * @param {string} type the event name
  50269. */;
  50270. _proto.trigger = function trigger(type) {
  50271. var callbacks = this.listeners[type];
  50272. if (!callbacks) {
  50273. return;
  50274. } // Slicing the arguments on every invocation of this method
  50275. // can add a significant amount of overhead. Avoid the
  50276. // intermediate object creation for the common case of a
  50277. // single callback argument
  50278. if (arguments.length === 2) {
  50279. var length = callbacks.length;
  50280. for (var i = 0; i < length; ++i) {
  50281. callbacks[i].call(this, arguments[1]);
  50282. }
  50283. } else {
  50284. var args = Array.prototype.slice.call(arguments, 1);
  50285. var _length = callbacks.length;
  50286. for (var _i = 0; _i < _length; ++_i) {
  50287. callbacks[_i].apply(this, args);
  50288. }
  50289. }
  50290. }
  50291. /**
  50292. * Destroys the stream and cleans up.
  50293. */;
  50294. _proto.dispose = function dispose() {
  50295. this.listeners = {};
  50296. }
  50297. /**
  50298. * Forwards all `data` events on this stream to the destination stream. The
  50299. * destination stream should provide a method `push` to receive the data
  50300. * events as they arrive.
  50301. *
  50302. * @param {Stream} destination the stream that will receive all `data` events
  50303. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  50304. */;
  50305. _proto.pipe = function pipe(destination) {
  50306. this.on('data', function (data) {
  50307. destination.push(data);
  50308. });
  50309. };
  50310. return Stream;
  50311. }();
  50312. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  50313. /**
  50314. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  50315. *
  50316. * @param padded {Uint8Array} unencrypted bytes that have been padded
  50317. * @return {Uint8Array} the unpadded bytes
  50318. * @see http://tools.ietf.org/html/rfc5652
  50319. */
  50320. function unpad(padded) {
  50321. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  50322. }
  50323. /*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */
  50324. /**
  50325. * @file aes.js
  50326. *
  50327. * This file contains an adaptation of the AES decryption algorithm
  50328. * from the Standford Javascript Cryptography Library. That work is
  50329. * covered by the following copyright and permissions notice:
  50330. *
  50331. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  50332. * All rights reserved.
  50333. *
  50334. * Redistribution and use in source and binary forms, with or without
  50335. * modification, are permitted provided that the following conditions are
  50336. * met:
  50337. *
  50338. * 1. Redistributions of source code must retain the above copyright
  50339. * notice, this list of conditions and the following disclaimer.
  50340. *
  50341. * 2. Redistributions in binary form must reproduce the above
  50342. * copyright notice, this list of conditions and the following
  50343. * disclaimer in the documentation and/or other materials provided
  50344. * with the distribution.
  50345. *
  50346. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  50347. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  50348. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  50349. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  50350. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  50351. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  50352. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  50353. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  50354. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  50355. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  50356. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  50357. *
  50358. * The views and conclusions contained in the software and documentation
  50359. * are those of the authors and should not be interpreted as representing
  50360. * official policies, either expressed or implied, of the authors.
  50361. */
  50362. /**
  50363. * Expand the S-box tables.
  50364. *
  50365. * @private
  50366. */
  50367. const precompute = function () {
  50368. const tables = [[[], [], [], [], []], [[], [], [], [], []]];
  50369. const encTable = tables[0];
  50370. const decTable = tables[1];
  50371. const sbox = encTable[4];
  50372. const sboxInv = decTable[4];
  50373. let i;
  50374. let x;
  50375. let xInv;
  50376. const d = [];
  50377. const th = [];
  50378. let x2;
  50379. let x4;
  50380. let x8;
  50381. let s;
  50382. let tEnc;
  50383. let tDec; // Compute double and third tables
  50384. for (i = 0; i < 256; i++) {
  50385. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  50386. }
  50387. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  50388. // Compute sbox
  50389. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  50390. s = s >> 8 ^ s & 255 ^ 99;
  50391. sbox[x] = s;
  50392. sboxInv[s] = x; // Compute MixColumns
  50393. x8 = d[x4 = d[x2 = d[x]]];
  50394. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  50395. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  50396. for (i = 0; i < 4; i++) {
  50397. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  50398. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  50399. }
  50400. } // Compactify. Considerable speedup on Firefox.
  50401. for (i = 0; i < 5; i++) {
  50402. encTable[i] = encTable[i].slice(0);
  50403. decTable[i] = decTable[i].slice(0);
  50404. }
  50405. return tables;
  50406. };
  50407. let aesTables = null;
  50408. /**
  50409. * Schedule out an AES key for both encryption and decryption. This
  50410. * is a low-level class. Use a cipher mode to do bulk encryption.
  50411. *
  50412. * @class AES
  50413. * @param key {Array} The key as an array of 4, 6 or 8 words.
  50414. */
  50415. class AES {
  50416. constructor(key) {
  50417. /**
  50418. * The expanded S-box and inverse S-box tables. These will be computed
  50419. * on the client so that we don't have to send them down the wire.
  50420. *
  50421. * There are two tables, _tables[0] is for encryption and
  50422. * _tables[1] is for decryption.
  50423. *
  50424. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  50425. * last (_tables[01][4]) is the S-box itself.
  50426. *
  50427. * @private
  50428. */
  50429. // if we have yet to precompute the S-box tables
  50430. // do so now
  50431. if (!aesTables) {
  50432. aesTables = precompute();
  50433. } // then make a copy of that object for use
  50434. 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()]];
  50435. let i;
  50436. let j;
  50437. let tmp;
  50438. const sbox = this._tables[0][4];
  50439. const decTable = this._tables[1];
  50440. const keyLen = key.length;
  50441. let rcon = 1;
  50442. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  50443. throw new Error('Invalid aes key size');
  50444. }
  50445. const encKey = key.slice(0);
  50446. const decKey = [];
  50447. this._key = [encKey, decKey]; // schedule encryption keys
  50448. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  50449. tmp = encKey[i - 1]; // apply sbox
  50450. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  50451. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  50452. if (i % keyLen === 0) {
  50453. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  50454. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  50455. }
  50456. }
  50457. encKey[i] = encKey[i - keyLen] ^ tmp;
  50458. } // schedule decryption keys
  50459. for (j = 0; i; j++, i--) {
  50460. tmp = encKey[j & 3 ? i : i - 4];
  50461. if (i <= 4 || j < 4) {
  50462. decKey[j] = tmp;
  50463. } else {
  50464. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  50465. }
  50466. }
  50467. }
  50468. /**
  50469. * Decrypt 16 bytes, specified as four 32-bit words.
  50470. *
  50471. * @param {number} encrypted0 the first word to decrypt
  50472. * @param {number} encrypted1 the second word to decrypt
  50473. * @param {number} encrypted2 the third word to decrypt
  50474. * @param {number} encrypted3 the fourth word to decrypt
  50475. * @param {Int32Array} out the array to write the decrypted words
  50476. * into
  50477. * @param {number} offset the offset into the output array to start
  50478. * writing results
  50479. * @return {Array} The plaintext.
  50480. */
  50481. decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  50482. const key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  50483. let a = encrypted0 ^ key[0];
  50484. let b = encrypted3 ^ key[1];
  50485. let c = encrypted2 ^ key[2];
  50486. let d = encrypted1 ^ key[3];
  50487. let a2;
  50488. let b2;
  50489. let c2; // key.length === 2 ?
  50490. const nInnerRounds = key.length / 4 - 2;
  50491. let i;
  50492. let kIndex = 4;
  50493. const table = this._tables[1]; // load up the tables
  50494. const table0 = table[0];
  50495. const table1 = table[1];
  50496. const table2 = table[2];
  50497. const table3 = table[3];
  50498. const sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  50499. for (i = 0; i < nInnerRounds; i++) {
  50500. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  50501. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  50502. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  50503. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  50504. kIndex += 4;
  50505. a = a2;
  50506. b = b2;
  50507. c = c2;
  50508. } // Last round.
  50509. for (i = 0; i < 4; i++) {
  50510. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  50511. a2 = a;
  50512. a = b;
  50513. b = c;
  50514. c = d;
  50515. d = a2;
  50516. }
  50517. }
  50518. }
  50519. /**
  50520. * @file async-stream.js
  50521. */
  50522. /**
  50523. * A wrapper around the Stream class to use setTimeout
  50524. * and run stream "jobs" Asynchronously
  50525. *
  50526. * @class AsyncStream
  50527. * @extends Stream
  50528. */
  50529. class AsyncStream extends Stream {
  50530. constructor() {
  50531. super(Stream);
  50532. this.jobs = [];
  50533. this.delay = 1;
  50534. this.timeout_ = null;
  50535. }
  50536. /**
  50537. * process an async job
  50538. *
  50539. * @private
  50540. */
  50541. processJob_() {
  50542. this.jobs.shift()();
  50543. if (this.jobs.length) {
  50544. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  50545. } else {
  50546. this.timeout_ = null;
  50547. }
  50548. }
  50549. /**
  50550. * push a job into the stream
  50551. *
  50552. * @param {Function} job the job to push into the stream
  50553. */
  50554. push(job) {
  50555. this.jobs.push(job);
  50556. if (!this.timeout_) {
  50557. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  50558. }
  50559. }
  50560. }
  50561. /**
  50562. * @file decrypter.js
  50563. *
  50564. * An asynchronous implementation of AES-128 CBC decryption with
  50565. * PKCS#7 padding.
  50566. */
  50567. /**
  50568. * Convert network-order (big-endian) bytes into their little-endian
  50569. * representation.
  50570. */
  50571. const ntoh = function (word) {
  50572. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  50573. };
  50574. /**
  50575. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  50576. *
  50577. * @param {Uint8Array} encrypted the encrypted bytes
  50578. * @param {Uint32Array} key the bytes of the decryption key
  50579. * @param {Uint32Array} initVector the initialization vector (IV) to
  50580. * use for the first round of CBC.
  50581. * @return {Uint8Array} the decrypted bytes
  50582. *
  50583. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  50584. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  50585. * @see https://tools.ietf.org/html/rfc2315
  50586. */
  50587. const decrypt = function (encrypted, key, initVector) {
  50588. // word-level access to the encrypted bytes
  50589. const encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  50590. const decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  50591. const decrypted = new Uint8Array(encrypted.byteLength);
  50592. const decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  50593. // decrypted data
  50594. let init0;
  50595. let init1;
  50596. let init2;
  50597. let init3;
  50598. let encrypted0;
  50599. let encrypted1;
  50600. let encrypted2;
  50601. let encrypted3; // iteration variable
  50602. let wordIx; // pull out the words of the IV to ensure we don't modify the
  50603. // passed-in reference and easier access
  50604. init0 = initVector[0];
  50605. init1 = initVector[1];
  50606. init2 = initVector[2];
  50607. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  50608. // to each decrypted block
  50609. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  50610. // convert big-endian (network order) words into little-endian
  50611. // (javascript order)
  50612. encrypted0 = ntoh(encrypted32[wordIx]);
  50613. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  50614. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  50615. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  50616. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  50617. // plaintext
  50618. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  50619. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  50620. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  50621. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  50622. init0 = encrypted0;
  50623. init1 = encrypted1;
  50624. init2 = encrypted2;
  50625. init3 = encrypted3;
  50626. }
  50627. return decrypted;
  50628. };
  50629. /**
  50630. * The `Decrypter` class that manages decryption of AES
  50631. * data through `AsyncStream` objects and the `decrypt`
  50632. * function
  50633. *
  50634. * @param {Uint8Array} encrypted the encrypted bytes
  50635. * @param {Uint32Array} key the bytes of the decryption key
  50636. * @param {Uint32Array} initVector the initialization vector (IV) to
  50637. * @param {Function} done the function to run when done
  50638. * @class Decrypter
  50639. */
  50640. class Decrypter {
  50641. constructor(encrypted, key, initVector, done) {
  50642. const step = Decrypter.STEP;
  50643. const encrypted32 = new Int32Array(encrypted.buffer);
  50644. const decrypted = new Uint8Array(encrypted.byteLength);
  50645. let i = 0;
  50646. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  50647. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  50648. for (i = step; i < encrypted32.length; i += step) {
  50649. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  50650. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  50651. } // invoke the done() callback when everything is finished
  50652. this.asyncStream_.push(function () {
  50653. // remove pkcs#7 padding from the decrypted bytes
  50654. done(null, unpad(decrypted));
  50655. });
  50656. }
  50657. /**
  50658. * a getter for step the maximum number of bytes to process at one time
  50659. *
  50660. * @return {number} the value of step 32000
  50661. */
  50662. static get STEP() {
  50663. // 4 * 8000;
  50664. return 32000;
  50665. }
  50666. /**
  50667. * @private
  50668. */
  50669. decryptChunk_(encrypted, key, initVector, decrypted) {
  50670. return function () {
  50671. const bytes = decrypt(encrypted, key, initVector);
  50672. decrypted.set(bytes, encrypted.byteOffset);
  50673. };
  50674. }
  50675. }
  50676. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  50677. var win;
  50678. if (typeof window !== "undefined") {
  50679. win = window;
  50680. } else if (typeof commonjsGlobal !== "undefined") {
  50681. win = commonjsGlobal;
  50682. } else if (typeof self !== "undefined") {
  50683. win = self;
  50684. } else {
  50685. win = {};
  50686. }
  50687. var window_1 = win;
  50688. var isArrayBufferView = function isArrayBufferView(obj) {
  50689. if (ArrayBuffer.isView === 'function') {
  50690. return ArrayBuffer.isView(obj);
  50691. }
  50692. return obj && obj.buffer instanceof ArrayBuffer;
  50693. };
  50694. var BigInt = window_1.BigInt || Number;
  50695. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  50696. (function () {
  50697. var a = new Uint16Array([0xFFCC]);
  50698. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  50699. if (b[0] === 0xFF) {
  50700. return 'big';
  50701. }
  50702. if (b[0] === 0xCC) {
  50703. return 'little';
  50704. }
  50705. return 'unknown';
  50706. })();
  50707. /**
  50708. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  50709. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  50710. *
  50711. * @param {Object} message
  50712. * Object of properties and values to send to the web worker
  50713. * @return {Object}
  50714. * Modified message with TypedArray values expanded
  50715. * @function createTransferableMessage
  50716. */
  50717. const createTransferableMessage = function (message) {
  50718. const transferable = {};
  50719. Object.keys(message).forEach(key => {
  50720. const value = message[key];
  50721. if (isArrayBufferView(value)) {
  50722. transferable[key] = {
  50723. bytes: value.buffer,
  50724. byteOffset: value.byteOffset,
  50725. byteLength: value.byteLength
  50726. };
  50727. } else {
  50728. transferable[key] = value;
  50729. }
  50730. });
  50731. return transferable;
  50732. };
  50733. /* global self */
  50734. /**
  50735. * Our web worker interface so that things can talk to aes-decrypter
  50736. * that will be running in a web worker. the scope is passed to this by
  50737. * webworkify.
  50738. */
  50739. self.onmessage = function (event) {
  50740. const data = event.data;
  50741. const encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  50742. const key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  50743. const iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  50744. /* eslint-disable no-new, handle-callback-err */
  50745. new Decrypter(encrypted, key, iv, function (err, bytes) {
  50746. self.postMessage(createTransferableMessage({
  50747. source: data.source,
  50748. decrypted: bytes
  50749. }), [bytes.buffer]);
  50750. });
  50751. /* eslint-enable */
  50752. };
  50753. }));
  50754. var Decrypter = factory(workerCode);
  50755. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  50756. /**
  50757. * Convert the properties of an HLS track into an audioTrackKind.
  50758. *
  50759. * @private
  50760. */
  50761. const audioTrackKind_ = properties => {
  50762. let kind = properties.default ? 'main' : 'alternative';
  50763. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  50764. kind = 'main-desc';
  50765. }
  50766. return kind;
  50767. };
  50768. /**
  50769. * Pause provided segment loader and playlist loader if active
  50770. *
  50771. * @param {SegmentLoader} segmentLoader
  50772. * SegmentLoader to pause
  50773. * @param {Object} mediaType
  50774. * Active media type
  50775. * @function stopLoaders
  50776. */
  50777. const stopLoaders = (segmentLoader, mediaType) => {
  50778. segmentLoader.abort();
  50779. segmentLoader.pause();
  50780. if (mediaType && mediaType.activePlaylistLoader) {
  50781. mediaType.activePlaylistLoader.pause();
  50782. mediaType.activePlaylistLoader = null;
  50783. }
  50784. };
  50785. /**
  50786. * Start loading provided segment loader and playlist loader
  50787. *
  50788. * @param {PlaylistLoader} playlistLoader
  50789. * PlaylistLoader to start loading
  50790. * @param {Object} mediaType
  50791. * Active media type
  50792. * @function startLoaders
  50793. */
  50794. const startLoaders = (playlistLoader, mediaType) => {
  50795. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  50796. // playlist loader
  50797. mediaType.activePlaylistLoader = playlistLoader;
  50798. playlistLoader.load();
  50799. };
  50800. /**
  50801. * Returns a function to be called when the media group changes. It performs a
  50802. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  50803. * change of group is merely a rendition switch of the same content at another encoding,
  50804. * rather than a change of content, such as switching audio from English to Spanish.
  50805. *
  50806. * @param {string} type
  50807. * MediaGroup type
  50808. * @param {Object} settings
  50809. * Object containing required information for media groups
  50810. * @return {Function}
  50811. * Handler for a non-destructive resync of SegmentLoader when the active media
  50812. * group changes.
  50813. * @function onGroupChanged
  50814. */
  50815. const onGroupChanged = (type, settings) => () => {
  50816. const {
  50817. segmentLoaders: {
  50818. [type]: segmentLoader,
  50819. main: mainSegmentLoader
  50820. },
  50821. mediaTypes: {
  50822. [type]: mediaType
  50823. }
  50824. } = settings;
  50825. const activeTrack = mediaType.activeTrack();
  50826. const activeGroup = mediaType.getActiveGroup();
  50827. const previousActiveLoader = mediaType.activePlaylistLoader;
  50828. const lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  50829. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  50830. return;
  50831. }
  50832. mediaType.lastGroup_ = activeGroup;
  50833. mediaType.lastTrack_ = activeTrack;
  50834. stopLoaders(segmentLoader, mediaType);
  50835. if (!activeGroup || activeGroup.isMainPlaylist) {
  50836. // there is no group active or active group is a main playlist and won't change
  50837. return;
  50838. }
  50839. if (!activeGroup.playlistLoader) {
  50840. if (previousActiveLoader) {
  50841. // The previous group had a playlist loader but the new active group does not
  50842. // this means we are switching from demuxed to muxed audio. In this case we want to
  50843. // do a destructive reset of the main segment loader and not restart the audio
  50844. // loaders.
  50845. mainSegmentLoader.resetEverything();
  50846. }
  50847. return;
  50848. } // Non-destructive resync
  50849. segmentLoader.resyncLoader();
  50850. startLoaders(activeGroup.playlistLoader, mediaType);
  50851. };
  50852. const onGroupChanging = (type, settings) => () => {
  50853. const {
  50854. segmentLoaders: {
  50855. [type]: segmentLoader
  50856. },
  50857. mediaTypes: {
  50858. [type]: mediaType
  50859. }
  50860. } = settings;
  50861. mediaType.lastGroup_ = null;
  50862. segmentLoader.abort();
  50863. segmentLoader.pause();
  50864. };
  50865. /**
  50866. * Returns a function to be called when the media track changes. It performs a
  50867. * destructive reset of the SegmentLoader to ensure we start loading as close to
  50868. * currentTime as possible.
  50869. *
  50870. * @param {string} type
  50871. * MediaGroup type
  50872. * @param {Object} settings
  50873. * Object containing required information for media groups
  50874. * @return {Function}
  50875. * Handler for a destructive reset of SegmentLoader when the active media
  50876. * track changes.
  50877. * @function onTrackChanged
  50878. */
  50879. const onTrackChanged = (type, settings) => () => {
  50880. const {
  50881. mainPlaylistLoader,
  50882. segmentLoaders: {
  50883. [type]: segmentLoader,
  50884. main: mainSegmentLoader
  50885. },
  50886. mediaTypes: {
  50887. [type]: mediaType
  50888. }
  50889. } = settings;
  50890. const activeTrack = mediaType.activeTrack();
  50891. const activeGroup = mediaType.getActiveGroup();
  50892. const previousActiveLoader = mediaType.activePlaylistLoader;
  50893. const lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  50894. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  50895. return;
  50896. }
  50897. mediaType.lastGroup_ = activeGroup;
  50898. mediaType.lastTrack_ = activeTrack;
  50899. stopLoaders(segmentLoader, mediaType);
  50900. if (!activeGroup) {
  50901. // there is no group active so we do not want to restart loaders
  50902. return;
  50903. }
  50904. if (activeGroup.isMainPlaylist) {
  50905. // track did not change, do nothing
  50906. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  50907. return;
  50908. }
  50909. const pc = settings.vhs.playlistController_;
  50910. const newPlaylist = pc.selectPlaylist(); // media will not change do nothing
  50911. if (pc.media() === newPlaylist) {
  50912. return;
  50913. }
  50914. mediaType.logger_(`track change. Switching main audio from ${lastTrack.id} to ${activeTrack.id}`);
  50915. mainPlaylistLoader.pause();
  50916. mainSegmentLoader.resetEverything();
  50917. pc.fastQualityChange_(newPlaylist);
  50918. return;
  50919. }
  50920. if (type === 'AUDIO') {
  50921. if (!activeGroup.playlistLoader) {
  50922. // when switching from demuxed audio/video to muxed audio/video (noted by no
  50923. // playlist loader for the audio group), we want to do a destructive reset of the
  50924. // main segment loader and not restart the audio loaders
  50925. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  50926. // it should be stopped
  50927. mainSegmentLoader.resetEverything();
  50928. return;
  50929. } // although the segment loader is an audio segment loader, call the setAudio
  50930. // function to ensure it is prepared to re-append the init segment (or handle other
  50931. // config changes)
  50932. segmentLoader.setAudio(true);
  50933. mainSegmentLoader.setAudio(false);
  50934. }
  50935. if (previousActiveLoader === activeGroup.playlistLoader) {
  50936. // Nothing has actually changed. This can happen because track change events can fire
  50937. // multiple times for a "single" change. One for enabling the new active track, and
  50938. // one for disabling the track that was active
  50939. startLoaders(activeGroup.playlistLoader, mediaType);
  50940. return;
  50941. }
  50942. if (segmentLoader.track) {
  50943. // For WebVTT, set the new text track in the segmentloader
  50944. segmentLoader.track(activeTrack);
  50945. } // destructive reset
  50946. segmentLoader.resetEverything();
  50947. startLoaders(activeGroup.playlistLoader, mediaType);
  50948. };
  50949. const onError = {
  50950. /**
  50951. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  50952. * an error.
  50953. *
  50954. * @param {string} type
  50955. * MediaGroup type
  50956. * @param {Object} settings
  50957. * Object containing required information for media groups
  50958. * @return {Function}
  50959. * Error handler. Logs warning (or error if the playlist is excluded) to
  50960. * console and switches back to default audio track.
  50961. * @function onError.AUDIO
  50962. */
  50963. AUDIO: (type, settings) => () => {
  50964. const {
  50965. segmentLoaders: {
  50966. [type]: segmentLoader
  50967. },
  50968. mediaTypes: {
  50969. [type]: mediaType
  50970. },
  50971. excludePlaylist
  50972. } = settings;
  50973. stopLoaders(segmentLoader, mediaType); // switch back to default audio track
  50974. const activeTrack = mediaType.activeTrack();
  50975. const activeGroup = mediaType.activeGroup();
  50976. const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;
  50977. const defaultTrack = mediaType.tracks[id];
  50978. if (activeTrack === defaultTrack) {
  50979. // Default track encountered an error. All we can do now is exclude the current
  50980. // rendition and hope another will switch audio groups
  50981. excludePlaylist({
  50982. error: {
  50983. message: 'Problem encountered loading the default audio track.'
  50984. }
  50985. });
  50986. return;
  50987. }
  50988. videojs.log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  50989. for (const trackId in mediaType.tracks) {
  50990. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  50991. }
  50992. mediaType.onTrackChanged();
  50993. },
  50994. /**
  50995. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  50996. * an error.
  50997. *
  50998. * @param {string} type
  50999. * MediaGroup type
  51000. * @param {Object} settings
  51001. * Object containing required information for media groups
  51002. * @return {Function}
  51003. * Error handler. Logs warning to console and disables the active subtitle track
  51004. * @function onError.SUBTITLES
  51005. */
  51006. SUBTITLES: (type, settings) => () => {
  51007. const {
  51008. segmentLoaders: {
  51009. [type]: segmentLoader
  51010. },
  51011. mediaTypes: {
  51012. [type]: mediaType
  51013. }
  51014. } = settings;
  51015. videojs.log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  51016. stopLoaders(segmentLoader, mediaType);
  51017. const track = mediaType.activeTrack();
  51018. if (track) {
  51019. track.mode = 'disabled';
  51020. }
  51021. mediaType.onTrackChanged();
  51022. }
  51023. };
  51024. const setupListeners = {
  51025. /**
  51026. * Setup event listeners for audio playlist loader
  51027. *
  51028. * @param {string} type
  51029. * MediaGroup type
  51030. * @param {PlaylistLoader|null} playlistLoader
  51031. * PlaylistLoader to register listeners on
  51032. * @param {Object} settings
  51033. * Object containing required information for media groups
  51034. * @function setupListeners.AUDIO
  51035. */
  51036. AUDIO: (type, playlistLoader, settings) => {
  51037. if (!playlistLoader) {
  51038. // no playlist loader means audio will be muxed with the video
  51039. return;
  51040. }
  51041. const {
  51042. tech,
  51043. requestOptions,
  51044. segmentLoaders: {
  51045. [type]: segmentLoader
  51046. }
  51047. } = settings;
  51048. playlistLoader.on('loadedmetadata', () => {
  51049. const media = playlistLoader.media();
  51050. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  51051. // permits, start downloading segments
  51052. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  51053. segmentLoader.load();
  51054. }
  51055. });
  51056. playlistLoader.on('loadedplaylist', () => {
  51057. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  51058. if (!tech.paused()) {
  51059. segmentLoader.load();
  51060. }
  51061. });
  51062. playlistLoader.on('error', onError[type](type, settings));
  51063. },
  51064. /**
  51065. * Setup event listeners for subtitle playlist loader
  51066. *
  51067. * @param {string} type
  51068. * MediaGroup type
  51069. * @param {PlaylistLoader|null} playlistLoader
  51070. * PlaylistLoader to register listeners on
  51071. * @param {Object} settings
  51072. * Object containing required information for media groups
  51073. * @function setupListeners.SUBTITLES
  51074. */
  51075. SUBTITLES: (type, playlistLoader, settings) => {
  51076. const {
  51077. tech,
  51078. requestOptions,
  51079. segmentLoaders: {
  51080. [type]: segmentLoader
  51081. },
  51082. mediaTypes: {
  51083. [type]: mediaType
  51084. }
  51085. } = settings;
  51086. playlistLoader.on('loadedmetadata', () => {
  51087. const media = playlistLoader.media();
  51088. segmentLoader.playlist(media, requestOptions);
  51089. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  51090. // permits, start downloading segments
  51091. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  51092. segmentLoader.load();
  51093. }
  51094. });
  51095. playlistLoader.on('loadedplaylist', () => {
  51096. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  51097. if (!tech.paused()) {
  51098. segmentLoader.load();
  51099. }
  51100. });
  51101. playlistLoader.on('error', onError[type](type, settings));
  51102. }
  51103. };
  51104. const initialize = {
  51105. /**
  51106. * Setup PlaylistLoaders and AudioTracks for the audio groups
  51107. *
  51108. * @param {string} type
  51109. * MediaGroup type
  51110. * @param {Object} settings
  51111. * Object containing required information for media groups
  51112. * @function initialize.AUDIO
  51113. */
  51114. 'AUDIO': (type, settings) => {
  51115. const {
  51116. vhs,
  51117. sourceType,
  51118. segmentLoaders: {
  51119. [type]: segmentLoader
  51120. },
  51121. requestOptions,
  51122. main: {
  51123. mediaGroups
  51124. },
  51125. mediaTypes: {
  51126. [type]: {
  51127. groups,
  51128. tracks,
  51129. logger_
  51130. }
  51131. },
  51132. mainPlaylistLoader
  51133. } = settings;
  51134. const audioOnlyMain = isAudioOnly(mainPlaylistLoader.main); // force a default if we have none
  51135. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  51136. mediaGroups[type] = {
  51137. main: {
  51138. default: {
  51139. default: true
  51140. }
  51141. }
  51142. };
  51143. if (audioOnlyMain) {
  51144. mediaGroups[type].main.default.playlists = mainPlaylistLoader.main.playlists;
  51145. }
  51146. }
  51147. for (const groupId in mediaGroups[type]) {
  51148. if (!groups[groupId]) {
  51149. groups[groupId] = [];
  51150. }
  51151. for (const variantLabel in mediaGroups[type][groupId]) {
  51152. let properties = mediaGroups[type][groupId][variantLabel];
  51153. let playlistLoader;
  51154. if (audioOnlyMain) {
  51155. logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a main playlist`);
  51156. properties.isMainPlaylist = true;
  51157. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  51158. // use the resolved media playlist object
  51159. } else if (sourceType === 'vhs-json' && properties.playlists) {
  51160. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  51161. } else if (properties.resolvedUri) {
  51162. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  51163. // should we even have properties.playlists in this check.
  51164. } else if (properties.playlists && sourceType === 'dash') {
  51165. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  51166. } else {
  51167. // no resolvedUri means the audio is muxed with the video when using this
  51168. // audio track
  51169. playlistLoader = null;
  51170. }
  51171. properties = merge({
  51172. id: variantLabel,
  51173. playlistLoader
  51174. }, properties);
  51175. setupListeners[type](type, properties.playlistLoader, settings);
  51176. groups[groupId].push(properties);
  51177. if (typeof tracks[variantLabel] === 'undefined') {
  51178. const track = new videojs.AudioTrack({
  51179. id: variantLabel,
  51180. kind: audioTrackKind_(properties),
  51181. enabled: false,
  51182. language: properties.language,
  51183. default: properties.default,
  51184. label: variantLabel
  51185. });
  51186. tracks[variantLabel] = track;
  51187. }
  51188. }
  51189. } // setup single error event handler for the segment loader
  51190. segmentLoader.on('error', onError[type](type, settings));
  51191. },
  51192. /**
  51193. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  51194. *
  51195. * @param {string} type
  51196. * MediaGroup type
  51197. * @param {Object} settings
  51198. * Object containing required information for media groups
  51199. * @function initialize.SUBTITLES
  51200. */
  51201. 'SUBTITLES': (type, settings) => {
  51202. const {
  51203. tech,
  51204. vhs,
  51205. sourceType,
  51206. segmentLoaders: {
  51207. [type]: segmentLoader
  51208. },
  51209. requestOptions,
  51210. main: {
  51211. mediaGroups
  51212. },
  51213. mediaTypes: {
  51214. [type]: {
  51215. groups,
  51216. tracks
  51217. }
  51218. },
  51219. mainPlaylistLoader
  51220. } = settings;
  51221. for (const groupId in mediaGroups[type]) {
  51222. if (!groups[groupId]) {
  51223. groups[groupId] = [];
  51224. }
  51225. for (const variantLabel in mediaGroups[type][groupId]) {
  51226. if (mediaGroups[type][groupId][variantLabel].forced) {
  51227. // Subtitle playlists with the forced attribute are not selectable in Safari.
  51228. // According to Apple's HLS Authoring Specification:
  51229. // If content has forced subtitles and regular subtitles in a given language,
  51230. // the regular subtitles track in that language MUST contain both the forced
  51231. // subtitles and the regular subtitles for that language.
  51232. // Because of this requirement and that Safari does not add forced subtitles,
  51233. // forced subtitles are skipped here to maintain consistent experience across
  51234. // all platforms
  51235. continue;
  51236. }
  51237. let properties = mediaGroups[type][groupId][variantLabel];
  51238. let playlistLoader;
  51239. if (sourceType === 'hls') {
  51240. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  51241. } else if (sourceType === 'dash') {
  51242. const playlists = properties.playlists.filter(p => p.excludeUntil !== Infinity);
  51243. if (!playlists.length) {
  51244. return;
  51245. }
  51246. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  51247. } else if (sourceType === 'vhs-json') {
  51248. playlistLoader = new PlaylistLoader(
  51249. // if the vhs-json object included the media playlist, use the media playlist
  51250. // as provided, otherwise use the resolved URI to load the playlist
  51251. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  51252. }
  51253. properties = merge({
  51254. id: variantLabel,
  51255. playlistLoader
  51256. }, properties);
  51257. setupListeners[type](type, properties.playlistLoader, settings);
  51258. groups[groupId].push(properties);
  51259. if (typeof tracks[variantLabel] === 'undefined') {
  51260. const track = tech.addRemoteTextTrack({
  51261. id: variantLabel,
  51262. kind: 'subtitles',
  51263. default: properties.default && properties.autoselect,
  51264. language: properties.language,
  51265. label: variantLabel
  51266. }, false).track;
  51267. tracks[variantLabel] = track;
  51268. }
  51269. }
  51270. } // setup single error event handler for the segment loader
  51271. segmentLoader.on('error', onError[type](type, settings));
  51272. },
  51273. /**
  51274. * Setup TextTracks for the closed-caption groups
  51275. *
  51276. * @param {String} type
  51277. * MediaGroup type
  51278. * @param {Object} settings
  51279. * Object containing required information for media groups
  51280. * @function initialize['CLOSED-CAPTIONS']
  51281. */
  51282. 'CLOSED-CAPTIONS': (type, settings) => {
  51283. const {
  51284. tech,
  51285. main: {
  51286. mediaGroups
  51287. },
  51288. mediaTypes: {
  51289. [type]: {
  51290. groups,
  51291. tracks
  51292. }
  51293. }
  51294. } = settings;
  51295. for (const groupId in mediaGroups[type]) {
  51296. if (!groups[groupId]) {
  51297. groups[groupId] = [];
  51298. }
  51299. for (const variantLabel in mediaGroups[type][groupId]) {
  51300. const properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  51301. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  51302. continue;
  51303. }
  51304. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  51305. let newProps = {
  51306. label: variantLabel,
  51307. language: properties.language,
  51308. instreamId: properties.instreamId,
  51309. default: properties.default && properties.autoselect
  51310. };
  51311. if (captionServices[newProps.instreamId]) {
  51312. newProps = merge(newProps, captionServices[newProps.instreamId]);
  51313. }
  51314. if (newProps.default === undefined) {
  51315. delete newProps.default;
  51316. } // No PlaylistLoader is required for Closed-Captions because the captions are
  51317. // embedded within the video stream
  51318. groups[groupId].push(merge({
  51319. id: variantLabel
  51320. }, properties));
  51321. if (typeof tracks[variantLabel] === 'undefined') {
  51322. const track = tech.addRemoteTextTrack({
  51323. id: newProps.instreamId,
  51324. kind: 'captions',
  51325. default: newProps.default,
  51326. language: newProps.language,
  51327. label: newProps.label
  51328. }, false).track;
  51329. tracks[variantLabel] = track;
  51330. }
  51331. }
  51332. }
  51333. }
  51334. };
  51335. const groupMatch = (list, media) => {
  51336. for (let i = 0; i < list.length; i++) {
  51337. if (playlistMatch(media, list[i])) {
  51338. return true;
  51339. }
  51340. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  51341. return true;
  51342. }
  51343. }
  51344. return false;
  51345. };
  51346. /**
  51347. * Returns a function used to get the active group of the provided type
  51348. *
  51349. * @param {string} type
  51350. * MediaGroup type
  51351. * @param {Object} settings
  51352. * Object containing required information for media groups
  51353. * @return {Function}
  51354. * Function that returns the active media group for the provided type. Takes an
  51355. * optional parameter {TextTrack} track. If no track is provided, a list of all
  51356. * variants in the group, otherwise the variant corresponding to the provided
  51357. * track is returned.
  51358. * @function activeGroup
  51359. */
  51360. const activeGroup = (type, settings) => track => {
  51361. const {
  51362. mainPlaylistLoader,
  51363. mediaTypes: {
  51364. [type]: {
  51365. groups
  51366. }
  51367. }
  51368. } = settings;
  51369. const media = mainPlaylistLoader.media();
  51370. if (!media) {
  51371. return null;
  51372. }
  51373. let variants = null; // set to variants to main media active group
  51374. if (media.attributes[type]) {
  51375. variants = groups[media.attributes[type]];
  51376. }
  51377. const groupKeys = Object.keys(groups);
  51378. if (!variants) {
  51379. // find the mainPlaylistLoader media
  51380. // that is in a media group if we are dealing
  51381. // with audio only
  51382. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.main)) {
  51383. for (let i = 0; i < groupKeys.length; i++) {
  51384. const groupPropertyList = groups[groupKeys[i]];
  51385. if (groupMatch(groupPropertyList, media)) {
  51386. variants = groupPropertyList;
  51387. break;
  51388. }
  51389. } // use the main group if it exists
  51390. } else if (groups.main) {
  51391. variants = groups.main; // only one group, use that one
  51392. } else if (groupKeys.length === 1) {
  51393. variants = groups[groupKeys[0]];
  51394. }
  51395. }
  51396. if (typeof track === 'undefined') {
  51397. return variants;
  51398. }
  51399. if (track === null || !variants) {
  51400. // An active track was specified so a corresponding group is expected. track === null
  51401. // means no track is currently active so there is no corresponding group
  51402. return null;
  51403. }
  51404. return variants.filter(props => props.id === track.id)[0] || null;
  51405. };
  51406. const activeTrack = {
  51407. /**
  51408. * Returns a function used to get the active track of type provided
  51409. *
  51410. * @param {string} type
  51411. * MediaGroup type
  51412. * @param {Object} settings
  51413. * Object containing required information for media groups
  51414. * @return {Function}
  51415. * Function that returns the active media track for the provided type. Returns
  51416. * null if no track is active
  51417. * @function activeTrack.AUDIO
  51418. */
  51419. AUDIO: (type, settings) => () => {
  51420. const {
  51421. mediaTypes: {
  51422. [type]: {
  51423. tracks
  51424. }
  51425. }
  51426. } = settings;
  51427. for (const id in tracks) {
  51428. if (tracks[id].enabled) {
  51429. return tracks[id];
  51430. }
  51431. }
  51432. return null;
  51433. },
  51434. /**
  51435. * Returns a function used to get the active track of type provided
  51436. *
  51437. * @param {string} type
  51438. * MediaGroup type
  51439. * @param {Object} settings
  51440. * Object containing required information for media groups
  51441. * @return {Function}
  51442. * Function that returns the active media track for the provided type. Returns
  51443. * null if no track is active
  51444. * @function activeTrack.SUBTITLES
  51445. */
  51446. SUBTITLES: (type, settings) => () => {
  51447. const {
  51448. mediaTypes: {
  51449. [type]: {
  51450. tracks
  51451. }
  51452. }
  51453. } = settings;
  51454. for (const id in tracks) {
  51455. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  51456. return tracks[id];
  51457. }
  51458. }
  51459. return null;
  51460. }
  51461. };
  51462. const getActiveGroup = (type, {
  51463. mediaTypes
  51464. }) => () => {
  51465. const activeTrack_ = mediaTypes[type].activeTrack();
  51466. if (!activeTrack_) {
  51467. return null;
  51468. }
  51469. return mediaTypes[type].activeGroup(activeTrack_);
  51470. };
  51471. /**
  51472. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  51473. * Closed-Captions) specified in the main manifest.
  51474. *
  51475. * @param {Object} settings
  51476. * Object containing required information for setting up the media groups
  51477. * @param {Tech} settings.tech
  51478. * The tech of the player
  51479. * @param {Object} settings.requestOptions
  51480. * XHR request options used by the segment loaders
  51481. * @param {PlaylistLoader} settings.mainPlaylistLoader
  51482. * PlaylistLoader for the main source
  51483. * @param {VhsHandler} settings.vhs
  51484. * VHS SourceHandler
  51485. * @param {Object} settings.main
  51486. * The parsed main manifest
  51487. * @param {Object} settings.mediaTypes
  51488. * Object to store the loaders, tracks, and utility methods for each media type
  51489. * @param {Function} settings.excludePlaylist
  51490. * Excludes the current rendition and forces a rendition switch.
  51491. * @function setupMediaGroups
  51492. */
  51493. const setupMediaGroups = settings => {
  51494. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  51495. initialize[type](type, settings);
  51496. });
  51497. const {
  51498. mediaTypes,
  51499. mainPlaylistLoader,
  51500. tech,
  51501. vhs,
  51502. segmentLoaders: {
  51503. ['AUDIO']: audioSegmentLoader,
  51504. main: mainSegmentLoader
  51505. }
  51506. } = settings; // setup active group and track getters and change event handlers
  51507. ['AUDIO', 'SUBTITLES'].forEach(type => {
  51508. mediaTypes[type].activeGroup = activeGroup(type, settings);
  51509. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  51510. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  51511. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  51512. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  51513. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  51514. }); // DO NOT enable the default subtitle or caption track.
  51515. // DO enable the default audio track
  51516. const audioGroup = mediaTypes.AUDIO.activeGroup();
  51517. if (audioGroup) {
  51518. const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;
  51519. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  51520. mediaTypes.AUDIO.onGroupChanged();
  51521. mediaTypes.AUDIO.onTrackChanged();
  51522. const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  51523. // track is changed, but needs to be handled here since the track may not be considered
  51524. // changed on the first call to onTrackChanged
  51525. if (!activeAudioGroup.playlistLoader) {
  51526. // either audio is muxed with video or the stream is audio only
  51527. mainSegmentLoader.setAudio(true);
  51528. } else {
  51529. // audio is demuxed
  51530. mainSegmentLoader.setAudio(false);
  51531. audioSegmentLoader.setAudio(true);
  51532. }
  51533. }
  51534. mainPlaylistLoader.on('mediachange', () => {
  51535. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());
  51536. });
  51537. mainPlaylistLoader.on('mediachanging', () => {
  51538. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());
  51539. }); // custom audio track change event handler for usage event
  51540. const onAudioTrackChanged = () => {
  51541. mediaTypes.AUDIO.onTrackChanged();
  51542. tech.trigger({
  51543. type: 'usage',
  51544. name: 'vhs-audio-change'
  51545. });
  51546. };
  51547. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  51548. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  51549. vhs.on('dispose', () => {
  51550. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  51551. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  51552. }); // clear existing audio tracks and add the ones we just created
  51553. tech.clearTracks('audio');
  51554. for (const id in mediaTypes.AUDIO.tracks) {
  51555. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  51556. }
  51557. };
  51558. /**
  51559. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  51560. * media type
  51561. *
  51562. * @return {Object}
  51563. * Object to store the loaders, tracks, and utility methods for each media type
  51564. * @function createMediaTypes
  51565. */
  51566. const createMediaTypes = () => {
  51567. const mediaTypes = {};
  51568. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  51569. mediaTypes[type] = {
  51570. groups: {},
  51571. tracks: {},
  51572. activePlaylistLoader: null,
  51573. activeGroup: noop,
  51574. activeTrack: noop,
  51575. getActiveGroup: noop,
  51576. onGroupChanged: noop,
  51577. onTrackChanged: noop,
  51578. lastTrack_: null,
  51579. logger_: logger(`MediaGroups[${type}]`)
  51580. };
  51581. });
  51582. return mediaTypes;
  51583. };
  51584. /**
  51585. * @file playlist-controller.js
  51586. */
  51587. const ABORT_EARLY_EXCLUSION_SECONDS = 60 * 2;
  51588. let Vhs$1; // SegmentLoader stats that need to have each loader's
  51589. // values summed to calculate the final value
  51590. const loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  51591. const sumLoaderStat = function (stat) {
  51592. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  51593. };
  51594. const shouldSwitchToMedia = function ({
  51595. currentPlaylist,
  51596. buffered,
  51597. currentTime,
  51598. nextPlaylist,
  51599. bufferLowWaterLine,
  51600. bufferHighWaterLine,
  51601. duration,
  51602. bufferBasedABR,
  51603. log
  51604. }) {
  51605. // we have no other playlist to switch to
  51606. if (!nextPlaylist) {
  51607. videojs.log.warn('We received no playlist to switch to. Please check your stream.');
  51608. return false;
  51609. }
  51610. const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;
  51611. if (!currentPlaylist) {
  51612. log(`${sharedLogLine} as current playlist is not set`);
  51613. return true;
  51614. } // no need to switch if playlist is the same
  51615. if (nextPlaylist.id === currentPlaylist.id) {
  51616. return false;
  51617. } // determine if current time is in a buffered range.
  51618. const isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  51619. // This is because in LIVE, the player plays 3 segments from the end of the
  51620. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  51621. // in those segments, a viewer will never experience a rendition upswitch.
  51622. if (!currentPlaylist.endList) {
  51623. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  51624. // doubles the time to first playback.
  51625. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  51626. log(`not ${sharedLogLine} as current playlist is live llhls, but currentTime isn't in buffered.`);
  51627. return false;
  51628. }
  51629. log(`${sharedLogLine} as current playlist is live`);
  51630. return true;
  51631. }
  51632. const forwardBuffer = timeAheadOf(buffered, currentTime);
  51633. const maxBufferLowWaterLine = bufferBasedABR ? 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
  51634. // duration is below the max potential low water line
  51635. if (duration < maxBufferLowWaterLine) {
  51636. log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);
  51637. return true;
  51638. }
  51639. const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  51640. const currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  51641. // we can switch down
  51642. if (nextBandwidth < currBandwidth && (!bufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  51643. let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;
  51644. if (bufferBasedABR) {
  51645. logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;
  51646. }
  51647. log(logLine);
  51648. return true;
  51649. } // and if our buffer is higher than the low water line,
  51650. // we can switch up
  51651. if ((!bufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  51652. let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;
  51653. if (bufferBasedABR) {
  51654. logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;
  51655. }
  51656. log(logLine);
  51657. return true;
  51658. }
  51659. log(`not ${sharedLogLine} as no switching criteria met`);
  51660. return false;
  51661. };
  51662. /**
  51663. * the main playlist controller controller all interactons
  51664. * between playlists and segmentloaders. At this time this mainly
  51665. * involves a main playlist and a series of audio playlists
  51666. * if they are available
  51667. *
  51668. * @class PlaylistController
  51669. * @extends videojs.EventTarget
  51670. */
  51671. class PlaylistController extends videojs.EventTarget {
  51672. constructor(options) {
  51673. super();
  51674. const {
  51675. src,
  51676. withCredentials,
  51677. tech,
  51678. bandwidth,
  51679. externVhs,
  51680. useCueTags,
  51681. playlistExclusionDuration,
  51682. enableLowInitialPlaylist,
  51683. sourceType,
  51684. cacheEncryptionKeys,
  51685. bufferBasedABR,
  51686. leastPixelDiffSelector,
  51687. captionServices
  51688. } = options;
  51689. if (!src) {
  51690. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  51691. }
  51692. let {
  51693. maxPlaylistRetries
  51694. } = options;
  51695. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  51696. maxPlaylistRetries = Infinity;
  51697. }
  51698. Vhs$1 = externVhs;
  51699. this.bufferBasedABR = Boolean(bufferBasedABR);
  51700. this.leastPixelDiffSelector = Boolean(leastPixelDiffSelector);
  51701. this.withCredentials = withCredentials;
  51702. this.tech_ = tech;
  51703. this.vhs_ = tech.vhs;
  51704. this.sourceType_ = sourceType;
  51705. this.useCueTags_ = useCueTags;
  51706. this.playlistExclusionDuration = playlistExclusionDuration;
  51707. this.maxPlaylistRetries = maxPlaylistRetries;
  51708. this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  51709. if (this.useCueTags_) {
  51710. this.cueTagsTrack_ = this.tech_.addTextTrack('metadata', 'ad-cues');
  51711. this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  51712. }
  51713. this.requestOptions_ = {
  51714. withCredentials,
  51715. maxPlaylistRetries,
  51716. timeout: null
  51717. };
  51718. this.on('error', this.pauseLoading);
  51719. this.mediaTypes_ = createMediaTypes();
  51720. this.mediaSource = new window.MediaSource();
  51721. this.handleDurationChange_ = this.handleDurationChange_.bind(this);
  51722. this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);
  51723. this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);
  51724. this.mediaSource.addEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  51725. this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);
  51726. this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  51727. // everything, and the MediaSource should not be detached without a proper disposal
  51728. this.seekable_ = createTimeRanges();
  51729. this.hasPlayed_ = false;
  51730. this.syncController_ = new SyncController(options);
  51731. this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  51732. kind: 'metadata',
  51733. label: 'segment-metadata'
  51734. }, false).track;
  51735. this.decrypter_ = new Decrypter();
  51736. this.sourceUpdater_ = new SourceUpdater(this.mediaSource);
  51737. this.inbandTextTracks_ = {};
  51738. this.timelineChangeController_ = new TimelineChangeController();
  51739. const segmentLoaderSettings = {
  51740. vhs: this.vhs_,
  51741. parse708captions: options.parse708captions,
  51742. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  51743. captionServices,
  51744. mediaSource: this.mediaSource,
  51745. currentTime: this.tech_.currentTime.bind(this.tech_),
  51746. seekable: () => this.seekable(),
  51747. seeking: () => this.tech_.seeking(),
  51748. duration: () => this.duration(),
  51749. hasPlayed: () => this.hasPlayed_,
  51750. goalBufferLength: () => this.goalBufferLength(),
  51751. bandwidth,
  51752. syncController: this.syncController_,
  51753. decrypter: this.decrypter_,
  51754. sourceType: this.sourceType_,
  51755. inbandTextTracks: this.inbandTextTracks_,
  51756. cacheEncryptionKeys,
  51757. sourceUpdater: this.sourceUpdater_,
  51758. timelineChangeController: this.timelineChangeController_,
  51759. exactManifestTimings: options.exactManifestTimings
  51760. }; // The source type check not only determines whether a special DASH playlist loader
  51761. // should be used, but also covers the case where the provided src is a vhs-json
  51762. // manifest object (instead of a URL). In the case of vhs-json, the default
  51763. // PlaylistLoader should be used.
  51764. this.mainPlaylistLoader_ = this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, this.vhs_, this.requestOptions_) : new PlaylistLoader(src, this.vhs_, this.requestOptions_);
  51765. this.setupMainPlaylistLoaderListeners_(); // setup segment loaders
  51766. // combined audio/video or just video when alternate audio track is selected
  51767. this.mainSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  51768. segmentMetadataTrack: this.segmentMetadataTrack_,
  51769. loaderType: 'main'
  51770. }), options); // alternate audio track
  51771. this.audioSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  51772. loaderType: 'audio'
  51773. }), options);
  51774. this.subtitleSegmentLoader_ = new VTTSegmentLoader(merge(segmentLoaderSettings, {
  51775. loaderType: 'vtt',
  51776. featuresNativeTextTracks: this.tech_.featuresNativeTextTracks,
  51777. loadVttJs: () => new Promise((resolve, reject) => {
  51778. function onLoad() {
  51779. tech.off('vttjserror', onError);
  51780. resolve();
  51781. }
  51782. function onError() {
  51783. tech.off('vttjsloaded', onLoad);
  51784. reject();
  51785. }
  51786. tech.one('vttjsloaded', onLoad);
  51787. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  51788. tech.addWebVttScript_();
  51789. })
  51790. }), options);
  51791. this.setupSegmentLoaderListeners_();
  51792. if (this.bufferBasedABR) {
  51793. this.mainPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());
  51794. this.tech_.on('pause', () => this.stopABRTimer_());
  51795. this.tech_.on('play', () => this.startABRTimer_());
  51796. } // Create SegmentLoader stat-getters
  51797. // mediaRequests_
  51798. // mediaRequestsAborted_
  51799. // mediaRequestsTimedout_
  51800. // mediaRequestsErrored_
  51801. // mediaTransferDuration_
  51802. // mediaBytesTransferred_
  51803. // mediaAppends_
  51804. loaderStats.forEach(stat => {
  51805. this[stat + '_'] = sumLoaderStat.bind(this, stat);
  51806. });
  51807. this.logger_ = logger('pc');
  51808. this.triggeredFmp4Usage = false;
  51809. if (this.tech_.preload() === 'none') {
  51810. this.loadOnPlay_ = () => {
  51811. this.loadOnPlay_ = null;
  51812. this.mainPlaylistLoader_.load();
  51813. };
  51814. this.tech_.one('play', this.loadOnPlay_);
  51815. } else {
  51816. this.mainPlaylistLoader_.load();
  51817. }
  51818. this.timeToLoadedData__ = -1;
  51819. this.mainAppendsToLoadedData__ = -1;
  51820. this.audioAppendsToLoadedData__ = -1;
  51821. const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  51822. this.tech_.one(event, () => {
  51823. const timeToLoadedDataStart = Date.now();
  51824. this.tech_.one('loadeddata', () => {
  51825. this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  51826. this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;
  51827. this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;
  51828. });
  51829. });
  51830. }
  51831. mainAppendsToLoadedData_() {
  51832. return this.mainAppendsToLoadedData__;
  51833. }
  51834. audioAppendsToLoadedData_() {
  51835. return this.audioAppendsToLoadedData__;
  51836. }
  51837. appendsToLoadedData_() {
  51838. const main = this.mainAppendsToLoadedData_();
  51839. const audio = this.audioAppendsToLoadedData_();
  51840. if (main === -1 || audio === -1) {
  51841. return -1;
  51842. }
  51843. return main + audio;
  51844. }
  51845. timeToLoadedData_() {
  51846. return this.timeToLoadedData__;
  51847. }
  51848. /**
  51849. * Run selectPlaylist and switch to the new playlist if we should
  51850. *
  51851. * @param {string} [reason=abr] a reason for why the ABR check is made
  51852. * @private
  51853. */
  51854. checkABR_(reason = 'abr') {
  51855. const nextPlaylist = this.selectPlaylist();
  51856. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  51857. this.switchMedia_(nextPlaylist, reason);
  51858. }
  51859. }
  51860. switchMedia_(playlist, cause, delay) {
  51861. const oldMedia = this.media();
  51862. const oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  51863. const 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.mainPlaylistLoader_.media(playlist, delay);
  51872. }
  51873. /**
  51874. * Start a timer that periodically calls checkABR_
  51875. *
  51876. * @private
  51877. */
  51878. startABRTimer_() {
  51879. this.stopABRTimer_();
  51880. this.abrTimer_ = window.setInterval(() => this.checkABR_(), 250);
  51881. }
  51882. /**
  51883. * Stop the timer that periodically calls checkABR_
  51884. *
  51885. * @private
  51886. */
  51887. stopABRTimer_() {
  51888. // if we're scrubbing, we don't need to pause.
  51889. // This getter will be added to Video.js in version 7.11.
  51890. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  51891. return;
  51892. }
  51893. window.clearInterval(this.abrTimer_);
  51894. this.abrTimer_ = null;
  51895. }
  51896. /**
  51897. * Get a list of playlists for the currently selected audio playlist
  51898. *
  51899. * @return {Array} the array of audio playlists
  51900. */
  51901. getAudioTrackPlaylists_() {
  51902. const main = this.main();
  51903. const defaultPlaylists = main && main.playlists || []; // if we don't have any audio groups then we can only
  51904. // assume that the audio tracks are contained in main
  51905. // playlist array, use that or an empty array.
  51906. if (!main || !main.mediaGroups || !main.mediaGroups.AUDIO) {
  51907. return defaultPlaylists;
  51908. }
  51909. const AUDIO = main.mediaGroups.AUDIO;
  51910. const groupKeys = Object.keys(AUDIO);
  51911. let track; // get the current active track
  51912. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  51913. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from main if mediaTypes_ isn't setup yet
  51914. } else {
  51915. // default group is `main` or just the first group.
  51916. const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  51917. for (const label in defaultGroup) {
  51918. if (defaultGroup[label].default) {
  51919. track = {
  51920. label
  51921. };
  51922. break;
  51923. }
  51924. }
  51925. } // no active track no playlists.
  51926. if (!track) {
  51927. return defaultPlaylists;
  51928. }
  51929. const playlists = []; // get all of the playlists that are possible for the
  51930. // active track.
  51931. for (const group in AUDIO) {
  51932. if (AUDIO[group][track.label]) {
  51933. const properties = AUDIO[group][track.label];
  51934. if (properties.playlists && properties.playlists.length) {
  51935. playlists.push.apply(playlists, properties.playlists);
  51936. } else if (properties.uri) {
  51937. playlists.push(properties);
  51938. } else if (main.playlists.length) {
  51939. // if an audio group does not have a uri
  51940. // see if we have main playlists that use it as a group.
  51941. // if we do then add those to the playlists list.
  51942. for (let i = 0; i < main.playlists.length; i++) {
  51943. const playlist = main.playlists[i];
  51944. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  51945. playlists.push(playlist);
  51946. }
  51947. }
  51948. }
  51949. }
  51950. }
  51951. if (!playlists.length) {
  51952. return defaultPlaylists;
  51953. }
  51954. return playlists;
  51955. }
  51956. /**
  51957. * Register event handlers on the main playlist loader. A helper
  51958. * function for construction time.
  51959. *
  51960. * @private
  51961. */
  51962. setupMainPlaylistLoaderListeners_() {
  51963. this.mainPlaylistLoader_.on('loadedmetadata', () => {
  51964. const media = this.mainPlaylistLoader_.media();
  51965. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  51966. // timeout the request.
  51967. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  51968. this.requestOptions_.timeout = 0;
  51969. } else {
  51970. this.requestOptions_.timeout = requestTimeout;
  51971. } // if this isn't a live video and preload permits, start
  51972. // downloading segments
  51973. if (media.endList && this.tech_.preload() !== 'none') {
  51974. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  51975. this.mainSegmentLoader_.load();
  51976. }
  51977. setupMediaGroups({
  51978. sourceType: this.sourceType_,
  51979. segmentLoaders: {
  51980. AUDIO: this.audioSegmentLoader_,
  51981. SUBTITLES: this.subtitleSegmentLoader_,
  51982. main: this.mainSegmentLoader_
  51983. },
  51984. tech: this.tech_,
  51985. requestOptions: this.requestOptions_,
  51986. mainPlaylistLoader: this.mainPlaylistLoader_,
  51987. vhs: this.vhs_,
  51988. main: this.main(),
  51989. mediaTypes: this.mediaTypes_,
  51990. excludePlaylist: this.excludePlaylist.bind(this)
  51991. });
  51992. this.triggerPresenceUsage_(this.main(), media);
  51993. this.setupFirstPlay();
  51994. if (!this.mediaTypes_.AUDIO.activePlaylistLoader || this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  51995. this.trigger('selectedinitialmedia');
  51996. } else {
  51997. // We must wait for the active audio playlist loader to
  51998. // finish setting up before triggering this event so the
  51999. // representations API and EME setup is correct
  52000. this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {
  52001. this.trigger('selectedinitialmedia');
  52002. });
  52003. }
  52004. });
  52005. this.mainPlaylistLoader_.on('loadedplaylist', () => {
  52006. if (this.loadOnPlay_) {
  52007. this.tech_.off('play', this.loadOnPlay_);
  52008. }
  52009. let updatedPlaylist = this.mainPlaylistLoader_.media();
  52010. if (!updatedPlaylist) {
  52011. // exclude any variants that are not supported by the browser before selecting
  52012. // an initial media as the playlist selectors do not consider browser support
  52013. this.excludeUnsupportedVariants_();
  52014. let selectedMedia;
  52015. if (this.enableLowInitialPlaylist) {
  52016. selectedMedia = this.selectInitialPlaylist();
  52017. }
  52018. if (!selectedMedia) {
  52019. selectedMedia = this.selectPlaylist();
  52020. }
  52021. if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {
  52022. return;
  52023. }
  52024. this.initialMedia_ = selectedMedia;
  52025. this.switchMedia_(this.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  52026. // fire again since the playlist will be requested. In the case of vhs-json
  52027. // (where the manifest object is provided as the source), when the media
  52028. // playlist's `segments` list is already available, a media playlist won't be
  52029. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  52030. // called on its own here.
  52031. const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;
  52032. if (!haveJsonSource) {
  52033. return;
  52034. }
  52035. updatedPlaylist = this.initialMedia_;
  52036. }
  52037. this.handleUpdatedMediaPlaylist(updatedPlaylist);
  52038. });
  52039. this.mainPlaylistLoader_.on('error', () => {
  52040. const error = this.mainPlaylistLoader_.error;
  52041. this.excludePlaylist({
  52042. playlistToExclude: error.playlist,
  52043. error
  52044. });
  52045. });
  52046. this.mainPlaylistLoader_.on('mediachanging', () => {
  52047. this.mainSegmentLoader_.abort();
  52048. this.mainSegmentLoader_.pause();
  52049. });
  52050. this.mainPlaylistLoader_.on('mediachange', () => {
  52051. const media = this.mainPlaylistLoader_.media();
  52052. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  52053. // timeout the request.
  52054. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  52055. this.requestOptions_.timeout = 0;
  52056. } else {
  52057. this.requestOptions_.timeout = requestTimeout;
  52058. }
  52059. this.mainPlaylistLoader_.load(); // TODO: Create a new event on the PlaylistLoader that signals
  52060. // that the segments have changed in some way and use that to
  52061. // update the SegmentLoader instead of doing it twice here and
  52062. // on `loadedplaylist`
  52063. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  52064. this.mainSegmentLoader_.load();
  52065. this.tech_.trigger({
  52066. type: 'mediachange',
  52067. bubbles: true
  52068. });
  52069. });
  52070. this.mainPlaylistLoader_.on('playlistunchanged', () => {
  52071. const updatedPlaylist = this.mainPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  52072. // excluded for not-changing. We likely just have a really slowly updating
  52073. // playlist.
  52074. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  52075. return;
  52076. }
  52077. const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);
  52078. if (playlistOutdated) {
  52079. // Playlist has stopped updating and we're stuck at its end. Try to
  52080. // exclude it and switch to another playlist in the hope that that
  52081. // one is updating (and give the player a chance to re-adjust to the
  52082. // safe live point).
  52083. this.excludePlaylist({
  52084. error: {
  52085. message: 'Playlist no longer updating.',
  52086. reason: 'playlist-unchanged'
  52087. }
  52088. }); // useful for monitoring QoS
  52089. this.tech_.trigger('playliststuck');
  52090. }
  52091. });
  52092. this.mainPlaylistLoader_.on('renditiondisabled', () => {
  52093. this.tech_.trigger({
  52094. type: 'usage',
  52095. name: 'vhs-rendition-disabled'
  52096. });
  52097. });
  52098. this.mainPlaylistLoader_.on('renditionenabled', () => {
  52099. this.tech_.trigger({
  52100. type: 'usage',
  52101. name: 'vhs-rendition-enabled'
  52102. });
  52103. });
  52104. }
  52105. /**
  52106. * Given an updated media playlist (whether it was loaded for the first time, or
  52107. * refreshed for live playlists), update any relevant properties and state to reflect
  52108. * changes in the media that should be accounted for (e.g., cues and duration).
  52109. *
  52110. * @param {Object} updatedPlaylist the updated media playlist object
  52111. *
  52112. * @private
  52113. */
  52114. handleUpdatedMediaPlaylist(updatedPlaylist) {
  52115. if (this.useCueTags_) {
  52116. this.updateAdCues_(updatedPlaylist);
  52117. } // TODO: Create a new event on the PlaylistLoader that signals
  52118. // that the segments have changed in some way and use that to
  52119. // update the SegmentLoader instead of doing it twice here and
  52120. // on `mediachange`
  52121. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  52122. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  52123. // as it is possible that it was temporarily stopped while waiting for
  52124. // a playlist (e.g., in case the playlist errored and we re-requested it).
  52125. if (!this.tech_.paused()) {
  52126. this.mainSegmentLoader_.load();
  52127. if (this.audioSegmentLoader_) {
  52128. this.audioSegmentLoader_.load();
  52129. }
  52130. }
  52131. }
  52132. /**
  52133. * A helper function for triggerring presence usage events once per source
  52134. *
  52135. * @private
  52136. */
  52137. triggerPresenceUsage_(main, media) {
  52138. const mediaGroups = main.mediaGroups || {};
  52139. let defaultDemuxed = true;
  52140. const audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  52141. for (const mediaGroup in mediaGroups.AUDIO) {
  52142. for (const label in mediaGroups.AUDIO[mediaGroup]) {
  52143. const properties = mediaGroups.AUDIO[mediaGroup][label];
  52144. if (!properties.uri) {
  52145. defaultDemuxed = false;
  52146. }
  52147. }
  52148. }
  52149. if (defaultDemuxed) {
  52150. this.tech_.trigger({
  52151. type: 'usage',
  52152. name: 'vhs-demuxed'
  52153. });
  52154. }
  52155. if (Object.keys(mediaGroups.SUBTITLES).length) {
  52156. this.tech_.trigger({
  52157. type: 'usage',
  52158. name: 'vhs-webvtt'
  52159. });
  52160. }
  52161. if (Vhs$1.Playlist.isAes(media)) {
  52162. this.tech_.trigger({
  52163. type: 'usage',
  52164. name: 'vhs-aes'
  52165. });
  52166. }
  52167. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  52168. this.tech_.trigger({
  52169. type: 'usage',
  52170. name: 'vhs-alternate-audio'
  52171. });
  52172. }
  52173. if (this.useCueTags_) {
  52174. this.tech_.trigger({
  52175. type: 'usage',
  52176. name: 'vhs-playlist-cue-tags'
  52177. });
  52178. }
  52179. }
  52180. shouldSwitchToMedia_(nextPlaylist) {
  52181. const currentPlaylist = this.mainPlaylistLoader_.media() || this.mainPlaylistLoader_.pendingMedia_;
  52182. const currentTime = this.tech_.currentTime();
  52183. const bufferLowWaterLine = this.bufferLowWaterLine();
  52184. const bufferHighWaterLine = this.bufferHighWaterLine();
  52185. const buffered = this.tech_.buffered();
  52186. return shouldSwitchToMedia({
  52187. buffered,
  52188. currentTime,
  52189. currentPlaylist,
  52190. nextPlaylist,
  52191. bufferLowWaterLine,
  52192. bufferHighWaterLine,
  52193. duration: this.duration(),
  52194. bufferBasedABR: this.bufferBasedABR,
  52195. log: this.logger_
  52196. });
  52197. }
  52198. /**
  52199. * Register event handlers on the segment loaders. A helper function
  52200. * for construction time.
  52201. *
  52202. * @private
  52203. */
  52204. setupSegmentLoaderListeners_() {
  52205. this.mainSegmentLoader_.on('bandwidthupdate', () => {
  52206. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  52207. // useful to check to see if a rendition switch should be made.
  52208. this.checkABR_('bandwidthupdate');
  52209. this.tech_.trigger('bandwidthupdate');
  52210. });
  52211. this.mainSegmentLoader_.on('timeout', () => {
  52212. if (this.bufferBasedABR) {
  52213. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  52214. // Here the only consideration is that for buffer based ABR there's no guarantee
  52215. // of an immediate switch (since the bandwidth is averaged with a timeout
  52216. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  52217. this.mainSegmentLoader_.load();
  52218. }
  52219. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  52220. // based ABR.
  52221. if (!this.bufferBasedABR) {
  52222. this.mainSegmentLoader_.on('progress', () => {
  52223. this.trigger('progress');
  52224. });
  52225. }
  52226. this.mainSegmentLoader_.on('error', () => {
  52227. const error = this.mainSegmentLoader_.error();
  52228. this.excludePlaylist({
  52229. playlistToExclude: error.playlist,
  52230. error
  52231. });
  52232. });
  52233. this.mainSegmentLoader_.on('appenderror', () => {
  52234. this.error = this.mainSegmentLoader_.error_;
  52235. this.trigger('error');
  52236. });
  52237. this.mainSegmentLoader_.on('syncinfoupdate', () => {
  52238. this.onSyncInfoUpdate_();
  52239. });
  52240. this.mainSegmentLoader_.on('timestampoffset', () => {
  52241. this.tech_.trigger({
  52242. type: 'usage',
  52243. name: 'vhs-timestamp-offset'
  52244. });
  52245. });
  52246. this.audioSegmentLoader_.on('syncinfoupdate', () => {
  52247. this.onSyncInfoUpdate_();
  52248. });
  52249. this.audioSegmentLoader_.on('appenderror', () => {
  52250. this.error = this.audioSegmentLoader_.error_;
  52251. this.trigger('error');
  52252. });
  52253. this.mainSegmentLoader_.on('ended', () => {
  52254. this.logger_('main segment loader ended');
  52255. this.onEndOfStream();
  52256. });
  52257. this.mainSegmentLoader_.on('earlyabort', event => {
  52258. // never try to early abort with the new ABR algorithm
  52259. if (this.bufferBasedABR) {
  52260. return;
  52261. }
  52262. this.delegateLoaders_('all', ['abort']);
  52263. this.excludePlaylist({
  52264. error: {
  52265. message: 'Aborted early because there isn\'t enough bandwidth to complete ' + 'the request without rebuffering.'
  52266. },
  52267. playlistExclusionDuration: ABORT_EARLY_EXCLUSION_SECONDS
  52268. });
  52269. });
  52270. const updateCodecs = () => {
  52271. if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {
  52272. return this.tryToCreateSourceBuffers_();
  52273. }
  52274. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  52275. if (!codecs) {
  52276. return;
  52277. }
  52278. this.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  52279. };
  52280. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  52281. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  52282. this.mainSegmentLoader_.on('fmp4', () => {
  52283. if (!this.triggeredFmp4Usage) {
  52284. this.tech_.trigger({
  52285. type: 'usage',
  52286. name: 'vhs-fmp4'
  52287. });
  52288. this.triggeredFmp4Usage = true;
  52289. }
  52290. });
  52291. this.audioSegmentLoader_.on('fmp4', () => {
  52292. if (!this.triggeredFmp4Usage) {
  52293. this.tech_.trigger({
  52294. type: 'usage',
  52295. name: 'vhs-fmp4'
  52296. });
  52297. this.triggeredFmp4Usage = true;
  52298. }
  52299. });
  52300. this.audioSegmentLoader_.on('ended', () => {
  52301. this.logger_('audioSegmentLoader ended');
  52302. this.onEndOfStream();
  52303. });
  52304. }
  52305. mediaSecondsLoaded_() {
  52306. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  52307. }
  52308. /**
  52309. * Call load on our SegmentLoaders
  52310. */
  52311. load() {
  52312. this.mainSegmentLoader_.load();
  52313. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  52314. this.audioSegmentLoader_.load();
  52315. }
  52316. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  52317. this.subtitleSegmentLoader_.load();
  52318. }
  52319. }
  52320. /**
  52321. * Re-tune playback quality level for the current player
  52322. * conditions. This method will perform destructive actions like removing
  52323. * already buffered content in order to readjust the currently active
  52324. * playlist quickly. This is good for manual quality changes
  52325. *
  52326. * @private
  52327. */
  52328. fastQualityChange_(media = this.selectPlaylist()) {
  52329. if (media === this.mainPlaylistLoader_.media()) {
  52330. this.logger_('skipping fastQualityChange because new media is same as old');
  52331. return;
  52332. }
  52333. this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
  52334. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  52335. // ahead is roughly the minimum that will accomplish this across a variety of content
  52336. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  52337. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  52338. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  52339. this.mainSegmentLoader_.resetEverything(() => {
  52340. // Since this is not a typical seek, we avoid the seekTo method which can cause segments
  52341. // from the previously enabled rendition to load before the new playlist has finished loading
  52342. if (videojs.browser.IE_VERSION || videojs.browser.IS_EDGE) {
  52343. this.tech_.setCurrentTime(this.tech_.currentTime() + 0.04);
  52344. } else {
  52345. this.tech_.setCurrentTime(this.tech_.currentTime());
  52346. }
  52347. }); // don't need to reset audio as it is reset when media changes
  52348. }
  52349. /**
  52350. * Begin playback.
  52351. */
  52352. play() {
  52353. if (this.setupFirstPlay()) {
  52354. return;
  52355. }
  52356. if (this.tech_.ended()) {
  52357. this.tech_.setCurrentTime(0);
  52358. }
  52359. if (this.hasPlayed_) {
  52360. this.load();
  52361. }
  52362. const seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  52363. // seek forward to the live point
  52364. if (this.tech_.duration() === Infinity) {
  52365. if (this.tech_.currentTime() < seekable.start(0)) {
  52366. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  52367. }
  52368. }
  52369. }
  52370. /**
  52371. * Seek to the latest media position if this is a live video and the
  52372. * player and video are loaded and initialized.
  52373. */
  52374. setupFirstPlay() {
  52375. const media = this.mainPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  52376. // If 1) there is no active media
  52377. // 2) the player is paused
  52378. // 3) the first play has already been setup
  52379. // then exit early
  52380. if (!media || this.tech_.paused() || this.hasPlayed_) {
  52381. return false;
  52382. } // when the video is a live stream
  52383. if (!media.endList) {
  52384. const seekable = this.seekable();
  52385. if (!seekable.length) {
  52386. // without a seekable range, the player cannot seek to begin buffering at the live
  52387. // point
  52388. return false;
  52389. }
  52390. if (videojs.browser.IE_VERSION && this.tech_.readyState() === 0) {
  52391. // IE11 throws an InvalidStateError if you try to set currentTime while the
  52392. // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
  52393. this.tech_.one('loadedmetadata', () => {
  52394. this.trigger('firstplay');
  52395. this.tech_.setCurrentTime(seekable.end(0));
  52396. this.hasPlayed_ = true;
  52397. });
  52398. return false;
  52399. } // trigger firstplay to inform the source handler to ignore the next seek event
  52400. this.trigger('firstplay'); // seek to the live point
  52401. this.tech_.setCurrentTime(seekable.end(0));
  52402. }
  52403. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  52404. this.load();
  52405. return true;
  52406. }
  52407. /**
  52408. * handle the sourceopen event on the MediaSource
  52409. *
  52410. * @private
  52411. */
  52412. handleSourceOpen_() {
  52413. // Only attempt to create the source buffer if none already exist.
  52414. // handleSourceOpen is also called when we are "re-opening" a source buffer
  52415. // after `endOfStream` has been called (in response to a seek for instance)
  52416. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  52417. // code in video.js but is required because play() must be invoked
  52418. // *after* the media source has opened.
  52419. if (this.tech_.autoplay()) {
  52420. const playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  52421. // on browsers which return a promise
  52422. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  52423. playPromise.then(null, e => {});
  52424. }
  52425. }
  52426. this.trigger('sourceopen');
  52427. }
  52428. /**
  52429. * handle the sourceended event on the MediaSource
  52430. *
  52431. * @private
  52432. */
  52433. handleSourceEnded_() {
  52434. if (!this.inbandTextTracks_.metadataTrack_) {
  52435. return;
  52436. }
  52437. const cues = this.inbandTextTracks_.metadataTrack_.cues;
  52438. if (!cues || !cues.length) {
  52439. return;
  52440. }
  52441. const duration = this.duration();
  52442. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  52443. }
  52444. /**
  52445. * handle the durationchange event on the MediaSource
  52446. *
  52447. * @private
  52448. */
  52449. handleDurationChange_() {
  52450. this.tech_.trigger('durationchange');
  52451. }
  52452. /**
  52453. * Calls endOfStream on the media source when all active stream types have called
  52454. * endOfStream
  52455. *
  52456. * @param {string} streamType
  52457. * Stream type of the segment loader that called endOfStream
  52458. * @private
  52459. */
  52460. onEndOfStream() {
  52461. let isEndOfStream = this.mainSegmentLoader_.ended_;
  52462. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  52463. const mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  52464. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  52465. // if we do not know if the main segment loader contains video yet or if we
  52466. // definitively know the main segment loader contains video, then we need to wait
  52467. // for both main and audio segment loaders to call endOfStream
  52468. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  52469. } else {
  52470. // otherwise just rely on the audio loader
  52471. isEndOfStream = this.audioSegmentLoader_.ended_;
  52472. }
  52473. }
  52474. if (!isEndOfStream) {
  52475. return;
  52476. }
  52477. this.stopABRTimer_();
  52478. this.sourceUpdater_.endOfStream();
  52479. }
  52480. /**
  52481. * Check if a playlist has stopped being updated
  52482. *
  52483. * @param {Object} playlist the media playlist object
  52484. * @return {boolean} whether the playlist has stopped being updated or not
  52485. */
  52486. stuckAtPlaylistEnd_(playlist) {
  52487. const seekable = this.seekable();
  52488. if (!seekable.length) {
  52489. // playlist doesn't have enough information to determine whether we are stuck
  52490. return false;
  52491. }
  52492. const expired = this.syncController_.getExpiredTime(playlist, this.duration());
  52493. if (expired === null) {
  52494. return false;
  52495. } // does not use the safe live end to calculate playlist end, since we
  52496. // don't want to say we are stuck while there is still content
  52497. const absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  52498. const currentTime = this.tech_.currentTime();
  52499. const buffered = this.tech_.buffered();
  52500. if (!buffered.length) {
  52501. // return true if the playhead reached the absolute end of the playlist
  52502. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  52503. }
  52504. const bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  52505. // end of playlist
  52506. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  52507. }
  52508. /**
  52509. * Exclude a playlist for a set amount of time, making it unavailable for selection by
  52510. * the rendition selection algorithm, then force a new playlist (rendition) selection.
  52511. *
  52512. * @param {Object=} playlistToExclude
  52513. * the playlist to exclude, defaults to the currently selected playlist
  52514. * @param {Object=} error
  52515. * an optional error
  52516. * @param {number=} playlistExclusionDuration
  52517. * an optional number of seconds to exclude the playlist
  52518. */
  52519. excludePlaylist({
  52520. playlistToExclude = this.mainPlaylistLoader_.media(),
  52521. error = {},
  52522. playlistExclusionDuration
  52523. }) {
  52524. // If the `error` was generated by the playlist loader, it will contain
  52525. // the playlist we were trying to load (but failed) and that should be
  52526. // excluded instead of the currently selected playlist which is likely
  52527. // out-of-date in this scenario
  52528. playlistToExclude = playlistToExclude || this.mainPlaylistLoader_.media();
  52529. playlistExclusionDuration = playlistExclusionDuration || error.playlistExclusionDuration || this.playlistExclusionDuration; // If there is no current playlist, then an error occurred while we were
  52530. // trying to load the main OR while we were disposing of the tech
  52531. if (!playlistToExclude) {
  52532. this.error = error;
  52533. if (this.mediaSource.readyState !== 'open') {
  52534. this.trigger('error');
  52535. } else {
  52536. this.sourceUpdater_.endOfStream('network');
  52537. }
  52538. return;
  52539. }
  52540. playlistToExclude.playlistErrors_++;
  52541. const playlists = this.mainPlaylistLoader_.main.playlists;
  52542. const enabledPlaylists = playlists.filter(isEnabled);
  52543. const isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === playlistToExclude; // Don't exclude the only playlist unless it was excluded
  52544. // forever
  52545. if (playlists.length === 1 && playlistExclusionDuration !== Infinity) {
  52546. videojs.log.warn(`Problem encountered with playlist ${playlistToExclude.id}. ` + 'Trying again since it is the only playlist.');
  52547. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  52548. return this.mainPlaylistLoader_.load(isFinalRendition);
  52549. }
  52550. if (isFinalRendition) {
  52551. // Since we're on the final non-excluded playlist, and we're about to exclude
  52552. // it, instead of erring the player or retrying this playlist, clear out the current
  52553. // exclusion list. This allows other playlists to be attempted in case any have been
  52554. // fixed.
  52555. let reincluded = false;
  52556. playlists.forEach(playlist => {
  52557. // skip current playlist which is about to be excluded
  52558. if (playlist === playlistToExclude) {
  52559. return;
  52560. }
  52561. const excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  52562. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  52563. reincluded = true;
  52564. delete playlist.excludeUntil;
  52565. }
  52566. });
  52567. if (reincluded) {
  52568. 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
  52569. // playlist. This is needed for users relying on the retryplaylist event to catch a
  52570. // case where the player might be stuck and looping through "dead" playlists.
  52571. this.tech_.trigger('retryplaylist');
  52572. }
  52573. } // Exclude this playlist
  52574. let excludeUntil;
  52575. if (playlistToExclude.playlistErrors_ > this.maxPlaylistRetries) {
  52576. excludeUntil = Infinity;
  52577. } else {
  52578. excludeUntil = Date.now() + playlistExclusionDuration * 1000;
  52579. }
  52580. playlistToExclude.excludeUntil = excludeUntil;
  52581. if (error.reason) {
  52582. playlistToExclude.lastExcludeReason_ = error.reason;
  52583. }
  52584. this.tech_.trigger('excludeplaylist');
  52585. this.tech_.trigger({
  52586. type: 'usage',
  52587. name: 'vhs-rendition-excluded'
  52588. }); // TODO: only load a new playlist if we're excluding the current playlist
  52589. // If this function was called with a playlist that's not the current active playlist
  52590. // (e.g., media().id !== playlistToExclude.id),
  52591. // then a new playlist should not be selected and loaded, as there's nothing wrong with the current playlist.
  52592. const nextPlaylist = this.selectPlaylist();
  52593. if (!nextPlaylist) {
  52594. this.error = 'Playback cannot continue. No available working or supported playlists.';
  52595. this.trigger('error');
  52596. return;
  52597. }
  52598. const logFn = error.internal ? this.logger_ : videojs.log.warn;
  52599. const errorMessage = error.message ? ' ' + error.message : '';
  52600. logFn(`${error.internal ? 'Internal problem' : 'Problem'} encountered with playlist ${playlistToExclude.id}.` + `${errorMessage} Switching to playlist ${nextPlaylist.id}.`); // if audio group changed reset audio loaders
  52601. if (nextPlaylist.attributes.AUDIO !== playlistToExclude.attributes.AUDIO) {
  52602. this.delegateLoaders_('audio', ['abort', 'pause']);
  52603. } // if subtitle group changed reset subtitle loaders
  52604. if (nextPlaylist.attributes.SUBTITLES !== playlistToExclude.attributes.SUBTITLES) {
  52605. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  52606. }
  52607. this.delegateLoaders_('main', ['abort', 'pause']);
  52608. const delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  52609. const 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
  52610. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  52611. }
  52612. /**
  52613. * Pause all segment/playlist loaders
  52614. */
  52615. pauseLoading() {
  52616. this.delegateLoaders_('all', ['abort', 'pause']);
  52617. this.stopABRTimer_();
  52618. }
  52619. /**
  52620. * Call a set of functions in order on playlist loaders, segment loaders,
  52621. * or both types of loaders.
  52622. *
  52623. * @param {string} filter
  52624. * Filter loaders that should call fnNames using a string. Can be:
  52625. * * all - run on all loaders
  52626. * * audio - run on all audio loaders
  52627. * * subtitle - run on all subtitle loaders
  52628. * * main - run on the main loaders
  52629. *
  52630. * @param {Array|string} fnNames
  52631. * A string or array of function names to call.
  52632. */
  52633. delegateLoaders_(filter, fnNames) {
  52634. const loaders = [];
  52635. const dontFilterPlaylist = filter === 'all';
  52636. if (dontFilterPlaylist || filter === 'main') {
  52637. loaders.push(this.mainPlaylistLoader_);
  52638. }
  52639. const mediaTypes = [];
  52640. if (dontFilterPlaylist || filter === 'audio') {
  52641. mediaTypes.push('AUDIO');
  52642. }
  52643. if (dontFilterPlaylist || filter === 'subtitle') {
  52644. mediaTypes.push('CLOSED-CAPTIONS');
  52645. mediaTypes.push('SUBTITLES');
  52646. }
  52647. mediaTypes.forEach(mediaType => {
  52648. const loader = this.mediaTypes_[mediaType] && this.mediaTypes_[mediaType].activePlaylistLoader;
  52649. if (loader) {
  52650. loaders.push(loader);
  52651. }
  52652. });
  52653. ['main', 'audio', 'subtitle'].forEach(name => {
  52654. const loader = this[`${name}SegmentLoader_`];
  52655. if (loader && (filter === name || filter === 'all')) {
  52656. loaders.push(loader);
  52657. }
  52658. });
  52659. loaders.forEach(loader => fnNames.forEach(fnName => {
  52660. if (typeof loader[fnName] === 'function') {
  52661. loader[fnName]();
  52662. }
  52663. }));
  52664. }
  52665. /**
  52666. * set the current time on all segment loaders
  52667. *
  52668. * @param {TimeRange} currentTime the current time to set
  52669. * @return {TimeRange} the current time
  52670. */
  52671. setCurrentTime(currentTime) {
  52672. const buffered = findRange(this.tech_.buffered(), currentTime);
  52673. if (!(this.mainPlaylistLoader_ && this.mainPlaylistLoader_.media())) {
  52674. // return immediately if the metadata is not ready yet
  52675. return 0;
  52676. } // it's clearly an edge-case but don't thrown an error if asked to
  52677. // seek within an empty playlist
  52678. if (!this.mainPlaylistLoader_.media().segments) {
  52679. return 0;
  52680. } // if the seek location is already buffered, continue buffering as usual
  52681. if (buffered && buffered.length) {
  52682. return currentTime;
  52683. } // cancel outstanding requests so we begin buffering at the new
  52684. // location
  52685. this.mainSegmentLoader_.resetEverything();
  52686. this.mainSegmentLoader_.abort();
  52687. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  52688. this.audioSegmentLoader_.resetEverything();
  52689. this.audioSegmentLoader_.abort();
  52690. }
  52691. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  52692. this.subtitleSegmentLoader_.resetEverything();
  52693. this.subtitleSegmentLoader_.abort();
  52694. } // start segment loader loading in case they are paused
  52695. this.load();
  52696. }
  52697. /**
  52698. * get the current duration
  52699. *
  52700. * @return {TimeRange} the duration
  52701. */
  52702. duration() {
  52703. if (!this.mainPlaylistLoader_) {
  52704. return 0;
  52705. }
  52706. const media = this.mainPlaylistLoader_.media();
  52707. if (!media) {
  52708. // no playlists loaded yet, so can't determine a duration
  52709. return 0;
  52710. } // Don't rely on the media source for duration in the case of a live playlist since
  52711. // setting the native MediaSource's duration to infinity ends up with consequences to
  52712. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  52713. //
  52714. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  52715. // however, few browsers have support for setLiveSeekableRange()
  52716. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  52717. //
  52718. // Until a time when the duration of the media source can be set to infinity, and a
  52719. // seekable range specified across browsers, just return Infinity.
  52720. if (!media.endList) {
  52721. return Infinity;
  52722. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  52723. // available). If it's not available, fall back to a playlist-calculated estimate.
  52724. if (this.mediaSource) {
  52725. return this.mediaSource.duration;
  52726. }
  52727. return Vhs$1.Playlist.duration(media);
  52728. }
  52729. /**
  52730. * check the seekable range
  52731. *
  52732. * @return {TimeRange} the seekable range
  52733. */
  52734. seekable() {
  52735. return this.seekable_;
  52736. }
  52737. onSyncInfoUpdate_() {
  52738. let audioSeekable; // TODO check for creation of both source buffers before updating seekable
  52739. //
  52740. // A fix was made to this function where a check for
  52741. // this.sourceUpdater_.hasCreatedSourceBuffers
  52742. // was added to ensure that both source buffers were created before seekable was
  52743. // updated. However, it originally had a bug where it was checking for a true and
  52744. // returning early instead of checking for false. Setting it to check for false to
  52745. // return early though created other issues. A call to play() would check for seekable
  52746. // end without verifying that a seekable range was present. In addition, even checking
  52747. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  52748. // due to a media update calling load on the segment loaders, skipping a seek to live,
  52749. // thereby starting live streams at the beginning of the stream rather than at the end.
  52750. //
  52751. // This conditional should be fixed to wait for the creation of two source buffers at
  52752. // the same time as the other sections of code are fixed to properly seek to live and
  52753. // not throw an error due to checking for a seekable end when no seekable range exists.
  52754. //
  52755. // For now, fall back to the older behavior, with the understanding that the seekable
  52756. // range may not be completely correct, leading to a suboptimal initial live point.
  52757. if (!this.mainPlaylistLoader_) {
  52758. return;
  52759. }
  52760. let media = this.mainPlaylistLoader_.media();
  52761. if (!media) {
  52762. return;
  52763. }
  52764. let expired = this.syncController_.getExpiredTime(media, this.duration());
  52765. if (expired === null) {
  52766. // not enough information to update seekable
  52767. return;
  52768. }
  52769. const main = this.mainPlaylistLoader_.main;
  52770. const mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  52771. if (mainSeekable.length === 0) {
  52772. return;
  52773. }
  52774. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  52775. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  52776. expired = this.syncController_.getExpiredTime(media, this.duration());
  52777. if (expired === null) {
  52778. return;
  52779. }
  52780. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  52781. if (audioSeekable.length === 0) {
  52782. return;
  52783. }
  52784. }
  52785. let oldEnd;
  52786. let oldStart;
  52787. if (this.seekable_ && this.seekable_.length) {
  52788. oldEnd = this.seekable_.end(0);
  52789. oldStart = this.seekable_.start(0);
  52790. }
  52791. if (!audioSeekable) {
  52792. // seekable has been calculated based on buffering video data so it
  52793. // can be returned directly
  52794. this.seekable_ = mainSeekable;
  52795. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  52796. // seekables are pretty far off, rely on main
  52797. this.seekable_ = mainSeekable;
  52798. } else {
  52799. this.seekable_ = 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)]]);
  52800. } // seekable is the same as last time
  52801. if (this.seekable_ && this.seekable_.length) {
  52802. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  52803. return;
  52804. }
  52805. }
  52806. this.logger_(`seekable updated [${printableRange(this.seekable_)}]`);
  52807. this.tech_.trigger('seekablechanged');
  52808. }
  52809. /**
  52810. * Update the player duration
  52811. */
  52812. updateDuration(isLive) {
  52813. if (this.updateDuration_) {
  52814. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  52815. this.updateDuration_ = null;
  52816. }
  52817. if (this.mediaSource.readyState !== 'open') {
  52818. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  52819. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  52820. return;
  52821. }
  52822. if (isLive) {
  52823. const seekable = this.seekable();
  52824. if (!seekable.length) {
  52825. return;
  52826. } // Even in the case of a live playlist, the native MediaSource's duration should not
  52827. // be set to Infinity (even though this would be expected for a live playlist), since
  52828. // setting the native MediaSource's duration to infinity ends up with consequences to
  52829. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  52830. //
  52831. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  52832. // however, few browsers have support for setLiveSeekableRange()
  52833. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  52834. //
  52835. // Until a time when the duration of the media source can be set to infinity, and a
  52836. // seekable range specified across browsers, the duration should be greater than or
  52837. // equal to the last possible seekable value.
  52838. // MediaSource duration starts as NaN
  52839. // It is possible (and probable) that this case will never be reached for many
  52840. // sources, since the MediaSource reports duration as the highest value without
  52841. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  52842. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  52843. // time will be between 0 and 100, the native media source may report the duration
  52844. // as 200. However, since we report duration separate from the media source (as
  52845. // Infinity), and as long as the native media source duration value is greater than
  52846. // our reported seekable range, seeks will work as expected. The large number as
  52847. // duration for live is actually a strategy used by some players to work around the
  52848. // issue of live seekable ranges cited above.
  52849. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  52850. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  52851. }
  52852. return;
  52853. }
  52854. const buffered = this.tech_.buffered();
  52855. let duration = Vhs$1.Playlist.duration(this.mainPlaylistLoader_.media());
  52856. if (buffered.length > 0) {
  52857. duration = Math.max(duration, buffered.end(buffered.length - 1));
  52858. }
  52859. if (this.mediaSource.duration !== duration) {
  52860. this.sourceUpdater_.setDuration(duration);
  52861. }
  52862. }
  52863. /**
  52864. * dispose of the PlaylistController and everything
  52865. * that it controls
  52866. */
  52867. dispose() {
  52868. this.trigger('dispose');
  52869. this.decrypter_.terminate();
  52870. this.mainPlaylistLoader_.dispose();
  52871. this.mainSegmentLoader_.dispose();
  52872. if (this.loadOnPlay_) {
  52873. this.tech_.off('play', this.loadOnPlay_);
  52874. }
  52875. ['AUDIO', 'SUBTITLES'].forEach(type => {
  52876. const groups = this.mediaTypes_[type].groups;
  52877. for (const id in groups) {
  52878. groups[id].forEach(group => {
  52879. if (group.playlistLoader) {
  52880. group.playlistLoader.dispose();
  52881. }
  52882. });
  52883. }
  52884. });
  52885. this.audioSegmentLoader_.dispose();
  52886. this.subtitleSegmentLoader_.dispose();
  52887. this.sourceUpdater_.dispose();
  52888. this.timelineChangeController_.dispose();
  52889. this.stopABRTimer_();
  52890. if (this.updateDuration_) {
  52891. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  52892. }
  52893. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  52894. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  52895. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  52896. this.off();
  52897. }
  52898. /**
  52899. * return the main playlist object if we have one
  52900. *
  52901. * @return {Object} the main playlist object that we parsed
  52902. */
  52903. main() {
  52904. return this.mainPlaylistLoader_.main;
  52905. }
  52906. /**
  52907. * return the currently selected playlist
  52908. *
  52909. * @return {Object} the currently selected playlist object that we parsed
  52910. */
  52911. media() {
  52912. // playlist loader will not return media if it has not been fully loaded
  52913. return this.mainPlaylistLoader_.media() || this.initialMedia_;
  52914. }
  52915. areMediaTypesKnown_() {
  52916. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  52917. const hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  52918. // otherwise check on the segment loader.
  52919. const hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  52920. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  52921. return false;
  52922. }
  52923. return true;
  52924. }
  52925. getCodecsOrExclude_() {
  52926. const media = {
  52927. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  52928. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  52929. };
  52930. const playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  52931. media.video = media.main;
  52932. const playlistCodecs = codecsForPlaylist(this.main(), playlist);
  52933. const codecs = {};
  52934. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  52935. if (media.main.hasVideo) {
  52936. codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
  52937. }
  52938. if (media.main.isMuxed) {
  52939. codecs.video += `,${playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC}`;
  52940. }
  52941. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  52942. codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
  52943. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  52944. } // no codecs, no playback.
  52945. if (!codecs.audio && !codecs.video) {
  52946. this.excludePlaylist({
  52947. playlistToExclude: playlist,
  52948. error: {
  52949. message: 'Could not determine codecs for playlist.'
  52950. },
  52951. playlistExclusionDuration: Infinity
  52952. });
  52953. return;
  52954. } // fmp4 relies on browser support, while ts relies on muxer support
  52955. const supportFunction = (isFmp4, codec) => isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
  52956. const unsupportedCodecs = {};
  52957. let unsupportedAudio;
  52958. ['video', 'audio'].forEach(function (type) {
  52959. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  52960. const supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  52961. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  52962. unsupportedCodecs[supporter].push(codecs[type]);
  52963. if (type === 'audio') {
  52964. unsupportedAudio = supporter;
  52965. }
  52966. }
  52967. });
  52968. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  52969. const audioGroup = playlist.attributes.AUDIO;
  52970. this.main().playlists.forEach(variant => {
  52971. const variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  52972. if (variantAudioGroup === audioGroup && variant !== playlist) {
  52973. variant.excludeUntil = Infinity;
  52974. }
  52975. });
  52976. this.logger_(`excluding audio group ${audioGroup} as ${unsupportedAudio} does not support codec(s): "${codecs.audio}"`);
  52977. } // if we have any unsupported codecs exclude this playlist.
  52978. if (Object.keys(unsupportedCodecs).length) {
  52979. const message = Object.keys(unsupportedCodecs).reduce((acc, supporter) => {
  52980. if (acc) {
  52981. acc += ', ';
  52982. }
  52983. acc += `${supporter} does not support codec(s): "${unsupportedCodecs[supporter].join(',')}"`;
  52984. return acc;
  52985. }, '') + '.';
  52986. this.excludePlaylist({
  52987. playlistToExclude: playlist,
  52988. error: {
  52989. internal: true,
  52990. message
  52991. },
  52992. playlistExclusionDuration: Infinity
  52993. });
  52994. return;
  52995. } // check if codec switching is happening
  52996. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  52997. const switchMessages = [];
  52998. ['video', 'audio'].forEach(type => {
  52999. const newCodec = (parseCodecs(this.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  53000. const oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
  53001. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  53002. switchMessages.push(`"${this.sourceUpdater_.codecs[type]}" -> "${codecs[type]}"`);
  53003. }
  53004. });
  53005. if (switchMessages.length) {
  53006. this.excludePlaylist({
  53007. playlistToExclude: playlist,
  53008. error: {
  53009. message: `Codec switching not supported: ${switchMessages.join(', ')}.`,
  53010. internal: true
  53011. },
  53012. playlistExclusionDuration: Infinity
  53013. });
  53014. return;
  53015. }
  53016. } // TODO: when using the muxer shouldn't we just return
  53017. // the codecs that the muxer outputs?
  53018. return codecs;
  53019. }
  53020. /**
  53021. * Create source buffers and exlude any incompatible renditions.
  53022. *
  53023. * @private
  53024. */
  53025. tryToCreateSourceBuffers_() {
  53026. // media source is not ready yet or sourceBuffers are already
  53027. // created.
  53028. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  53029. return;
  53030. }
  53031. if (!this.areMediaTypesKnown_()) {
  53032. return;
  53033. }
  53034. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  53035. if (!codecs) {
  53036. return;
  53037. }
  53038. this.sourceUpdater_.createSourceBuffers(codecs);
  53039. const codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  53040. this.excludeIncompatibleVariants_(codecString);
  53041. }
  53042. /**
  53043. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  53044. */
  53045. excludeUnsupportedVariants_() {
  53046. const playlists = this.main().playlists;
  53047. const ids = []; // TODO: why don't we have a property to loop through all
  53048. // playlist? Why did we ever mix indexes and keys?
  53049. Object.keys(playlists).forEach(key => {
  53050. const variant = playlists[key]; // check if we already processed this playlist.
  53051. if (ids.indexOf(variant.id) !== -1) {
  53052. return;
  53053. }
  53054. ids.push(variant.id);
  53055. const codecs = codecsForPlaylist(this.main, variant);
  53056. const unsupported = [];
  53057. if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
  53058. unsupported.push(`audio codec ${codecs.audio}`);
  53059. }
  53060. if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
  53061. unsupported.push(`video codec ${codecs.video}`);
  53062. }
  53063. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  53064. unsupported.push(`text codec ${codecs.text}`);
  53065. }
  53066. if (unsupported.length) {
  53067. variant.excludeUntil = Infinity;
  53068. this.logger_(`excluding ${variant.id} for unsupported: ${unsupported.join(', ')}`);
  53069. }
  53070. });
  53071. }
  53072. /**
  53073. * Exclude playlists that are known to be codec or
  53074. * stream-incompatible with the SourceBuffer configuration. For
  53075. * instance, Media Source Extensions would cause the video element to
  53076. * stall waiting for video data if you switched from a variant with
  53077. * video and audio to an audio-only one.
  53078. *
  53079. * @param {Object} media a media playlist compatible with the current
  53080. * set of SourceBuffers. Variants in the current main playlist that
  53081. * do not appear to have compatible codec or stream configurations
  53082. * will be excluded from the default playlist selection algorithm
  53083. * indefinitely.
  53084. * @private
  53085. */
  53086. excludeIncompatibleVariants_(codecString) {
  53087. const ids = [];
  53088. const playlists = this.main().playlists;
  53089. const codecs = unwrapCodecList(parseCodecs(codecString));
  53090. const codecCount_ = codecCount(codecs);
  53091. const videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
  53092. const audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
  53093. Object.keys(playlists).forEach(key => {
  53094. const variant = playlists[key]; // check if we already processed this playlist.
  53095. // or it if it is already excluded forever.
  53096. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  53097. return;
  53098. }
  53099. ids.push(variant.id);
  53100. const exclusionReasons = []; // get codecs from the playlist for this variant
  53101. const variantCodecs = codecsForPlaylist(this.mainPlaylistLoader_.main, variant);
  53102. const variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  53103. // variant is incompatible. Wait for mux.js to probe
  53104. if (!variantCodecs.audio && !variantCodecs.video) {
  53105. return;
  53106. } // TODO: we can support this by removing the
  53107. // old media source and creating a new one, but it will take some work.
  53108. // The number of streams cannot change
  53109. if (variantCodecCount !== codecCount_) {
  53110. exclusionReasons.push(`codec count "${variantCodecCount}" !== "${codecCount_}"`);
  53111. } // only exclude playlists by codec change, if codecs cannot switch
  53112. // during playback.
  53113. if (!this.sourceUpdater_.canChangeType()) {
  53114. const variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
  53115. const variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  53116. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  53117. exclusionReasons.push(`video codec "${variantVideoDetails.type}" !== "${videoDetails.type}"`);
  53118. } // the audio codec cannot change
  53119. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  53120. exclusionReasons.push(`audio codec "${variantAudioDetails.type}" !== "${audioDetails.type}"`);
  53121. }
  53122. }
  53123. if (exclusionReasons.length) {
  53124. variant.excludeUntil = Infinity;
  53125. this.logger_(`excluding ${variant.id}: ${exclusionReasons.join(' && ')}`);
  53126. }
  53127. });
  53128. }
  53129. updateAdCues_(media) {
  53130. let offset = 0;
  53131. const seekable = this.seekable();
  53132. if (seekable.length) {
  53133. offset = seekable.start(0);
  53134. }
  53135. updateAdCues(media, this.cueTagsTrack_, offset);
  53136. }
  53137. /**
  53138. * Calculates the desired forward buffer length based on current time
  53139. *
  53140. * @return {number} Desired forward buffer length in seconds
  53141. */
  53142. goalBufferLength() {
  53143. const currentTime = this.tech_.currentTime();
  53144. const initial = Config.GOAL_BUFFER_LENGTH;
  53145. const rate = Config.GOAL_BUFFER_LENGTH_RATE;
  53146. const max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  53147. return Math.min(initial + currentTime * rate, max);
  53148. }
  53149. /**
  53150. * Calculates the desired buffer low water line based on current time
  53151. *
  53152. * @return {number} Desired buffer low water line in seconds
  53153. */
  53154. bufferLowWaterLine() {
  53155. const currentTime = this.tech_.currentTime();
  53156. const initial = Config.BUFFER_LOW_WATER_LINE;
  53157. const rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  53158. const max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  53159. const newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  53160. return Math.min(initial + currentTime * rate, this.bufferBasedABR ? newMax : max);
  53161. }
  53162. bufferHighWaterLine() {
  53163. return Config.BUFFER_HIGH_WATER_LINE;
  53164. }
  53165. }
  53166. /**
  53167. * Returns a function that acts as the Enable/disable playlist function.
  53168. *
  53169. * @param {PlaylistLoader} loader - The main playlist loader
  53170. * @param {string} playlistID - id of the playlist
  53171. * @param {Function} changePlaylistFn - A function to be called after a
  53172. * playlist's enabled-state has been changed. Will NOT be called if a
  53173. * playlist's enabled-state is unchanged
  53174. * @param {boolean=} enable - Value to set the playlist enabled-state to
  53175. * or if undefined returns the current enabled-state for the playlist
  53176. * @return {Function} Function for setting/getting enabled
  53177. */
  53178. const enableFunction = (loader, playlistID, changePlaylistFn) => enable => {
  53179. const playlist = loader.main.playlists[playlistID];
  53180. const incompatible = isIncompatible(playlist);
  53181. const currentlyEnabled = isEnabled(playlist);
  53182. if (typeof enable === 'undefined') {
  53183. return currentlyEnabled;
  53184. }
  53185. if (enable) {
  53186. delete playlist.disabled;
  53187. } else {
  53188. playlist.disabled = true;
  53189. }
  53190. if (enable !== currentlyEnabled && !incompatible) {
  53191. // Ensure the outside world knows about our changes
  53192. changePlaylistFn();
  53193. if (enable) {
  53194. loader.trigger('renditionenabled');
  53195. } else {
  53196. loader.trigger('renditiondisabled');
  53197. }
  53198. }
  53199. return enable;
  53200. };
  53201. /**
  53202. * The representation object encapsulates the publicly visible information
  53203. * in a media playlist along with a setter/getter-type function (enabled)
  53204. * for changing the enabled-state of a particular playlist entry
  53205. *
  53206. * @class Representation
  53207. */
  53208. class Representation {
  53209. constructor(vhsHandler, playlist, id) {
  53210. const {
  53211. playlistController_: pc
  53212. } = vhsHandler;
  53213. const qualityChangeFunction = pc.fastQualityChange_.bind(pc); // some playlist attributes are optional
  53214. if (playlist.attributes) {
  53215. const resolution = playlist.attributes.RESOLUTION;
  53216. this.width = resolution && resolution.width;
  53217. this.height = resolution && resolution.height;
  53218. this.bandwidth = playlist.attributes.BANDWIDTH;
  53219. this.frameRate = playlist.attributes['FRAME-RATE'];
  53220. }
  53221. this.codecs = codecsForPlaylist(pc.main(), playlist);
  53222. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  53223. // within the main playlist
  53224. this.id = id; // Partially-apply the enableFunction to create a playlist-
  53225. // specific variant
  53226. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  53227. }
  53228. }
  53229. /**
  53230. * A mixin function that adds the `representations` api to an instance
  53231. * of the VhsHandler class
  53232. *
  53233. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  53234. * representation API into
  53235. */
  53236. const renditionSelectionMixin = function (vhsHandler) {
  53237. // Add a single API-specific function to the VhsHandler instance
  53238. vhsHandler.representations = () => {
  53239. const main = vhsHandler.playlistController_.main();
  53240. const playlists = isAudioOnly(main) ? vhsHandler.playlistController_.getAudioTrackPlaylists_() : main.playlists;
  53241. if (!playlists) {
  53242. return [];
  53243. }
  53244. return playlists.filter(media => !isIncompatible(media)).map((e, i) => new Representation(vhsHandler, e, e.id));
  53245. };
  53246. };
  53247. /**
  53248. * @file playback-watcher.js
  53249. *
  53250. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  53251. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  53252. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  53253. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  53254. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  53255. */
  53256. const timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  53257. /**
  53258. * @class PlaybackWatcher
  53259. */
  53260. class PlaybackWatcher {
  53261. /**
  53262. * Represents an PlaybackWatcher object.
  53263. *
  53264. * @class
  53265. * @param {Object} options an object that includes the tech and settings
  53266. */
  53267. constructor(options) {
  53268. this.playlistController_ = options.playlistController;
  53269. this.tech_ = options.tech;
  53270. this.seekable = options.seekable;
  53271. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  53272. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  53273. this.media = options.media;
  53274. this.consecutiveUpdates = 0;
  53275. this.lastRecordedTime = null;
  53276. this.checkCurrentTimeTimeout_ = null;
  53277. this.logger_ = logger('PlaybackWatcher');
  53278. this.logger_('initialize');
  53279. const playHandler = () => this.monitorCurrentTime_();
  53280. const canPlayHandler = () => this.monitorCurrentTime_();
  53281. const waitingHandler = () => this.techWaiting_();
  53282. const cancelTimerHandler = () => this.resetTimeUpdate_();
  53283. const pc = this.playlistController_;
  53284. const loaderTypes = ['main', 'subtitle', 'audio'];
  53285. const loaderChecks = {};
  53286. loaderTypes.forEach(type => {
  53287. loaderChecks[type] = {
  53288. reset: () => this.resetSegmentDownloads_(type),
  53289. updateend: () => this.checkSegmentDownloads_(type)
  53290. };
  53291. pc[`${type}SegmentLoader_`].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  53292. // isn't changing we want to reset. We cannot assume that the new rendition
  53293. // will also be stalled, until after new appends.
  53294. pc[`${type}SegmentLoader_`].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  53295. // This prevents one segment playlists (single vtt or single segment content)
  53296. // from being detected as stalling. As the buffer will not change in those cases, since
  53297. // the buffer is the entire video duration.
  53298. this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  53299. });
  53300. /**
  53301. * We check if a seek was into a gap through the following steps:
  53302. * 1. We get a seeking event and we do not get a seeked event. This means that
  53303. * a seek was attempted but not completed.
  53304. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  53305. * removed everything from our buffer and appended a segment, and should be ready
  53306. * to check for gaps.
  53307. */
  53308. const setSeekingHandlers = fn => {
  53309. ['main', 'audio'].forEach(type => {
  53310. pc[`${type}SegmentLoader_`][fn]('appended', this.seekingAppendCheck_);
  53311. });
  53312. };
  53313. this.seekingAppendCheck_ = () => {
  53314. if (this.fixesBadSeeks_()) {
  53315. this.consecutiveUpdates = 0;
  53316. this.lastRecordedTime = this.tech_.currentTime();
  53317. setSeekingHandlers('off');
  53318. }
  53319. };
  53320. this.clearSeekingAppendCheck_ = () => setSeekingHandlers('off');
  53321. this.watchForBadSeeking_ = () => {
  53322. this.clearSeekingAppendCheck_();
  53323. setSeekingHandlers('on');
  53324. };
  53325. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  53326. this.tech_.on('seeking', this.watchForBadSeeking_);
  53327. this.tech_.on('waiting', waitingHandler);
  53328. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  53329. this.tech_.on('canplay', canPlayHandler);
  53330. /*
  53331. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  53332. is surfaced in one of two ways:
  53333. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  53334. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  53335. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  53336. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  53337. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  53338. even if the player is in a playing state
  53339. */
  53340. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  53341. this.dispose = () => {
  53342. this.clearSeekingAppendCheck_();
  53343. this.logger_('dispose');
  53344. this.tech_.off('waiting', waitingHandler);
  53345. this.tech_.off(timerCancelEvents, cancelTimerHandler);
  53346. this.tech_.off('canplay', canPlayHandler);
  53347. this.tech_.off('play', playHandler);
  53348. this.tech_.off('seeking', this.watchForBadSeeking_);
  53349. this.tech_.off('seeked', this.clearSeekingAppendCheck_);
  53350. loaderTypes.forEach(type => {
  53351. pc[`${type}SegmentLoader_`].off('appendsdone', loaderChecks[type].updateend);
  53352. pc[`${type}SegmentLoader_`].off('playlistupdate', loaderChecks[type].reset);
  53353. this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  53354. });
  53355. if (this.checkCurrentTimeTimeout_) {
  53356. window.clearTimeout(this.checkCurrentTimeTimeout_);
  53357. }
  53358. this.resetTimeUpdate_();
  53359. };
  53360. }
  53361. /**
  53362. * Periodically check current time to see if playback stopped
  53363. *
  53364. * @private
  53365. */
  53366. monitorCurrentTime_() {
  53367. this.checkCurrentTime_();
  53368. if (this.checkCurrentTimeTimeout_) {
  53369. window.clearTimeout(this.checkCurrentTimeTimeout_);
  53370. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  53371. this.checkCurrentTimeTimeout_ = window.setTimeout(this.monitorCurrentTime_.bind(this), 250);
  53372. }
  53373. /**
  53374. * Reset stalled download stats for a specific type of loader
  53375. *
  53376. * @param {string} type
  53377. * The segment loader type to check.
  53378. *
  53379. * @listens SegmentLoader#playlistupdate
  53380. * @listens Tech#seeking
  53381. * @listens Tech#seeked
  53382. */
  53383. resetSegmentDownloads_(type) {
  53384. const loader = this.playlistController_[`${type}SegmentLoader_`];
  53385. if (this[`${type}StalledDownloads_`] > 0) {
  53386. this.logger_(`resetting possible stalled download count for ${type} loader`);
  53387. }
  53388. this[`${type}StalledDownloads_`] = 0;
  53389. this[`${type}Buffered_`] = loader.buffered_();
  53390. }
  53391. /**
  53392. * Checks on every segment `appendsdone` to see
  53393. * if segment appends are making progress. If they are not
  53394. * and we are still downloading bytes. We exclude the playlist.
  53395. *
  53396. * @param {string} type
  53397. * The segment loader type to check.
  53398. *
  53399. * @listens SegmentLoader#appendsdone
  53400. */
  53401. checkSegmentDownloads_(type) {
  53402. const pc = this.playlistController_;
  53403. const loader = pc[`${type}SegmentLoader_`];
  53404. const buffered = loader.buffered_();
  53405. const isBufferedDifferent = isRangeDifferent(this[`${type}Buffered_`], buffered);
  53406. this[`${type}Buffered_`] = buffered; // if another watcher is going to fix the issue or
  53407. // the buffered value for this loader changed
  53408. // appends are working
  53409. if (isBufferedDifferent) {
  53410. this.resetSegmentDownloads_(type);
  53411. return;
  53412. }
  53413. this[`${type}StalledDownloads_`]++;
  53414. this.logger_(`found #${this[`${type}StalledDownloads_`]} ${type} appends that did not increase buffer (possible stalled download)`, {
  53415. playlistId: loader.playlist_ && loader.playlist_.id,
  53416. buffered: timeRangesToArray(buffered)
  53417. }); // after 10 possibly stalled appends with no reset, exclude
  53418. if (this[`${type}StalledDownloads_`] < 10) {
  53419. return;
  53420. }
  53421. this.logger_(`${type} loader stalled download exclusion`);
  53422. this.resetSegmentDownloads_(type);
  53423. this.tech_.trigger({
  53424. type: 'usage',
  53425. name: `vhs-${type}-download-exclusion`
  53426. });
  53427. if (type === 'subtitle') {
  53428. return;
  53429. } // TODO: should we exclude audio tracks rather than main tracks
  53430. // when type is audio?
  53431. pc.excludePlaylist({
  53432. error: {
  53433. message: `Excessive ${type} segment downloading detected.`
  53434. },
  53435. playlistExclusionDuration: Infinity
  53436. });
  53437. }
  53438. /**
  53439. * The purpose of this function is to emulate the "waiting" event on
  53440. * browsers that do not emit it when they are waiting for more
  53441. * data to continue playback
  53442. *
  53443. * @private
  53444. */
  53445. checkCurrentTime_() {
  53446. if (this.tech_.paused() || this.tech_.seeking()) {
  53447. return;
  53448. }
  53449. const currentTime = this.tech_.currentTime();
  53450. const buffered = this.tech_.buffered();
  53451. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  53452. // If current time is at the end of the final buffered region, then any playback
  53453. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  53454. // should fire a `waiting` event in this scenario, but due to browser and tech
  53455. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  53456. // responding to a native `waiting` event when the tech fails to emit one.
  53457. return this.techWaiting_();
  53458. }
  53459. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  53460. this.consecutiveUpdates++;
  53461. this.waiting_();
  53462. } else if (currentTime === this.lastRecordedTime) {
  53463. this.consecutiveUpdates++;
  53464. } else {
  53465. this.consecutiveUpdates = 0;
  53466. this.lastRecordedTime = currentTime;
  53467. }
  53468. }
  53469. /**
  53470. * Resets the 'timeupdate' mechanism designed to detect that we are stalled
  53471. *
  53472. * @private
  53473. */
  53474. resetTimeUpdate_() {
  53475. this.consecutiveUpdates = 0;
  53476. }
  53477. /**
  53478. * Fixes situations where there's a bad seek
  53479. *
  53480. * @return {boolean} whether an action was taken to fix the seek
  53481. * @private
  53482. */
  53483. fixesBadSeeks_() {
  53484. const seeking = this.tech_.seeking();
  53485. if (!seeking) {
  53486. return false;
  53487. } // TODO: It's possible that these seekable checks should be moved out of this function
  53488. // and into a function that runs on seekablechange. It's also possible that we only need
  53489. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  53490. // seekable range.
  53491. const seekable = this.seekable();
  53492. const currentTime = this.tech_.currentTime();
  53493. const isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  53494. let seekTo;
  53495. if (isAfterSeekableRange) {
  53496. const seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  53497. seekTo = seekableEnd;
  53498. }
  53499. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  53500. const seekableStart = seekable.start(0); // sync to the beginning of the live window
  53501. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  53502. seekTo = seekableStart + (
  53503. // if the playlist is too short and the seekable range is an exact time (can
  53504. // happen in live with a 3 segment playlist), then don't use a time delta
  53505. seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
  53506. }
  53507. if (typeof seekTo !== 'undefined') {
  53508. this.logger_(`Trying to seek outside of seekable at time ${currentTime} with ` + `seekable range ${printableRange(seekable)}. Seeking to ` + `${seekTo}.`);
  53509. this.tech_.setCurrentTime(seekTo);
  53510. return true;
  53511. }
  53512. const sourceUpdater = this.playlistController_.sourceUpdater_;
  53513. const buffered = this.tech_.buffered();
  53514. const audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  53515. const videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  53516. const media = this.media(); // verify that at least two segment durations or one part duration have been
  53517. // appended before checking for a gap.
  53518. const minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been
  53519. // appended before checking for a gap.
  53520. const bufferedToCheck = [audioBuffered, videoBuffered];
  53521. for (let i = 0; i < bufferedToCheck.length; i++) {
  53522. // skip null buffered
  53523. if (!bufferedToCheck[i]) {
  53524. continue;
  53525. }
  53526. const timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part
  53527. // duration behind we haven't appended enough to call this a bad seek.
  53528. if (timeAhead < minAppendedDuration) {
  53529. return false;
  53530. }
  53531. }
  53532. const nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered
  53533. // to seek over the gap
  53534. if (nextRange.length === 0) {
  53535. return false;
  53536. }
  53537. seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
  53538. this.logger_(`Buffered region starts (${nextRange.start(0)}) ` + ` just beyond seek point (${currentTime}). Seeking to ${seekTo}.`);
  53539. this.tech_.setCurrentTime(seekTo);
  53540. return true;
  53541. }
  53542. /**
  53543. * Handler for situations when we determine the player is waiting.
  53544. *
  53545. * @private
  53546. */
  53547. waiting_() {
  53548. if (this.techWaiting_()) {
  53549. return;
  53550. } // All tech waiting checks failed. Use last resort correction
  53551. const currentTime = this.tech_.currentTime();
  53552. const buffered = this.tech_.buffered();
  53553. const currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  53554. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  53555. // currentTime is usually enough to kickstart the player. This checks that the player
  53556. // is currently within a buffered region before attempting a corrective seek.
  53557. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  53558. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  53559. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  53560. // to avoid triggering an `unknownwaiting` event when the network is slow.
  53561. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  53562. this.resetTimeUpdate_();
  53563. this.tech_.setCurrentTime(currentTime);
  53564. 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
  53565. this.tech_.trigger({
  53566. type: 'usage',
  53567. name: 'vhs-unknown-waiting'
  53568. });
  53569. return;
  53570. }
  53571. }
  53572. /**
  53573. * Handler for situations when the tech fires a `waiting` event
  53574. *
  53575. * @return {boolean}
  53576. * True if an action (or none) was needed to correct the waiting. False if no
  53577. * checks passed
  53578. * @private
  53579. */
  53580. techWaiting_() {
  53581. const seekable = this.seekable();
  53582. const currentTime = this.tech_.currentTime();
  53583. if (this.tech_.seeking()) {
  53584. // Tech is seeking or already waiting on another action, no action needed
  53585. return true;
  53586. }
  53587. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  53588. const livePoint = seekable.end(seekable.length - 1);
  53589. this.logger_(`Fell out of live window at time ${currentTime}. Seeking to ` + `live point (seekable end) ${livePoint}`);
  53590. this.resetTimeUpdate_();
  53591. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  53592. this.tech_.trigger({
  53593. type: 'usage',
  53594. name: 'vhs-live-resync'
  53595. });
  53596. return true;
  53597. }
  53598. const sourceUpdater = this.tech_.vhs.playlistController_.sourceUpdater_;
  53599. const buffered = this.tech_.buffered();
  53600. const videoUnderflow = this.videoUnderflow_({
  53601. audioBuffered: sourceUpdater.audioBuffered(),
  53602. videoBuffered: sourceUpdater.videoBuffered(),
  53603. currentTime
  53604. });
  53605. if (videoUnderflow) {
  53606. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  53607. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  53608. // allows the video to catch up to the audio position without losing any audio
  53609. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  53610. this.resetTimeUpdate_();
  53611. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  53612. this.tech_.trigger({
  53613. type: 'usage',
  53614. name: 'vhs-video-underflow'
  53615. });
  53616. return true;
  53617. }
  53618. const nextRange = findNextRange(buffered, currentTime); // check for gap
  53619. if (nextRange.length > 0) {
  53620. this.logger_(`Stopped at ${currentTime} and seeking to ${nextRange.start(0)}`);
  53621. this.resetTimeUpdate_();
  53622. this.skipTheGap_(currentTime);
  53623. return true;
  53624. } // All checks failed. Returning false to indicate failure to correct waiting
  53625. return false;
  53626. }
  53627. afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow = false) {
  53628. if (!seekable.length) {
  53629. // we can't make a solid case if there's no seekable, default to false
  53630. return false;
  53631. }
  53632. let allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  53633. const isLive = !playlist.endList;
  53634. if (isLive && allowSeeksWithinUnsafeLiveWindow) {
  53635. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  53636. }
  53637. if (currentTime > allowedEnd) {
  53638. return true;
  53639. }
  53640. return false;
  53641. }
  53642. beforeSeekableWindow_(seekable, currentTime) {
  53643. if (seekable.length &&
  53644. // can't fall before 0 and 0 seekable start identifies VOD stream
  53645. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  53646. return true;
  53647. }
  53648. return false;
  53649. }
  53650. videoUnderflow_({
  53651. videoBuffered,
  53652. audioBuffered,
  53653. currentTime
  53654. }) {
  53655. // audio only content will not have video underflow :)
  53656. if (!videoBuffered) {
  53657. return;
  53658. }
  53659. let gap; // find a gap in demuxed content.
  53660. if (videoBuffered.length && audioBuffered.length) {
  53661. // in Chrome audio will continue to play for ~3s when we run out of video
  53662. // so we have to check that the video buffer did have some buffer in the
  53663. // past.
  53664. const lastVideoRange = findRange(videoBuffered, currentTime - 3);
  53665. const videoRange = findRange(videoBuffered, currentTime);
  53666. const audioRange = findRange(audioBuffered, currentTime);
  53667. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  53668. gap = {
  53669. start: lastVideoRange.end(0),
  53670. end: audioRange.end(0)
  53671. };
  53672. } // find a gap in muxed content.
  53673. } else {
  53674. const nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  53675. // stuck in a gap due to video underflow.
  53676. if (!nextRange.length) {
  53677. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  53678. }
  53679. }
  53680. if (gap) {
  53681. this.logger_(`Encountered a gap in video from ${gap.start} to ${gap.end}. ` + `Seeking to current time ${currentTime}`);
  53682. return true;
  53683. }
  53684. return false;
  53685. }
  53686. /**
  53687. * Timer callback. If playback still has not proceeded, then we seek
  53688. * to the start of the next buffered region.
  53689. *
  53690. * @private
  53691. */
  53692. skipTheGap_(scheduledCurrentTime) {
  53693. const buffered = this.tech_.buffered();
  53694. const currentTime = this.tech_.currentTime();
  53695. const nextRange = findNextRange(buffered, currentTime);
  53696. this.resetTimeUpdate_();
  53697. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  53698. return;
  53699. }
  53700. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  53701. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  53702. this.tech_.trigger({
  53703. type: 'usage',
  53704. name: 'vhs-gap-skip'
  53705. });
  53706. }
  53707. gapFromVideoUnderflow_(buffered, currentTime) {
  53708. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  53709. // playing for ~3 seconds after the video gap starts. This is done to account for
  53710. // video buffer underflow/underrun (note that this is not done when there is audio
  53711. // buffer underflow/underrun -- in that case the video will stop as soon as it
  53712. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  53713. // video stalls). The player's time will reflect the playthrough of audio, so the
  53714. // time will appear as if we are in a buffered region, even if we are stuck in a
  53715. // "gap."
  53716. //
  53717. // Example:
  53718. // video buffer: 0 => 10.1, 10.2 => 20
  53719. // audio buffer: 0 => 20
  53720. // overall buffer: 0 => 10.1, 10.2 => 20
  53721. // current time: 13
  53722. //
  53723. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  53724. // however, the audio continued playing until it reached ~3 seconds past the gap
  53725. // (13 seconds), at which point it stops as well. Since current time is past the
  53726. // gap, findNextRange will return no ranges.
  53727. //
  53728. // To check for this issue, we see if there is a gap that starts somewhere within
  53729. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  53730. const gaps = findGaps(buffered);
  53731. for (let i = 0; i < gaps.length; i++) {
  53732. const start = gaps.start(i);
  53733. const end = gaps.end(i); // gap is starts no more than 4 seconds back
  53734. if (currentTime - start < 4 && currentTime - start > 2) {
  53735. return {
  53736. start,
  53737. end
  53738. };
  53739. }
  53740. }
  53741. return null;
  53742. }
  53743. }
  53744. const defaultOptions = {
  53745. errorInterval: 30,
  53746. getSource(next) {
  53747. const tech = this.tech({
  53748. IWillNotUseThisInPlugins: true
  53749. });
  53750. const sourceObj = tech.currentSource_ || this.currentSource();
  53751. return next(sourceObj);
  53752. }
  53753. };
  53754. /**
  53755. * Main entry point for the plugin
  53756. *
  53757. * @param {Player} player a reference to a videojs Player instance
  53758. * @param {Object} [options] an object with plugin options
  53759. * @private
  53760. */
  53761. const initPlugin = function (player, options) {
  53762. let lastCalled = 0;
  53763. let seekTo = 0;
  53764. const localOptions = merge(defaultOptions, options);
  53765. player.ready(() => {
  53766. player.trigger({
  53767. type: 'usage',
  53768. name: 'vhs-error-reload-initialized'
  53769. });
  53770. });
  53771. /**
  53772. * Player modifications to perform that must wait until `loadedmetadata`
  53773. * has been triggered
  53774. *
  53775. * @private
  53776. */
  53777. const loadedMetadataHandler = function () {
  53778. if (seekTo) {
  53779. player.currentTime(seekTo);
  53780. }
  53781. };
  53782. /**
  53783. * Set the source on the player element, play, and seek if necessary
  53784. *
  53785. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  53786. * @private
  53787. */
  53788. const setSource = function (sourceObj) {
  53789. if (sourceObj === null || sourceObj === undefined) {
  53790. return;
  53791. }
  53792. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  53793. player.one('loadedmetadata', loadedMetadataHandler);
  53794. player.src(sourceObj);
  53795. player.trigger({
  53796. type: 'usage',
  53797. name: 'vhs-error-reload'
  53798. });
  53799. player.play();
  53800. };
  53801. /**
  53802. * Attempt to get a source from either the built-in getSource function
  53803. * or a custom function provided via the options
  53804. *
  53805. * @private
  53806. */
  53807. const errorHandler = function () {
  53808. // Do not attempt to reload the source if a source-reload occurred before
  53809. // 'errorInterval' time has elapsed since the last source-reload
  53810. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  53811. player.trigger({
  53812. type: 'usage',
  53813. name: 'vhs-error-reload-canceled'
  53814. });
  53815. return;
  53816. }
  53817. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  53818. videojs.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  53819. return;
  53820. }
  53821. lastCalled = Date.now();
  53822. return localOptions.getSource.call(player, setSource);
  53823. };
  53824. /**
  53825. * Unbind any event handlers that were bound by the plugin
  53826. *
  53827. * @private
  53828. */
  53829. const cleanupEvents = function () {
  53830. player.off('loadedmetadata', loadedMetadataHandler);
  53831. player.off('error', errorHandler);
  53832. player.off('dispose', cleanupEvents);
  53833. };
  53834. /**
  53835. * Cleanup before re-initializing the plugin
  53836. *
  53837. * @param {Object} [newOptions] an object with plugin options
  53838. * @private
  53839. */
  53840. const reinitPlugin = function (newOptions) {
  53841. cleanupEvents();
  53842. initPlugin(player, newOptions);
  53843. };
  53844. player.on('error', errorHandler);
  53845. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  53846. // initializing the plugin
  53847. player.reloadSourceOnError = reinitPlugin;
  53848. };
  53849. /**
  53850. * Reload the source when an error is detected as long as there
  53851. * wasn't an error previously within the last 30 seconds
  53852. *
  53853. * @param {Object} [options] an object with plugin options
  53854. */
  53855. const reloadSourceOnError = function (options) {
  53856. initPlugin(this, options);
  53857. };
  53858. var version$4 = "3.0.2";
  53859. var version$3 = "6.3.0";
  53860. var version$2 = "1.0.1";
  53861. var version$1 = "6.0.0";
  53862. var version = "4.0.1";
  53863. /**
  53864. * @file videojs-http-streaming.js
  53865. *
  53866. * The main file for the VHS project.
  53867. * License: https://github.com/videojs/videojs-http-streaming/blob/main/LICENSE
  53868. */
  53869. const Vhs = {
  53870. PlaylistLoader,
  53871. Playlist,
  53872. utils,
  53873. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  53874. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  53875. lastBandwidthSelector,
  53876. movingAverageBandwidthSelector,
  53877. comparePlaylistBandwidth,
  53878. comparePlaylistResolution,
  53879. xhr: xhrFactory()
  53880. }; // Define getter/setters for config properties
  53881. Object.keys(Config).forEach(prop => {
  53882. Object.defineProperty(Vhs, prop, {
  53883. get() {
  53884. videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  53885. return Config[prop];
  53886. },
  53887. set(value) {
  53888. videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  53889. if (typeof value !== 'number' || value < 0) {
  53890. videojs.log.warn(`value of Vhs.${prop} must be greater than or equal to 0`);
  53891. return;
  53892. }
  53893. Config[prop] = value;
  53894. }
  53895. });
  53896. });
  53897. const LOCAL_STORAGE_KEY = 'videojs-vhs';
  53898. /**
  53899. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  53900. *
  53901. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  53902. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  53903. * @function handleVhsMediaChange
  53904. */
  53905. const handleVhsMediaChange = function (qualityLevels, playlistLoader) {
  53906. const newPlaylist = playlistLoader.media();
  53907. let selectedIndex = -1;
  53908. for (let i = 0; i < qualityLevels.length; i++) {
  53909. if (qualityLevels[i].id === newPlaylist.id) {
  53910. selectedIndex = i;
  53911. break;
  53912. }
  53913. }
  53914. qualityLevels.selectedIndex_ = selectedIndex;
  53915. qualityLevels.trigger({
  53916. selectedIndex,
  53917. type: 'change'
  53918. });
  53919. };
  53920. /**
  53921. * Adds quality levels to list once playlist metadata is available
  53922. *
  53923. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  53924. * @param {Object} vhs Vhs object to listen to for media events.
  53925. * @function handleVhsLoadedMetadata
  53926. */
  53927. const handleVhsLoadedMetadata = function (qualityLevels, vhs) {
  53928. vhs.representations().forEach(rep => {
  53929. qualityLevels.addQualityLevel(rep);
  53930. });
  53931. handleVhsMediaChange(qualityLevels, vhs.playlists);
  53932. }; // VHS is a source handler, not a tech. Make sure attempts to use it
  53933. // as one do not cause exceptions.
  53934. Vhs.canPlaySource = function () {
  53935. return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  53936. };
  53937. const emeKeySystems = (keySystemOptions, mainPlaylist, audioPlaylist) => {
  53938. if (!keySystemOptions) {
  53939. return keySystemOptions;
  53940. }
  53941. let codecs = {};
  53942. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  53943. codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
  53944. }
  53945. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  53946. codecs.audio = audioPlaylist.attributes.CODECS;
  53947. }
  53948. const videoContentType = getMimeForCodec(codecs.video);
  53949. const audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  53950. const keySystemContentTypes = {};
  53951. for (const keySystem in keySystemOptions) {
  53952. keySystemContentTypes[keySystem] = {};
  53953. if (audioContentType) {
  53954. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  53955. }
  53956. if (videoContentType) {
  53957. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  53958. } // Default to using the video playlist's PSSH even though they may be different, as
  53959. // videojs-contrib-eme will only accept one in the options.
  53960. //
  53961. // This shouldn't be an issue for most cases as early intialization will handle all
  53962. // unique PSSH values, and if they aren't, then encrypted events should have the
  53963. // specific information needed for the unique license.
  53964. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  53965. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  53966. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  53967. // so we need to prevent overwriting the URL entirely
  53968. if (typeof keySystemOptions[keySystem] === 'string') {
  53969. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  53970. }
  53971. }
  53972. return merge(keySystemOptions, keySystemContentTypes);
  53973. };
  53974. /**
  53975. * @typedef {Object} KeySystems
  53976. *
  53977. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  53978. * Note: not all options are listed here.
  53979. *
  53980. * @property {Uint8Array} [pssh]
  53981. * Protection System Specific Header
  53982. */
  53983. /**
  53984. * Goes through all the playlists and collects an array of KeySystems options objects
  53985. * containing each playlist's keySystems and their pssh values, if available.
  53986. *
  53987. * @param {Object[]} playlists
  53988. * The playlists to look through
  53989. * @param {string[]} keySystems
  53990. * The keySystems to collect pssh values for
  53991. *
  53992. * @return {KeySystems[]}
  53993. * An array of KeySystems objects containing available key systems and their
  53994. * pssh values
  53995. */
  53996. const getAllPsshKeySystemsOptions = (playlists, keySystems) => {
  53997. return playlists.reduce((keySystemsArr, playlist) => {
  53998. if (!playlist.contentProtection) {
  53999. return keySystemsArr;
  54000. }
  54001. const keySystemsOptions = keySystems.reduce((keySystemsObj, keySystem) => {
  54002. const keySystemOptions = playlist.contentProtection[keySystem];
  54003. if (keySystemOptions && keySystemOptions.pssh) {
  54004. keySystemsObj[keySystem] = {
  54005. pssh: keySystemOptions.pssh
  54006. };
  54007. }
  54008. return keySystemsObj;
  54009. }, {});
  54010. if (Object.keys(keySystemsOptions).length) {
  54011. keySystemsArr.push(keySystemsOptions);
  54012. }
  54013. return keySystemsArr;
  54014. }, []);
  54015. };
  54016. /**
  54017. * Returns a promise that waits for the
  54018. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  54019. *
  54020. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  54021. * browsers.
  54022. *
  54023. * As per the above ticket, this is particularly important for Chrome, where, if
  54024. * unencrypted content is appended before encrypted content and the key session has not
  54025. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  54026. * during playback.
  54027. *
  54028. * @param {Object} player
  54029. * The player instance
  54030. * @param {Object[]} sourceKeySystems
  54031. * The key systems options from the player source
  54032. * @param {Object} [audioMedia]
  54033. * The active audio media playlist (optional)
  54034. * @param {Object[]} mainPlaylists
  54035. * The playlists found on the main playlist object
  54036. *
  54037. * @return {Object}
  54038. * Promise that resolves when the key session has been created
  54039. */
  54040. const waitForKeySessionCreation = ({
  54041. player,
  54042. sourceKeySystems,
  54043. audioMedia,
  54044. mainPlaylists
  54045. }) => {
  54046. if (!player.eme.initializeMediaKeys) {
  54047. return Promise.resolve();
  54048. } // TODO should all audio PSSH values be initialized for DRM?
  54049. //
  54050. // All unique video rendition pssh values are initialized for DRM, but here only
  54051. // the initial audio playlist license is initialized. In theory, an encrypted
  54052. // event should be fired if the user switches to an alternative audio playlist
  54053. // where a license is required, but this case hasn't yet been tested. In addition, there
  54054. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  54055. // languages).
  54056. const playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  54057. const keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  54058. const initializationFinishedPromises = [];
  54059. const keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  54060. // only place where it should not be deduped is for ms-prefixed APIs, but the early
  54061. // return for IE11 above, and the existence of modern EME APIs in addition to
  54062. // ms-prefixed APIs on Edge should prevent this from being a concern.
  54063. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  54064. keySystemsOptionsArr.forEach(keySystemsOptions => {
  54065. keySessionCreatedPromises.push(new Promise((resolve, reject) => {
  54066. player.tech_.one('keysessioncreated', resolve);
  54067. }));
  54068. initializationFinishedPromises.push(new Promise((resolve, reject) => {
  54069. player.eme.initializeMediaKeys({
  54070. keySystems: keySystemsOptions
  54071. }, err => {
  54072. if (err) {
  54073. reject(err);
  54074. return;
  54075. }
  54076. resolve();
  54077. });
  54078. }));
  54079. }); // The reasons Promise.race is chosen over Promise.any:
  54080. //
  54081. // * Promise.any is only available in Safari 14+.
  54082. // * None of these promises are expected to reject. If they do reject, it might be
  54083. // better here for the race to surface the rejection, rather than mask it by using
  54084. // Promise.any.
  54085. return Promise.race([
  54086. // If a session was previously created, these will all finish resolving without
  54087. // creating a new session, otherwise it will take until the end of all license
  54088. // requests, which is why the key session check is used (to make setup much faster).
  54089. Promise.all(initializationFinishedPromises),
  54090. // Once a single session is created, the browser knows DRM will be used.
  54091. Promise.race(keySessionCreatedPromises)]);
  54092. };
  54093. /**
  54094. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  54095. * there are keySystems on the source, sets up source options to prepare the source for
  54096. * eme.
  54097. *
  54098. * @param {Object} player
  54099. * The player instance
  54100. * @param {Object[]} sourceKeySystems
  54101. * The key systems options from the player source
  54102. * @param {Object} media
  54103. * The active media playlist
  54104. * @param {Object} [audioMedia]
  54105. * The active audio media playlist (optional)
  54106. *
  54107. * @return {boolean}
  54108. * Whether or not options were configured and EME is available
  54109. */
  54110. const setupEmeOptions = ({
  54111. player,
  54112. sourceKeySystems,
  54113. media,
  54114. audioMedia
  54115. }) => {
  54116. const sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  54117. if (!sourceOptions) {
  54118. return false;
  54119. }
  54120. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  54121. // do nothing.
  54122. if (sourceOptions && !player.eme) {
  54123. videojs.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  54124. return false;
  54125. }
  54126. return true;
  54127. };
  54128. const getVhsLocalStorage = () => {
  54129. if (!window.localStorage) {
  54130. return null;
  54131. }
  54132. const storedObject = window.localStorage.getItem(LOCAL_STORAGE_KEY);
  54133. if (!storedObject) {
  54134. return null;
  54135. }
  54136. try {
  54137. return JSON.parse(storedObject);
  54138. } catch (e) {
  54139. // someone may have tampered with the value
  54140. return null;
  54141. }
  54142. };
  54143. const updateVhsLocalStorage = options => {
  54144. if (!window.localStorage) {
  54145. return false;
  54146. }
  54147. let objectToStore = getVhsLocalStorage();
  54148. objectToStore = objectToStore ? merge(objectToStore, options) : options;
  54149. try {
  54150. window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  54151. } catch (e) {
  54152. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  54153. // storage is set to 0).
  54154. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  54155. // No need to perform any operation.
  54156. return false;
  54157. }
  54158. return objectToStore;
  54159. };
  54160. /**
  54161. * Parses VHS-supported media types from data URIs. See
  54162. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  54163. * for information on data URIs.
  54164. *
  54165. * @param {string} dataUri
  54166. * The data URI
  54167. *
  54168. * @return {string|Object}
  54169. * The parsed object/string, or the original string if no supported media type
  54170. * was found
  54171. */
  54172. const expandDataUri = dataUri => {
  54173. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  54174. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  54175. } // no known case for this data URI, return the string as-is
  54176. return dataUri;
  54177. };
  54178. /**
  54179. * Whether the browser has built-in HLS support.
  54180. */
  54181. Vhs.supportsNativeHls = function () {
  54182. if (!document || !document.createElement) {
  54183. return false;
  54184. }
  54185. const video = document.createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  54186. if (!videojs.getTech('Html5').isSupported()) {
  54187. return false;
  54188. } // HLS manifests can go by many mime-types
  54189. const canPlay = [
  54190. // Apple santioned
  54191. 'application/vnd.apple.mpegurl',
  54192. // Apple sanctioned for backwards compatibility
  54193. 'audio/mpegurl',
  54194. // Very common
  54195. 'audio/x-mpegurl',
  54196. // Very common
  54197. 'application/x-mpegurl',
  54198. // Included for completeness
  54199. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  54200. return canPlay.some(function (canItPlay) {
  54201. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  54202. });
  54203. }();
  54204. Vhs.supportsNativeDash = function () {
  54205. if (!document || !document.createElement || !videojs.getTech('Html5').isSupported()) {
  54206. return false;
  54207. }
  54208. return /maybe|probably/i.test(document.createElement('video').canPlayType('application/dash+xml'));
  54209. }();
  54210. Vhs.supportsTypeNatively = type => {
  54211. if (type === 'hls') {
  54212. return Vhs.supportsNativeHls;
  54213. }
  54214. if (type === 'dash') {
  54215. return Vhs.supportsNativeDash;
  54216. }
  54217. return false;
  54218. };
  54219. /**
  54220. * VHS is a source handler, not a tech. Make sure attempts to use it
  54221. * as one do not cause exceptions.
  54222. */
  54223. Vhs.isSupported = function () {
  54224. return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  54225. };
  54226. const Component = videojs.getComponent('Component');
  54227. /**
  54228. * The Vhs Handler object, where we orchestrate all of the parts
  54229. * of VHS to interact with video.js
  54230. *
  54231. * @class VhsHandler
  54232. * @extends videojs.Component
  54233. * @param {Object} source the soruce object
  54234. * @param {Tech} tech the parent tech object
  54235. * @param {Object} options optional and required options
  54236. */
  54237. class VhsHandler extends Component {
  54238. constructor(source, tech, options) {
  54239. super(tech, options.vhs); // if a tech level `initialBandwidth` option was passed
  54240. // use that over the VHS level `bandwidth` option
  54241. if (typeof options.initialBandwidth === 'number') {
  54242. this.options_.bandwidth = options.initialBandwidth;
  54243. }
  54244. this.logger_ = logger('VhsHandler'); // we need access to the player in some cases,
  54245. // so, get it from Video.js via the `playerId`
  54246. if (tech.options_ && tech.options_.playerId) {
  54247. const _player = videojs.getPlayer(tech.options_.playerId);
  54248. this.player_ = _player;
  54249. }
  54250. this.tech_ = tech;
  54251. this.source_ = source;
  54252. this.stats = {};
  54253. this.ignoreNextSeekingEvent_ = false;
  54254. this.setOptions_();
  54255. if (this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  54256. tech.overrideNativeAudioTracks(true);
  54257. tech.overrideNativeVideoTracks(true);
  54258. } else if (this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  54259. // overriding native VHS only works if audio tracks have been emulated
  54260. // error early if we're misconfigured
  54261. throw new Error('Overriding native VHS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  54262. } // listen for fullscreenchange events for this player so that we
  54263. // can adjust our quality selection quickly
  54264. this.on(document, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], event => {
  54265. const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  54266. if (fullscreenElement && fullscreenElement.contains(this.tech_.el())) {
  54267. this.playlistController_.fastQualityChange_();
  54268. } else {
  54269. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  54270. // than full screen, see if there should be a rendition switch down to preserve
  54271. // bandwidth.
  54272. this.playlistController_.checkABR_();
  54273. }
  54274. });
  54275. this.on(this.tech_, 'seeking', function () {
  54276. if (this.ignoreNextSeekingEvent_) {
  54277. this.ignoreNextSeekingEvent_ = false;
  54278. return;
  54279. }
  54280. this.setCurrentTime(this.tech_.currentTime());
  54281. });
  54282. this.on(this.tech_, 'error', function () {
  54283. // verify that the error was real and we are loaded
  54284. // enough to have pc loaded.
  54285. if (this.tech_.error() && this.playlistController_) {
  54286. this.playlistController_.pauseLoading();
  54287. }
  54288. });
  54289. this.on(this.tech_, 'play', this.play);
  54290. }
  54291. setOptions_() {
  54292. // defaults
  54293. this.options_.withCredentials = this.options_.withCredentials || false;
  54294. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  54295. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  54296. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  54297. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  54298. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  54299. this.options_.customTagParsers = this.options_.customTagParsers || [];
  54300. this.options_.customTagMappers = this.options_.customTagMappers || [];
  54301. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  54302. this.options_.llhls = this.options_.llhls === false ? false : true;
  54303. this.options_.bufferBasedABR = this.options_.bufferBasedABR || false;
  54304. if (typeof this.options_.playlistExclusionDuration !== 'number') {
  54305. this.options_.playlistExclusionDuration = 5 * 60;
  54306. }
  54307. if (typeof this.options_.bandwidth !== 'number') {
  54308. if (this.options_.useBandwidthFromLocalStorage) {
  54309. const storedObject = getVhsLocalStorage();
  54310. if (storedObject && storedObject.bandwidth) {
  54311. this.options_.bandwidth = storedObject.bandwidth;
  54312. this.tech_.trigger({
  54313. type: 'usage',
  54314. name: 'vhs-bandwidth-from-local-storage'
  54315. });
  54316. }
  54317. if (storedObject && storedObject.throughput) {
  54318. this.options_.throughput = storedObject.throughput;
  54319. this.tech_.trigger({
  54320. type: 'usage',
  54321. name: 'vhs-throughput-from-local-storage'
  54322. });
  54323. }
  54324. }
  54325. } // if bandwidth was not set by options or pulled from local storage, start playlist
  54326. // selection at a reasonable bandwidth
  54327. if (typeof this.options_.bandwidth !== 'number') {
  54328. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  54329. } // If the bandwidth number is unchanged from the initial setting
  54330. // then this takes precedence over the enableLowInitialPlaylist option
  54331. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  54332. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'customTagParsers', 'customTagMappers', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'bufferBasedABR', 'liveRangeSafeTimeDelta', 'llhls', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'exactManifestTimings', 'leastPixelDiffSelector'].forEach(option => {
  54333. if (typeof this.source_[option] !== 'undefined') {
  54334. this.options_[option] = this.source_[option];
  54335. }
  54336. });
  54337. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  54338. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  54339. }
  54340. /**
  54341. * called when player.src gets called, handle a new source
  54342. *
  54343. * @param {Object} src the source object to handle
  54344. */
  54345. src(src, type) {
  54346. // do nothing if the src is falsey
  54347. if (!src) {
  54348. return;
  54349. }
  54350. this.setOptions_(); // add main playlist controller options
  54351. this.options_.src = expandDataUri(this.source_.src);
  54352. this.options_.tech = this.tech_;
  54353. this.options_.externVhs = Vhs;
  54354. this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  54355. this.options_.seekTo = time => {
  54356. this.tech_.setCurrentTime(time);
  54357. };
  54358. this.playlistController_ = new PlaylistController(this.options_);
  54359. const playbackWatcherOptions = merge({
  54360. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  54361. }, this.options_, {
  54362. seekable: () => this.seekable(),
  54363. media: () => this.playlistController_.media(),
  54364. playlistController: this.playlistController_
  54365. });
  54366. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  54367. this.playlistController_.on('error', () => {
  54368. const player = videojs.players[this.tech_.options_.playerId];
  54369. let error = this.playlistController_.error;
  54370. if (typeof error === 'object' && !error.code) {
  54371. error.code = 3;
  54372. } else if (typeof error === 'string') {
  54373. error = {
  54374. message: error,
  54375. code: 3
  54376. };
  54377. }
  54378. player.error(error);
  54379. });
  54380. const defaultSelector = this.options_.bufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  54381. // compatibility with < v2
  54382. this.playlistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  54383. this.playlistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  54384. this.playlists = this.playlistController_.mainPlaylistLoader_;
  54385. this.mediaSource = this.playlistController_.mediaSource; // Proxy assignment of some properties to the main playlist
  54386. // controller. Using a custom property for backwards compatibility
  54387. // with < v2
  54388. Object.defineProperties(this, {
  54389. selectPlaylist: {
  54390. get() {
  54391. return this.playlistController_.selectPlaylist;
  54392. },
  54393. set(selectPlaylist) {
  54394. this.playlistController_.selectPlaylist = selectPlaylist.bind(this);
  54395. }
  54396. },
  54397. throughput: {
  54398. get() {
  54399. return this.playlistController_.mainSegmentLoader_.throughput.rate;
  54400. },
  54401. set(throughput) {
  54402. this.playlistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  54403. // for the cumulative average
  54404. this.playlistController_.mainSegmentLoader_.throughput.count = 1;
  54405. }
  54406. },
  54407. bandwidth: {
  54408. get() {
  54409. let playerBandwidthEst = this.playlistController_.mainSegmentLoader_.bandwidth;
  54410. const networkInformation = window.navigator.connection || window.navigator.mozConnection || window.navigator.webkitConnection;
  54411. const tenMbpsAsBitsPerSecond = 10e6;
  54412. if (this.options_.useNetworkInformationApi && networkInformation) {
  54413. // downlink returns Mbps
  54414. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  54415. const networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  54416. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  54417. // high quality streams are not filtered out.
  54418. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  54419. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  54420. } else {
  54421. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  54422. }
  54423. }
  54424. return playerBandwidthEst;
  54425. },
  54426. set(bandwidth) {
  54427. this.playlistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  54428. // `count` is set to zero that current value of `rate` isn't included
  54429. // in the cumulative average
  54430. this.playlistController_.mainSegmentLoader_.throughput = {
  54431. rate: 0,
  54432. count: 0
  54433. };
  54434. }
  54435. },
  54436. /**
  54437. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  54438. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  54439. * the entire process after that - decryption, transmuxing, and appending - provided
  54440. * by `throughput`.
  54441. *
  54442. * Since the two process are serial, the overall system bandwidth is given by:
  54443. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  54444. */
  54445. systemBandwidth: {
  54446. get() {
  54447. const invBandwidth = 1 / (this.bandwidth || 1);
  54448. let invThroughput;
  54449. if (this.throughput > 0) {
  54450. invThroughput = 1 / this.throughput;
  54451. } else {
  54452. invThroughput = 0;
  54453. }
  54454. const systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  54455. return systemBitrate;
  54456. },
  54457. set() {
  54458. videojs.log.error('The "systemBandwidth" property is read-only');
  54459. }
  54460. }
  54461. });
  54462. if (this.options_.bandwidth) {
  54463. this.bandwidth = this.options_.bandwidth;
  54464. }
  54465. if (this.options_.throughput) {
  54466. this.throughput = this.options_.throughput;
  54467. }
  54468. Object.defineProperties(this.stats, {
  54469. bandwidth: {
  54470. get: () => this.bandwidth || 0,
  54471. enumerable: true
  54472. },
  54473. mediaRequests: {
  54474. get: () => this.playlistController_.mediaRequests_() || 0,
  54475. enumerable: true
  54476. },
  54477. mediaRequestsAborted: {
  54478. get: () => this.playlistController_.mediaRequestsAborted_() || 0,
  54479. enumerable: true
  54480. },
  54481. mediaRequestsTimedout: {
  54482. get: () => this.playlistController_.mediaRequestsTimedout_() || 0,
  54483. enumerable: true
  54484. },
  54485. mediaRequestsErrored: {
  54486. get: () => this.playlistController_.mediaRequestsErrored_() || 0,
  54487. enumerable: true
  54488. },
  54489. mediaTransferDuration: {
  54490. get: () => this.playlistController_.mediaTransferDuration_() || 0,
  54491. enumerable: true
  54492. },
  54493. mediaBytesTransferred: {
  54494. get: () => this.playlistController_.mediaBytesTransferred_() || 0,
  54495. enumerable: true
  54496. },
  54497. mediaSecondsLoaded: {
  54498. get: () => this.playlistController_.mediaSecondsLoaded_() || 0,
  54499. enumerable: true
  54500. },
  54501. mediaAppends: {
  54502. get: () => this.playlistController_.mediaAppends_() || 0,
  54503. enumerable: true
  54504. },
  54505. mainAppendsToLoadedData: {
  54506. get: () => this.playlistController_.mainAppendsToLoadedData_() || 0,
  54507. enumerable: true
  54508. },
  54509. audioAppendsToLoadedData: {
  54510. get: () => this.playlistController_.audioAppendsToLoadedData_() || 0,
  54511. enumerable: true
  54512. },
  54513. appendsToLoadedData: {
  54514. get: () => this.playlistController_.appendsToLoadedData_() || 0,
  54515. enumerable: true
  54516. },
  54517. timeToLoadedData: {
  54518. get: () => this.playlistController_.timeToLoadedData_() || 0,
  54519. enumerable: true
  54520. },
  54521. buffered: {
  54522. get: () => timeRangesToArray(this.tech_.buffered()),
  54523. enumerable: true
  54524. },
  54525. currentTime: {
  54526. get: () => this.tech_.currentTime(),
  54527. enumerable: true
  54528. },
  54529. currentSource: {
  54530. get: () => this.tech_.currentSource_,
  54531. enumerable: true
  54532. },
  54533. currentTech: {
  54534. get: () => this.tech_.name_,
  54535. enumerable: true
  54536. },
  54537. duration: {
  54538. get: () => this.tech_.duration(),
  54539. enumerable: true
  54540. },
  54541. main: {
  54542. get: () => this.playlists.main,
  54543. enumerable: true
  54544. },
  54545. playerDimensions: {
  54546. get: () => this.tech_.currentDimensions(),
  54547. enumerable: true
  54548. },
  54549. seekable: {
  54550. get: () => timeRangesToArray(this.tech_.seekable()),
  54551. enumerable: true
  54552. },
  54553. timestamp: {
  54554. get: () => Date.now(),
  54555. enumerable: true
  54556. },
  54557. videoPlaybackQuality: {
  54558. get: () => this.tech_.getVideoPlaybackQuality(),
  54559. enumerable: true
  54560. }
  54561. });
  54562. this.tech_.one('canplay', this.playlistController_.setupFirstPlay.bind(this.playlistController_));
  54563. this.tech_.on('bandwidthupdate', () => {
  54564. if (this.options_.useBandwidthFromLocalStorage) {
  54565. updateVhsLocalStorage({
  54566. bandwidth: this.bandwidth,
  54567. throughput: Math.round(this.throughput)
  54568. });
  54569. }
  54570. });
  54571. this.playlistController_.on('selectedinitialmedia', () => {
  54572. // Add the manual rendition mix-in to VhsHandler
  54573. renditionSelectionMixin(this);
  54574. });
  54575. this.playlistController_.sourceUpdater_.on('createdsourcebuffers', () => {
  54576. this.setupEme_();
  54577. }); // the bandwidth of the primary segment loader is our best
  54578. // estimate of overall bandwidth
  54579. this.on(this.playlistController_, 'progress', function () {
  54580. this.tech_.trigger('progress');
  54581. }); // In the live case, we need to ignore the very first `seeking` event since
  54582. // that will be the result of the seek-to-live behavior
  54583. this.on(this.playlistController_, 'firstplay', function () {
  54584. this.ignoreNextSeekingEvent_ = true;
  54585. });
  54586. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  54587. // this can occur if someone sets the src in player.ready(), for instance
  54588. if (!this.tech_.el()) {
  54589. return;
  54590. }
  54591. this.mediaSourceUrl_ = window.URL.createObjectURL(this.playlistController_.mediaSource);
  54592. this.tech_.src(this.mediaSourceUrl_);
  54593. }
  54594. createKeySessions_() {
  54595. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  54596. this.logger_('waiting for EME key session creation');
  54597. waitForKeySessionCreation({
  54598. player: this.player_,
  54599. sourceKeySystems: this.source_.keySystems,
  54600. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  54601. mainPlaylists: this.playlists.main.playlists
  54602. }).then(() => {
  54603. this.logger_('created EME key session');
  54604. this.playlistController_.sourceUpdater_.initializedEme();
  54605. }).catch(err => {
  54606. this.logger_('error while creating EME key session', err);
  54607. this.player_.error({
  54608. message: 'Failed to initialize media keys for EME',
  54609. code: 3
  54610. });
  54611. });
  54612. }
  54613. handleWaitingForKey_() {
  54614. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  54615. // the key is in the manifest. While this should've happened on initial source load, it
  54616. // may happen again in live streams where the keys change, and the manifest info
  54617. // reflects the update.
  54618. //
  54619. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  54620. // already requested keys for, we don't have to worry about this generating extraneous
  54621. // requests.
  54622. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  54623. this.createKeySessions_();
  54624. }
  54625. /**
  54626. * If necessary and EME is available, sets up EME options and waits for key session
  54627. * creation.
  54628. *
  54629. * This function also updates the source updater so taht it can be used, as for some
  54630. * browsers, EME must be configured before content is appended (if appending unencrypted
  54631. * content before encrypted content).
  54632. */
  54633. setupEme_() {
  54634. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  54635. const didSetupEmeOptions = setupEmeOptions({
  54636. player: this.player_,
  54637. sourceKeySystems: this.source_.keySystems,
  54638. media: this.playlists.media(),
  54639. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  54640. });
  54641. this.player_.tech_.on('keystatuschange', e => {
  54642. if (e.status !== 'output-restricted') {
  54643. return;
  54644. }
  54645. const mainPlaylist = this.playlistController_.main();
  54646. if (!mainPlaylist || !mainPlaylist.playlists) {
  54647. return;
  54648. }
  54649. const excludedHDPlaylists = []; // Assume all HD streams are unplayable and exclude them from ABR selection
  54650. mainPlaylist.playlists.forEach(playlist => {
  54651. if (playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height >= 720) {
  54652. if (!playlist.excludeUntil || playlist.excludeUntil < Infinity) {
  54653. playlist.excludeUntil = Infinity;
  54654. excludedHDPlaylists.push(playlist);
  54655. }
  54656. }
  54657. });
  54658. if (excludedHDPlaylists.length) {
  54659. videojs.log.warn('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.', ...excludedHDPlaylists); // Clear the buffer before switching playlists, since it may already contain unplayable segments
  54660. this.playlistController_.fastQualityChange_();
  54661. }
  54662. });
  54663. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  54664. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_); // In IE11 this is too early to initialize media keys, and IE11 does not support
  54665. // promises.
  54666. if (videojs.browser.IE_VERSION === 11 || !didSetupEmeOptions) {
  54667. // If EME options were not set up, we've done all we could to initialize EME.
  54668. this.playlistController_.sourceUpdater_.initializedEme();
  54669. return;
  54670. }
  54671. this.createKeySessions_();
  54672. }
  54673. /**
  54674. * Initializes the quality levels and sets listeners to update them.
  54675. *
  54676. * @method setupQualityLevels_
  54677. * @private
  54678. */
  54679. setupQualityLevels_() {
  54680. const player = videojs.players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  54681. // or qualityLevels_ listeners have already been setup, do nothing.
  54682. if (!player || !player.qualityLevels || this.qualityLevels_) {
  54683. return;
  54684. }
  54685. this.qualityLevels_ = player.qualityLevels();
  54686. this.playlistController_.on('selectedinitialmedia', () => {
  54687. handleVhsLoadedMetadata(this.qualityLevels_, this);
  54688. });
  54689. this.playlists.on('mediachange', () => {
  54690. handleVhsMediaChange(this.qualityLevels_, this.playlists);
  54691. });
  54692. }
  54693. /**
  54694. * return the version
  54695. */
  54696. static version() {
  54697. return {
  54698. '@videojs/http-streaming': version$4,
  54699. 'mux.js': version$3,
  54700. 'mpd-parser': version$2,
  54701. 'm3u8-parser': version$1,
  54702. 'aes-decrypter': version
  54703. };
  54704. }
  54705. /**
  54706. * return the version
  54707. */
  54708. version() {
  54709. return this.constructor.version();
  54710. }
  54711. canChangeType() {
  54712. return SourceUpdater.canChangeType();
  54713. }
  54714. /**
  54715. * Begin playing the video.
  54716. */
  54717. play() {
  54718. this.playlistController_.play();
  54719. }
  54720. /**
  54721. * a wrapper around the function in PlaylistController
  54722. */
  54723. setCurrentTime(currentTime) {
  54724. this.playlistController_.setCurrentTime(currentTime);
  54725. }
  54726. /**
  54727. * a wrapper around the function in PlaylistController
  54728. */
  54729. duration() {
  54730. return this.playlistController_.duration();
  54731. }
  54732. /**
  54733. * a wrapper around the function in PlaylistController
  54734. */
  54735. seekable() {
  54736. return this.playlistController_.seekable();
  54737. }
  54738. /**
  54739. * Abort all outstanding work and cleanup.
  54740. */
  54741. dispose() {
  54742. if (this.playbackWatcher_) {
  54743. this.playbackWatcher_.dispose();
  54744. }
  54745. if (this.playlistController_) {
  54746. this.playlistController_.dispose();
  54747. }
  54748. if (this.qualityLevels_) {
  54749. this.qualityLevels_.dispose();
  54750. }
  54751. if (this.tech_ && this.tech_.vhs) {
  54752. delete this.tech_.vhs;
  54753. }
  54754. if (this.mediaSourceUrl_ && window.URL.revokeObjectURL) {
  54755. window.URL.revokeObjectURL(this.mediaSourceUrl_);
  54756. this.mediaSourceUrl_ = null;
  54757. }
  54758. if (this.tech_) {
  54759. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  54760. }
  54761. super.dispose();
  54762. }
  54763. convertToProgramTime(time, callback) {
  54764. return getProgramTime({
  54765. playlist: this.playlistController_.media(),
  54766. time,
  54767. callback
  54768. });
  54769. } // the player must be playing before calling this
  54770. seekToProgramTime(programTime, callback, pauseAfterSeek = true, retryCount = 2) {
  54771. return seekToProgramTime({
  54772. programTime,
  54773. playlist: this.playlistController_.media(),
  54774. retryCount,
  54775. pauseAfterSeek,
  54776. seekTo: this.options_.seekTo,
  54777. tech: this.options_.tech,
  54778. callback
  54779. });
  54780. }
  54781. }
  54782. /**
  54783. * The Source Handler object, which informs video.js what additional
  54784. * MIME types are supported and sets up playback. It is registered
  54785. * automatically to the appropriate tech based on the capabilities of
  54786. * the browser it is running in. It is not necessary to use or modify
  54787. * this object in normal usage.
  54788. */
  54789. const VhsSourceHandler = {
  54790. name: 'videojs-http-streaming',
  54791. VERSION: version$4,
  54792. canHandleSource(srcObj, options = {}) {
  54793. const localOptions = merge(videojs.options, options);
  54794. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  54795. },
  54796. handleSource(source, tech, options = {}) {
  54797. const localOptions = merge(videojs.options, options);
  54798. tech.vhs = new VhsHandler(source, tech, localOptions);
  54799. tech.vhs.xhr = xhrFactory();
  54800. tech.vhs.src(source.src, source.type);
  54801. return tech.vhs;
  54802. },
  54803. canPlayType(type, options) {
  54804. const simpleType = simpleTypeFromSourceType(type);
  54805. if (!simpleType) {
  54806. return '';
  54807. }
  54808. const overrideNative = VhsSourceHandler.getOverrideNative(options);
  54809. const supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  54810. const canUseMsePlayback = !supportsTypeNatively || overrideNative;
  54811. return canUseMsePlayback ? 'maybe' : '';
  54812. },
  54813. getOverrideNative(options = {}) {
  54814. const {
  54815. vhs = {}
  54816. } = options;
  54817. const defaultOverrideNative = !(videojs.browser.IS_ANY_SAFARI || videojs.browser.IS_IOS);
  54818. const {
  54819. overrideNative = defaultOverrideNative
  54820. } = vhs;
  54821. return overrideNative;
  54822. }
  54823. };
  54824. /**
  54825. * Check to see if the native MediaSource object exists and supports
  54826. * an MP4 container with both H.264 video and AAC-LC audio.
  54827. *
  54828. * @return {boolean} if native media sources are supported
  54829. */
  54830. const supportsNativeMediaSources = () => {
  54831. return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  54832. }; // register source handlers with the appropriate techs
  54833. if (supportsNativeMediaSources()) {
  54834. videojs.getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  54835. }
  54836. videojs.VhsHandler = VhsHandler;
  54837. videojs.VhsSourceHandler = VhsSourceHandler;
  54838. videojs.Vhs = Vhs;
  54839. if (!videojs.use) {
  54840. videojs.registerComponent('Vhs', Vhs);
  54841. }
  54842. videojs.options.vhs = videojs.options.vhs || {};
  54843. if (!videojs.getPlugin || !videojs.getPlugin('reloadSourceOnError')) {
  54844. videojs.registerPlugin('reloadSourceOnError', reloadSourceOnError);
  54845. }
  54846. return videojs;
  54847. }));