video.es.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785
  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. import window$1 from 'global/window';
  13. import document from 'global/document';
  14. import keycode from 'keycode';
  15. import safeParseTuple from 'safe-json-parse/tuple';
  16. import XHR from '@videojs/xhr';
  17. import vtt from 'videojs-vtt.js';
  18. import _resolveUrl from '@videojs/vhs-utils/es/resolve-url.js';
  19. import _extends from '@babel/runtime/helpers/extends';
  20. import { Parser } from 'm3u8-parser';
  21. import { DEFAULT_VIDEO_CODEC, DEFAULT_AUDIO_CODEC, parseCodecs, muxerSupportsCodec, browserSupportsCodec, translateLegacyCodec, codecsFromDefault, isAudioCodec, getMimeForCodec } from '@videojs/vhs-utils/es/codecs.js';
  22. import { simpleTypeFromSourceType } from '@videojs/vhs-utils/es/media-types.js';
  23. import { isArrayBufferView, concatTypedArrays, stringToBytes, toUint8 } from '@videojs/vhs-utils/es/byte-helpers';
  24. import { generateSidxKey, parseUTCTiming, parse, addSidxSegmentsToPlaylist } from 'mpd-parser';
  25. import parseSidx from 'mux.js/lib/tools/parse-sidx';
  26. import { getId3Offset } from '@videojs/vhs-utils/es/id3-helpers';
  27. import { detectContainerForBytes, isLikelyFmp4MediaSegment } from '@videojs/vhs-utils/es/containers';
  28. import { ONE_SECOND_IN_TS } from 'mux.js/lib/utils/clock';
  29. var version$6 = "8.3.0";
  30. /**
  31. * An Object that contains lifecycle hooks as keys which point to an array
  32. * of functions that are run when a lifecycle is triggered
  33. *
  34. * @private
  35. */
  36. const hooks_ = {};
  37. /**
  38. * Get a list of hooks for a specific lifecycle
  39. *
  40. * @param {string} type
  41. * the lifecycle to get hooks from
  42. *
  43. * @param {Function|Function[]} [fn]
  44. * Optionally add a hook (or hooks) to the lifecycle that your are getting.
  45. *
  46. * @return {Array}
  47. * an array of hooks, or an empty array if there are none.
  48. */
  49. const hooks = function (type, fn) {
  50. hooks_[type] = hooks_[type] || [];
  51. if (fn) {
  52. hooks_[type] = hooks_[type].concat(fn);
  53. }
  54. return hooks_[type];
  55. };
  56. /**
  57. * Add a function hook to a specific videojs lifecycle.
  58. *
  59. * @param {string} type
  60. * the lifecycle to hook the function to.
  61. *
  62. * @param {Function|Function[]}
  63. * The function or array of functions to attach.
  64. */
  65. const hook = function (type, fn) {
  66. hooks(type, fn);
  67. };
  68. /**
  69. * Remove a hook from a specific videojs lifecycle.
  70. *
  71. * @param {string} type
  72. * the lifecycle that the function hooked to
  73. *
  74. * @param {Function} fn
  75. * The hooked function to remove
  76. *
  77. * @return {boolean}
  78. * The function that was removed or undef
  79. */
  80. const removeHook = function (type, fn) {
  81. const index = hooks(type).indexOf(fn);
  82. if (index <= -1) {
  83. return false;
  84. }
  85. hooks_[type] = hooks_[type].slice();
  86. hooks_[type].splice(index, 1);
  87. return true;
  88. };
  89. /**
  90. * Add a function hook that will only run once to a specific videojs lifecycle.
  91. *
  92. * @param {string} type
  93. * the lifecycle to hook the function to.
  94. *
  95. * @param {Function|Function[]}
  96. * The function or array of functions to attach.
  97. */
  98. const hookOnce = function (type, fn) {
  99. hooks(type, [].concat(fn).map(original => {
  100. const wrapper = (...args) => {
  101. removeHook(type, wrapper);
  102. return original(...args);
  103. };
  104. return wrapper;
  105. }));
  106. };
  107. /**
  108. * @file fullscreen-api.js
  109. * @module fullscreen-api
  110. */
  111. /**
  112. * Store the browser-specific methods for the fullscreen API.
  113. *
  114. * @type {Object}
  115. * @see [Specification]{@link https://fullscreen.spec.whatwg.org}
  116. * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}
  117. */
  118. const FullscreenApi = {
  119. prefixed: true
  120. };
  121. // browser API methods
  122. const apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror', 'fullscreen'],
  123. // WebKit
  124. ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror', '-webkit-full-screen'],
  125. // Mozilla
  126. ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror', '-moz-full-screen'],
  127. // Microsoft
  128. ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError', '-ms-fullscreen']];
  129. const specApi = apiMap[0];
  130. let browserApi;
  131. // determine the supported set of functions
  132. for (let i = 0; i < apiMap.length; i++) {
  133. // check for exitFullscreen function
  134. if (apiMap[i][1] in document) {
  135. browserApi = apiMap[i];
  136. break;
  137. }
  138. }
  139. // map the browser API names to the spec API names
  140. if (browserApi) {
  141. for (let i = 0; i < browserApi.length; i++) {
  142. FullscreenApi[specApi[i]] = browserApi[i];
  143. }
  144. FullscreenApi.prefixed = browserApi[0] !== specApi[0];
  145. }
  146. /**
  147. * @file create-logger.js
  148. * @module create-logger
  149. */
  150. // This is the private tracking variable for the logging history.
  151. let history = [];
  152. /**
  153. * Log messages to the console and history based on the type of message
  154. *
  155. * @private
  156. * @param {string} type
  157. * The name of the console method to use.
  158. *
  159. * @param {Array} args
  160. * The arguments to be passed to the matching console method.
  161. */
  162. const LogByTypeFactory = (name, log) => (type, level, args) => {
  163. const lvl = log.levels[level];
  164. const lvlRegExp = new RegExp(`^(${lvl})$`);
  165. if (type !== 'log') {
  166. // Add the type to the front of the message when it's not "log".
  167. args.unshift(type.toUpperCase() + ':');
  168. }
  169. // Add console prefix after adding to history.
  170. args.unshift(name + ':');
  171. // Add a clone of the args at this point to history.
  172. if (history) {
  173. history.push([].concat(args));
  174. // only store 1000 history entries
  175. const splice = history.length - 1000;
  176. history.splice(0, splice > 0 ? splice : 0);
  177. }
  178. // If there's no console then don't try to output messages, but they will
  179. // still be stored in history.
  180. if (!window$1.console) {
  181. return;
  182. }
  183. // Was setting these once outside of this function, but containing them
  184. // in the function makes it easier to test cases where console doesn't exist
  185. // when the module is executed.
  186. let fn = window$1.console[type];
  187. if (!fn && type === 'debug') {
  188. // Certain browsers don't have support for console.debug. For those, we
  189. // should default to the closest comparable log.
  190. fn = window$1.console.info || window$1.console.log;
  191. }
  192. // Bail out if there's no console or if this type is not allowed by the
  193. // current logging level.
  194. if (!fn || !lvl || !lvlRegExp.test(type)) {
  195. return;
  196. }
  197. fn[Array.isArray(args) ? 'apply' : 'call'](window$1.console, args);
  198. };
  199. function createLogger$1(name) {
  200. // This is the private tracking variable for logging level.
  201. let level = 'info';
  202. // the curried logByType bound to the specific log and history
  203. let logByType;
  204. /**
  205. * Logs plain debug messages. Similar to `console.log`.
  206. *
  207. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  208. * of our JSDoc template, we cannot properly document this as both a function
  209. * and a namespace, so its function signature is documented here.
  210. *
  211. * #### Arguments
  212. * ##### *args
  213. * *[]
  214. *
  215. * Any combination of values that could be passed to `console.log()`.
  216. *
  217. * #### Return Value
  218. *
  219. * `undefined`
  220. *
  221. * @namespace
  222. * @param {...*} args
  223. * One or more messages or objects that should be logged.
  224. */
  225. const log = function (...args) {
  226. logByType('log', level, args);
  227. };
  228. // This is the logByType helper that the logging methods below use
  229. logByType = LogByTypeFactory(name, log);
  230. /**
  231. * Create a new sublogger which chains the old name to the new name.
  232. *
  233. * For example, doing `videojs.log.createLogger('player')` and then using that logger will log the following:
  234. * ```js
  235. * mylogger('foo');
  236. * // > VIDEOJS: player: foo
  237. * ```
  238. *
  239. * @param {string} name
  240. * The name to add call the new logger
  241. * @return {Object}
  242. */
  243. log.createLogger = subname => createLogger$1(name + ': ' + subname);
  244. /**
  245. * Enumeration of available logging levels, where the keys are the level names
  246. * and the values are `|`-separated strings containing logging methods allowed
  247. * in that logging level. These strings are used to create a regular expression
  248. * matching the function name being called.
  249. *
  250. * Levels provided by Video.js are:
  251. *
  252. * - `off`: Matches no calls. Any value that can be cast to `false` will have
  253. * this effect. The most restrictive.
  254. * - `all`: Matches only Video.js-provided functions (`debug`, `log`,
  255. * `log.warn`, and `log.error`).
  256. * - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls.
  257. * - `info` (default): Matches `log`, `log.warn`, and `log.error` calls.
  258. * - `warn`: Matches `log.warn` and `log.error` calls.
  259. * - `error`: Matches only `log.error` calls.
  260. *
  261. * @type {Object}
  262. */
  263. log.levels = {
  264. all: 'debug|log|warn|error',
  265. off: '',
  266. debug: 'debug|log|warn|error',
  267. info: 'log|warn|error',
  268. warn: 'warn|error',
  269. error: 'error',
  270. DEFAULT: level
  271. };
  272. /**
  273. * Get or set the current logging level.
  274. *
  275. * If a string matching a key from {@link module:log.levels} is provided, acts
  276. * as a setter.
  277. *
  278. * @param {string} [lvl]
  279. * Pass a valid level to set a new logging level.
  280. *
  281. * @return {string}
  282. * The current logging level.
  283. */
  284. log.level = lvl => {
  285. if (typeof lvl === 'string') {
  286. if (!log.levels.hasOwnProperty(lvl)) {
  287. throw new Error(`"${lvl}" in not a valid log level`);
  288. }
  289. level = lvl;
  290. }
  291. return level;
  292. };
  293. /**
  294. * Returns an array containing everything that has been logged to the history.
  295. *
  296. * This array is a shallow clone of the internal history record. However, its
  297. * contents are _not_ cloned; so, mutating objects inside this array will
  298. * mutate them in history.
  299. *
  300. * @return {Array}
  301. */
  302. log.history = () => history ? [].concat(history) : [];
  303. /**
  304. * Allows you to filter the history by the given logger name
  305. *
  306. * @param {string} fname
  307. * The name to filter by
  308. *
  309. * @return {Array}
  310. * The filtered list to return
  311. */
  312. log.history.filter = fname => {
  313. return (history || []).filter(historyItem => {
  314. // if the first item in each historyItem includes `fname`, then it's a match
  315. return new RegExp(`.*${fname}.*`).test(historyItem[0]);
  316. });
  317. };
  318. /**
  319. * Clears the internal history tracking, but does not prevent further history
  320. * tracking.
  321. */
  322. log.history.clear = () => {
  323. if (history) {
  324. history.length = 0;
  325. }
  326. };
  327. /**
  328. * Disable history tracking if it is currently enabled.
  329. */
  330. log.history.disable = () => {
  331. if (history !== null) {
  332. history.length = 0;
  333. history = null;
  334. }
  335. };
  336. /**
  337. * Enable history tracking if it is currently disabled.
  338. */
  339. log.history.enable = () => {
  340. if (history === null) {
  341. history = [];
  342. }
  343. };
  344. /**
  345. * Logs error messages. Similar to `console.error`.
  346. *
  347. * @param {...*} args
  348. * One or more messages or objects that should be logged as an error
  349. */
  350. log.error = (...args) => logByType('error', level, args);
  351. /**
  352. * Logs warning messages. Similar to `console.warn`.
  353. *
  354. * @param {...*} args
  355. * One or more messages or objects that should be logged as a warning.
  356. */
  357. log.warn = (...args) => logByType('warn', level, args);
  358. /**
  359. * Logs debug messages. Similar to `console.debug`, but may also act as a comparable
  360. * log if `console.debug` is not available
  361. *
  362. * @param {...*} args
  363. * One or more messages or objects that should be logged as debug.
  364. */
  365. log.debug = (...args) => logByType('debug', level, args);
  366. return log;
  367. }
  368. /**
  369. * @file log.js
  370. * @module log
  371. */
  372. const log$1 = createLogger$1('VIDEOJS');
  373. const createLogger = log$1.createLogger;
  374. /**
  375. * @file obj.js
  376. * @module obj
  377. */
  378. /**
  379. * @callback obj:EachCallback
  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. /**
  388. * @callback obj:ReduceCallback
  389. *
  390. * @param {*} accum
  391. * The value that is accumulating over the reduce loop.
  392. *
  393. * @param {*} value
  394. * The current key for the object that is being iterated over.
  395. *
  396. * @param {string} key
  397. * The current key-value for object that is being iterated over
  398. *
  399. * @return {*}
  400. * The new accumulated value.
  401. */
  402. const toString = Object.prototype.toString;
  403. /**
  404. * Get the keys of an Object
  405. *
  406. * @param {Object}
  407. * The Object to get the keys from
  408. *
  409. * @return {string[]}
  410. * An array of the keys from the object. Returns an empty array if the
  411. * object passed in was invalid or had no keys.
  412. *
  413. * @private
  414. */
  415. const keys = function (object) {
  416. return isObject(object) ? Object.keys(object) : [];
  417. };
  418. /**
  419. * Array-like iteration for objects.
  420. *
  421. * @param {Object} object
  422. * The object to iterate over
  423. *
  424. * @param {obj:EachCallback} fn
  425. * The callback function which is called for each key in the object.
  426. */
  427. function each(object, fn) {
  428. keys(object).forEach(key => fn(object[key], key));
  429. }
  430. /**
  431. * Array-like reduce for objects.
  432. *
  433. * @param {Object} object
  434. * The Object that you want to reduce.
  435. *
  436. * @param {Function} fn
  437. * A callback function which is called for each key in the object. It
  438. * receives the accumulated value and the per-iteration value and key
  439. * as arguments.
  440. *
  441. * @param {*} [initial = 0]
  442. * Starting value
  443. *
  444. * @return {*}
  445. * The final accumulated value.
  446. */
  447. function reduce(object, fn, initial = 0) {
  448. return keys(object).reduce((accum, key) => fn(accum, object[key], key), initial);
  449. }
  450. /**
  451. * Returns whether a value is an object of any kind - including DOM nodes,
  452. * arrays, regular expressions, etc. Not functions, though.
  453. *
  454. * This avoids the gotcha where using `typeof` on a `null` value
  455. * results in `'object'`.
  456. *
  457. * @param {Object} value
  458. * @return {boolean}
  459. */
  460. function isObject(value) {
  461. return !!value && typeof value === 'object';
  462. }
  463. /**
  464. * Returns whether an object appears to be a "plain" object - that is, a
  465. * direct instance of `Object`.
  466. *
  467. * @param {Object} value
  468. * @return {boolean}
  469. */
  470. function isPlain(value) {
  471. return isObject(value) && toString.call(value) === '[object Object]' && value.constructor === Object;
  472. }
  473. /**
  474. * Merge two objects recursively.
  475. *
  476. * Performs a deep merge like
  477. * {@link https://lodash.com/docs/4.17.10#merge|lodash.merge}, but only merges
  478. * plain objects (not arrays, elements, or anything else).
  479. *
  480. * Non-plain object values will be copied directly from the right-most
  481. * argument.
  482. *
  483. * @param {Object[]} sources
  484. * One or more objects to merge into a new object.
  485. *
  486. * @return {Object}
  487. * A new object that is the merged result of all sources.
  488. */
  489. function merge$1(...sources) {
  490. const result = {};
  491. sources.forEach(source => {
  492. if (!source) {
  493. return;
  494. }
  495. each(source, (value, key) => {
  496. if (!isPlain(value)) {
  497. result[key] = value;
  498. return;
  499. }
  500. if (!isPlain(result[key])) {
  501. result[key] = {};
  502. }
  503. result[key] = merge$1(result[key], value);
  504. });
  505. });
  506. return result;
  507. }
  508. /**
  509. * Object.defineProperty but "lazy", which means that the value is only set after
  510. * it is retrieved the first time, rather than being set right away.
  511. *
  512. * @param {Object} obj the object to set the property on
  513. * @param {string} key the key for the property to set
  514. * @param {Function} getValue the function used to get the value when it is needed.
  515. * @param {boolean} setter whether a setter should be allowed or not
  516. */
  517. function defineLazyProperty(obj, key, getValue, setter = true) {
  518. const set = value => Object.defineProperty(obj, key, {
  519. value,
  520. enumerable: true,
  521. writable: true
  522. });
  523. const options = {
  524. configurable: true,
  525. enumerable: true,
  526. get() {
  527. const value = getValue();
  528. set(value);
  529. return value;
  530. }
  531. };
  532. if (setter) {
  533. options.set = set;
  534. }
  535. return Object.defineProperty(obj, key, options);
  536. }
  537. var Obj = /*#__PURE__*/Object.freeze({
  538. __proto__: null,
  539. each: each,
  540. reduce: reduce,
  541. isObject: isObject,
  542. isPlain: isPlain,
  543. merge: merge$1,
  544. defineLazyProperty: defineLazyProperty
  545. });
  546. /**
  547. * @file browser.js
  548. * @module browser
  549. */
  550. /**
  551. * Whether or not this device is an iPod.
  552. *
  553. * @static
  554. * @type {Boolean}
  555. */
  556. let IS_IPOD = false;
  557. /**
  558. * The detected iOS version - or `null`.
  559. *
  560. * @static
  561. * @type {string|null}
  562. */
  563. let IOS_VERSION = null;
  564. /**
  565. * Whether or not this is an Android device.
  566. *
  567. * @static
  568. * @type {Boolean}
  569. */
  570. let IS_ANDROID = false;
  571. /**
  572. * The detected Android version - or `null` if not Android or indeterminable.
  573. *
  574. * @static
  575. * @type {number|string|null}
  576. */
  577. let ANDROID_VERSION;
  578. /**
  579. * Whether or not this is Mozilla Firefox.
  580. *
  581. * @static
  582. * @type {Boolean}
  583. */
  584. let IS_FIREFOX = false;
  585. /**
  586. * Whether or not this is Microsoft Edge.
  587. *
  588. * @static
  589. * @type {Boolean}
  590. */
  591. let IS_EDGE = false;
  592. /**
  593. * Whether or not this is any Chromium Browser
  594. *
  595. * @static
  596. * @type {Boolean}
  597. */
  598. let IS_CHROMIUM = false;
  599. /**
  600. * Whether or not this is any Chromium browser that is not Edge.
  601. *
  602. * This will also be `true` for Chrome on iOS, which will have different support
  603. * as it is actually Safari under the hood.
  604. *
  605. * Deprecated, as the behaviour to not match Edge was to prevent Legacy Edge's UA matching.
  606. * IS_CHROMIUM should be used instead.
  607. * "Chromium but not Edge" could be explicitly tested with IS_CHROMIUM && !IS_EDGE
  608. *
  609. * @static
  610. * @deprecated
  611. * @type {Boolean}
  612. */
  613. let IS_CHROME = false;
  614. /**
  615. * The detected Chromium version - or `null`.
  616. *
  617. * @static
  618. * @type {number|null}
  619. */
  620. let CHROMIUM_VERSION = null;
  621. /**
  622. * The detected Google Chrome version - or `null`.
  623. * This has always been the _Chromium_ version, i.e. would return on Chromium Edge.
  624. * Deprecated, use CHROMIUM_VERSION instead.
  625. *
  626. * @static
  627. * @deprecated
  628. * @type {number|null}
  629. */
  630. let CHROME_VERSION = null;
  631. /**
  632. * The detected Internet Explorer version - or `null`.
  633. *
  634. * @static
  635. * @deprecated
  636. * @type {number|null}
  637. */
  638. let IE_VERSION = null;
  639. /**
  640. * Whether or not this is desktop Safari.
  641. *
  642. * @static
  643. * @type {Boolean}
  644. */
  645. let IS_SAFARI = false;
  646. /**
  647. * Whether or not this is a Windows machine.
  648. *
  649. * @static
  650. * @type {Boolean}
  651. */
  652. let IS_WINDOWS = false;
  653. /**
  654. * Whether or not this device is an iPad.
  655. *
  656. * @static
  657. * @type {Boolean}
  658. */
  659. let IS_IPAD = false;
  660. /**
  661. * Whether or not this device is an iPhone.
  662. *
  663. * @static
  664. * @type {Boolean}
  665. */
  666. // The Facebook app's UIWebView identifies as both an iPhone and iPad, so
  667. // to identify iPhones, we need to exclude iPads.
  668. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
  669. let IS_IPHONE = false;
  670. /**
  671. * Whether or not this device is touch-enabled.
  672. *
  673. * @static
  674. * @const
  675. * @type {Boolean}
  676. */
  677. const TOUCH_ENABLED = Boolean(isReal() && ('ontouchstart' in window$1 || window$1.navigator.maxTouchPoints || window$1.DocumentTouch && window$1.document instanceof window$1.DocumentTouch));
  678. const UAD = window$1.navigator && window$1.navigator.userAgentData;
  679. if (UAD) {
  680. // If userAgentData is present, use it instead of userAgent to avoid warnings
  681. // Currently only implemented on Chromium
  682. // userAgentData does not expose Android version, so ANDROID_VERSION remains `null`
  683. IS_ANDROID = UAD.platform === 'Android';
  684. IS_EDGE = Boolean(UAD.brands.find(b => b.brand === 'Microsoft Edge'));
  685. IS_CHROMIUM = Boolean(UAD.brands.find(b => b.brand === 'Chromium'));
  686. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  687. CHROMIUM_VERSION = CHROME_VERSION = (UAD.brands.find(b => b.brand === 'Chromium') || {}).version || null;
  688. IS_WINDOWS = UAD.platform === 'Windows';
  689. }
  690. // If the browser is not Chromium, either userAgentData is not present which could be an old Chromium browser,
  691. // or it's a browser that has added userAgentData since that we don't have tests for yet. In either case,
  692. // the checks need to be made agiainst the regular userAgent string.
  693. if (!IS_CHROMIUM) {
  694. const USER_AGENT = window$1.navigator && window$1.navigator.userAgent || '';
  695. IS_IPOD = /iPod/i.test(USER_AGENT);
  696. IOS_VERSION = function () {
  697. const match = USER_AGENT.match(/OS (\d+)_/i);
  698. if (match && match[1]) {
  699. return match[1];
  700. }
  701. return null;
  702. }();
  703. IS_ANDROID = /Android/i.test(USER_AGENT);
  704. ANDROID_VERSION = function () {
  705. // This matches Android Major.Minor.Patch versions
  706. // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
  707. const match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
  708. if (!match) {
  709. return null;
  710. }
  711. const major = match[1] && parseFloat(match[1]);
  712. const minor = match[2] && parseFloat(match[2]);
  713. if (major && minor) {
  714. return parseFloat(match[1] + '.' + match[2]);
  715. } else if (major) {
  716. return major;
  717. }
  718. return null;
  719. }();
  720. IS_FIREFOX = /Firefox/i.test(USER_AGENT);
  721. IS_EDGE = /Edg/i.test(USER_AGENT);
  722. IS_CHROMIUM = /Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT);
  723. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  724. CHROMIUM_VERSION = CHROME_VERSION = function () {
  725. const match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
  726. if (match && match[2]) {
  727. return parseFloat(match[2]);
  728. }
  729. return null;
  730. }();
  731. IE_VERSION = function () {
  732. const result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT);
  733. let version = result && parseFloat(result[1]);
  734. if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) {
  735. // IE 11 has a different user agent string than other IE versions
  736. version = 11.0;
  737. }
  738. return version;
  739. }();
  740. IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE;
  741. IS_WINDOWS = /Windows/i.test(USER_AGENT);
  742. IS_IPAD = /iPad/i.test(USER_AGENT) || IS_SAFARI && TOUCH_ENABLED && !/iPhone/i.test(USER_AGENT);
  743. IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD;
  744. }
  745. /**
  746. * Whether or not this is an iOS device.
  747. *
  748. * @static
  749. * @const
  750. * @type {Boolean}
  751. */
  752. const IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
  753. /**
  754. * Whether or not this is any flavor of Safari - including iOS.
  755. *
  756. * @static
  757. * @const
  758. * @type {Boolean}
  759. */
  760. const IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;
  761. var browser = /*#__PURE__*/Object.freeze({
  762. __proto__: null,
  763. get IS_IPOD () { return IS_IPOD; },
  764. get IOS_VERSION () { return IOS_VERSION; },
  765. get IS_ANDROID () { return IS_ANDROID; },
  766. get ANDROID_VERSION () { return ANDROID_VERSION; },
  767. get IS_FIREFOX () { return IS_FIREFOX; },
  768. get IS_EDGE () { return IS_EDGE; },
  769. get IS_CHROMIUM () { return IS_CHROMIUM; },
  770. get IS_CHROME () { return IS_CHROME; },
  771. get CHROMIUM_VERSION () { return CHROMIUM_VERSION; },
  772. get CHROME_VERSION () { return CHROME_VERSION; },
  773. get IE_VERSION () { return IE_VERSION; },
  774. get IS_SAFARI () { return IS_SAFARI; },
  775. get IS_WINDOWS () { return IS_WINDOWS; },
  776. get IS_IPAD () { return IS_IPAD; },
  777. get IS_IPHONE () { return IS_IPHONE; },
  778. TOUCH_ENABLED: TOUCH_ENABLED,
  779. IS_IOS: IS_IOS,
  780. IS_ANY_SAFARI: IS_ANY_SAFARI
  781. });
  782. /**
  783. * @file dom.js
  784. * @module dom
  785. */
  786. /**
  787. * Detect if a value is a string with any non-whitespace characters.
  788. *
  789. * @private
  790. * @param {string} str
  791. * The string to check
  792. *
  793. * @return {boolean}
  794. * Will be `true` if the string is non-blank, `false` otherwise.
  795. *
  796. */
  797. function isNonBlankString(str) {
  798. // we use str.trim as it will trim any whitespace characters
  799. // from the front or back of non-whitespace characters. aka
  800. // Any string that contains non-whitespace characters will
  801. // still contain them after `trim` but whitespace only strings
  802. // will have a length of 0, failing this check.
  803. return typeof str === 'string' && Boolean(str.trim());
  804. }
  805. /**
  806. * Throws an error if the passed string has whitespace. This is used by
  807. * class methods to be relatively consistent with the classList API.
  808. *
  809. * @private
  810. * @param {string} str
  811. * The string to check for whitespace.
  812. *
  813. * @throws {Error}
  814. * Throws an error if there is whitespace in the string.
  815. */
  816. function throwIfWhitespace(str) {
  817. // str.indexOf instead of regex because str.indexOf is faster performance wise.
  818. if (str.indexOf(' ') >= 0) {
  819. throw new Error('class has illegal whitespace characters');
  820. }
  821. }
  822. /**
  823. * Whether the current DOM interface appears to be real (i.e. not simulated).
  824. *
  825. * @return {boolean}
  826. * Will be `true` if the DOM appears to be real, `false` otherwise.
  827. */
  828. function isReal() {
  829. // Both document and window will never be undefined thanks to `global`.
  830. return document === window$1.document;
  831. }
  832. /**
  833. * Determines, via duck typing, whether or not a value is a DOM element.
  834. *
  835. * @param {*} value
  836. * The value to check.
  837. *
  838. * @return {boolean}
  839. * Will be `true` if the value is a DOM element, `false` otherwise.
  840. */
  841. function isEl(value) {
  842. return isObject(value) && value.nodeType === 1;
  843. }
  844. /**
  845. * Determines if the current DOM is embedded in an iframe.
  846. *
  847. * @return {boolean}
  848. * Will be `true` if the DOM is embedded in an iframe, `false`
  849. * otherwise.
  850. */
  851. function isInFrame() {
  852. // We need a try/catch here because Safari will throw errors when attempting
  853. // to get either `parent` or `self`
  854. try {
  855. return window$1.parent !== window$1.self;
  856. } catch (x) {
  857. return true;
  858. }
  859. }
  860. /**
  861. * Creates functions to query the DOM using a given method.
  862. *
  863. * @private
  864. * @param {string} method
  865. * The method to create the query with.
  866. *
  867. * @return {Function}
  868. * The query method
  869. */
  870. function createQuerier(method) {
  871. return function (selector, context) {
  872. if (!isNonBlankString(selector)) {
  873. return document[method](null);
  874. }
  875. if (isNonBlankString(context)) {
  876. context = document.querySelector(context);
  877. }
  878. const ctx = isEl(context) ? context : document;
  879. return ctx[method] && ctx[method](selector);
  880. };
  881. }
  882. /**
  883. * Creates an element and applies properties, attributes, and inserts content.
  884. *
  885. * @param {string} [tagName='div']
  886. * Name of tag to be created.
  887. *
  888. * @param {Object} [properties={}]
  889. * Element properties to be applied.
  890. *
  891. * @param {Object} [attributes={}]
  892. * Element attributes to be applied.
  893. *
  894. * @param {ContentDescriptor} [content]
  895. * A content descriptor object.
  896. *
  897. * @return {Element}
  898. * The element that was created.
  899. */
  900. function createEl(tagName = 'div', properties = {}, attributes = {}, content) {
  901. const el = document.createElement(tagName);
  902. Object.getOwnPropertyNames(properties).forEach(function (propName) {
  903. const val = properties[propName];
  904. // Handle textContent since it's not supported everywhere and we have a
  905. // method for it.
  906. if (propName === 'textContent') {
  907. textContent(el, val);
  908. } else if (el[propName] !== val || propName === 'tabIndex') {
  909. el[propName] = val;
  910. }
  911. });
  912. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  913. el.setAttribute(attrName, attributes[attrName]);
  914. });
  915. if (content) {
  916. appendContent(el, content);
  917. }
  918. return el;
  919. }
  920. /**
  921. * Injects text into an element, replacing any existing contents entirely.
  922. *
  923. * @param {Element} el
  924. * The element to add text content into
  925. *
  926. * @param {string} text
  927. * The text content to add.
  928. *
  929. * @return {Element}
  930. * The element with added text content.
  931. */
  932. function textContent(el, text) {
  933. if (typeof el.textContent === 'undefined') {
  934. el.innerText = text;
  935. } else {
  936. el.textContent = text;
  937. }
  938. return el;
  939. }
  940. /**
  941. * Insert an element as the first child node of another
  942. *
  943. * @param {Element} child
  944. * Element to insert
  945. *
  946. * @param {Element} parent
  947. * Element to insert child into
  948. */
  949. function prependTo(child, parent) {
  950. if (parent.firstChild) {
  951. parent.insertBefore(child, parent.firstChild);
  952. } else {
  953. parent.appendChild(child);
  954. }
  955. }
  956. /**
  957. * Check if an element has a class name.
  958. *
  959. * @param {Element} element
  960. * Element to check
  961. *
  962. * @param {string} classToCheck
  963. * Class name to check for
  964. *
  965. * @return {boolean}
  966. * Will be `true` if the element has a class, `false` otherwise.
  967. *
  968. * @throws {Error}
  969. * Throws an error if `classToCheck` has white space.
  970. */
  971. function hasClass(element, classToCheck) {
  972. throwIfWhitespace(classToCheck);
  973. return element.classList.contains(classToCheck);
  974. }
  975. /**
  976. * Add a class name to an element.
  977. *
  978. * @param {Element} element
  979. * Element to add class name to.
  980. *
  981. * @param {...string} classesToAdd
  982. * One or more class name to add.
  983. *
  984. * @return {Element}
  985. * The DOM element with the added class name.
  986. */
  987. function addClass(element, ...classesToAdd) {
  988. element.classList.add(...classesToAdd.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  989. return element;
  990. }
  991. /**
  992. * Remove a class name from an element.
  993. *
  994. * @param {Element} element
  995. * Element to remove a class name from.
  996. *
  997. * @param {...string} classesToRemove
  998. * One or more class name to remove.
  999. *
  1000. * @return {Element}
  1001. * The DOM element with class name removed.
  1002. */
  1003. function removeClass(element, ...classesToRemove) {
  1004. // Protect in case the player gets disposed
  1005. if (!element) {
  1006. log$1.warn("removeClass was called with an element that doesn't exist");
  1007. return null;
  1008. }
  1009. element.classList.remove(...classesToRemove.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  1010. return element;
  1011. }
  1012. /**
  1013. * The callback definition for toggleClass.
  1014. *
  1015. * @callback module:dom~PredicateCallback
  1016. * @param {Element} element
  1017. * The DOM element of the Component.
  1018. *
  1019. * @param {string} classToToggle
  1020. * The `className` that wants to be toggled
  1021. *
  1022. * @return {boolean|undefined}
  1023. * If `true` is returned, the `classToToggle` will be added to the
  1024. * `element`. If `false`, the `classToToggle` will be removed from
  1025. * the `element`. If `undefined`, the callback will be ignored.
  1026. */
  1027. /**
  1028. * Adds or removes a class name to/from an element depending on an optional
  1029. * condition or the presence/absence of the class name.
  1030. *
  1031. * @param {Element} element
  1032. * The element to toggle a class name on.
  1033. *
  1034. * @param {string} classToToggle
  1035. * The class that should be toggled.
  1036. *
  1037. * @param {boolean|module:dom~PredicateCallback} [predicate]
  1038. * See the return value for {@link module:dom~PredicateCallback}
  1039. *
  1040. * @return {Element}
  1041. * The element with a class that has been toggled.
  1042. */
  1043. function toggleClass(element, classToToggle, predicate) {
  1044. if (typeof predicate === 'function') {
  1045. predicate = predicate(element, classToToggle);
  1046. }
  1047. if (typeof predicate !== 'boolean') {
  1048. predicate = undefined;
  1049. }
  1050. classToToggle.split(/\s+/).forEach(className => element.classList.toggle(className, predicate));
  1051. return element;
  1052. }
  1053. /**
  1054. * Apply attributes to an HTML element.
  1055. *
  1056. * @param {Element} el
  1057. * Element to add attributes to.
  1058. *
  1059. * @param {Object} [attributes]
  1060. * Attributes to be applied.
  1061. */
  1062. function setAttributes(el, attributes) {
  1063. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  1064. const attrValue = attributes[attrName];
  1065. if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
  1066. el.removeAttribute(attrName);
  1067. } else {
  1068. el.setAttribute(attrName, attrValue === true ? '' : attrValue);
  1069. }
  1070. });
  1071. }
  1072. /**
  1073. * Get an element's attribute values, as defined on the HTML tag.
  1074. *
  1075. * Attributes are not the same as properties. They're defined on the tag
  1076. * or with setAttribute.
  1077. *
  1078. * @param {Element} tag
  1079. * Element from which to get tag attributes.
  1080. *
  1081. * @return {Object}
  1082. * All attributes of the element. Boolean attributes will be `true` or
  1083. * `false`, others will be strings.
  1084. */
  1085. function getAttributes(tag) {
  1086. const obj = {};
  1087. // known boolean attributes
  1088. // we can check for matching boolean properties, but not all browsers
  1089. // and not all tags know about these attributes, so, we still want to check them manually
  1090. const knownBooleans = ',' + 'autoplay,controls,playsinline,loop,muted,default,defaultMuted' + ',';
  1091. if (tag && tag.attributes && tag.attributes.length > 0) {
  1092. const attrs = tag.attributes;
  1093. for (let i = attrs.length - 1; i >= 0; i--) {
  1094. const attrName = attrs[i].name;
  1095. let attrVal = attrs[i].value;
  1096. // check for known booleans
  1097. // the matching element property will return a value for typeof
  1098. if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) {
  1099. // the value of an included boolean attribute is typically an empty
  1100. // string ('') which would equal false if we just check for a false value.
  1101. // we also don't want support bad code like autoplay='false'
  1102. attrVal = attrVal !== null ? true : false;
  1103. }
  1104. obj[attrName] = attrVal;
  1105. }
  1106. }
  1107. return obj;
  1108. }
  1109. /**
  1110. * Get the value of an element's attribute.
  1111. *
  1112. * @param {Element} el
  1113. * A DOM element.
  1114. *
  1115. * @param {string} attribute
  1116. * Attribute to get the value of.
  1117. *
  1118. * @return {string}
  1119. * The value of the attribute.
  1120. */
  1121. function getAttribute(el, attribute) {
  1122. return el.getAttribute(attribute);
  1123. }
  1124. /**
  1125. * Set the value of an element's attribute.
  1126. *
  1127. * @param {Element} el
  1128. * A DOM element.
  1129. *
  1130. * @param {string} attribute
  1131. * Attribute to set.
  1132. *
  1133. * @param {string} value
  1134. * Value to set the attribute to.
  1135. */
  1136. function setAttribute(el, attribute, value) {
  1137. el.setAttribute(attribute, value);
  1138. }
  1139. /**
  1140. * Remove an element's attribute.
  1141. *
  1142. * @param {Element} el
  1143. * A DOM element.
  1144. *
  1145. * @param {string} attribute
  1146. * Attribute to remove.
  1147. */
  1148. function removeAttribute(el, attribute) {
  1149. el.removeAttribute(attribute);
  1150. }
  1151. /**
  1152. * Attempt to block the ability to select text.
  1153. */
  1154. function blockTextSelection() {
  1155. document.body.focus();
  1156. document.onselectstart = function () {
  1157. return false;
  1158. };
  1159. }
  1160. /**
  1161. * Turn off text selection blocking.
  1162. */
  1163. function unblockTextSelection() {
  1164. document.onselectstart = function () {
  1165. return true;
  1166. };
  1167. }
  1168. /**
  1169. * Identical to the native `getBoundingClientRect` function, but ensures that
  1170. * the method is supported at all (it is in all browsers we claim to support)
  1171. * and that the element is in the DOM before continuing.
  1172. *
  1173. * This wrapper function also shims properties which are not provided by some
  1174. * older browsers (namely, IE8).
  1175. *
  1176. * Additionally, some browsers do not support adding properties to a
  1177. * `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard
  1178. * properties (except `x` and `y` which are not widely supported). This helps
  1179. * avoid implementations where keys are non-enumerable.
  1180. *
  1181. * @param {Element} el
  1182. * Element whose `ClientRect` we want to calculate.
  1183. *
  1184. * @return {Object|undefined}
  1185. * Always returns a plain object - or `undefined` if it cannot.
  1186. */
  1187. function getBoundingClientRect(el) {
  1188. if (el && el.getBoundingClientRect && el.parentNode) {
  1189. const rect = el.getBoundingClientRect();
  1190. const result = {};
  1191. ['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(k => {
  1192. if (rect[k] !== undefined) {
  1193. result[k] = rect[k];
  1194. }
  1195. });
  1196. if (!result.height) {
  1197. result.height = parseFloat(computedStyle(el, 'height'));
  1198. }
  1199. if (!result.width) {
  1200. result.width = parseFloat(computedStyle(el, 'width'));
  1201. }
  1202. return result;
  1203. }
  1204. }
  1205. /**
  1206. * Represents the position of a DOM element on the page.
  1207. *
  1208. * @typedef {Object} module:dom~Position
  1209. *
  1210. * @property {number} left
  1211. * Pixels to the left.
  1212. *
  1213. * @property {number} top
  1214. * Pixels from the top.
  1215. */
  1216. /**
  1217. * Get the position of an element in the DOM.
  1218. *
  1219. * Uses `getBoundingClientRect` technique from John Resig.
  1220. *
  1221. * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/
  1222. *
  1223. * @param {Element} el
  1224. * Element from which to get offset.
  1225. *
  1226. * @return {module:dom~Position}
  1227. * The position of the element that was passed in.
  1228. */
  1229. function findPosition(el) {
  1230. if (!el || el && !el.offsetParent) {
  1231. return {
  1232. left: 0,
  1233. top: 0,
  1234. width: 0,
  1235. height: 0
  1236. };
  1237. }
  1238. const width = el.offsetWidth;
  1239. const height = el.offsetHeight;
  1240. let left = 0;
  1241. let top = 0;
  1242. while (el.offsetParent && el !== document[FullscreenApi.fullscreenElement]) {
  1243. left += el.offsetLeft;
  1244. top += el.offsetTop;
  1245. el = el.offsetParent;
  1246. }
  1247. return {
  1248. left,
  1249. top,
  1250. width,
  1251. height
  1252. };
  1253. }
  1254. /**
  1255. * Represents x and y coordinates for a DOM element or mouse pointer.
  1256. *
  1257. * @typedef {Object} module:dom~Coordinates
  1258. *
  1259. * @property {number} x
  1260. * x coordinate in pixels
  1261. *
  1262. * @property {number} y
  1263. * y coordinate in pixels
  1264. */
  1265. /**
  1266. * Get the pointer position within an element.
  1267. *
  1268. * The base on the coordinates are the bottom left of the element.
  1269. *
  1270. * @param {Element} el
  1271. * Element on which to get the pointer position on.
  1272. *
  1273. * @param {Event} event
  1274. * Event object.
  1275. *
  1276. * @return {module:dom~Coordinates}
  1277. * A coordinates object corresponding to the mouse position.
  1278. *
  1279. */
  1280. function getPointerPosition(el, event) {
  1281. const translated = {
  1282. x: 0,
  1283. y: 0
  1284. };
  1285. if (IS_IOS) {
  1286. let item = el;
  1287. while (item && item.nodeName.toLowerCase() !== 'html') {
  1288. const transform = computedStyle(item, 'transform');
  1289. if (/^matrix/.test(transform)) {
  1290. const values = transform.slice(7, -1).split(/,\s/).map(Number);
  1291. translated.x += values[4];
  1292. translated.y += values[5];
  1293. } else if (/^matrix3d/.test(transform)) {
  1294. const values = transform.slice(9, -1).split(/,\s/).map(Number);
  1295. translated.x += values[12];
  1296. translated.y += values[13];
  1297. }
  1298. item = item.parentNode;
  1299. }
  1300. }
  1301. const position = {};
  1302. const boxTarget = findPosition(event.target);
  1303. const box = findPosition(el);
  1304. const boxW = box.width;
  1305. const boxH = box.height;
  1306. let offsetY = event.offsetY - (box.top - boxTarget.top);
  1307. let offsetX = event.offsetX - (box.left - boxTarget.left);
  1308. if (event.changedTouches) {
  1309. offsetX = event.changedTouches[0].pageX - box.left;
  1310. offsetY = event.changedTouches[0].pageY + box.top;
  1311. if (IS_IOS) {
  1312. offsetX -= translated.x;
  1313. offsetY -= translated.y;
  1314. }
  1315. }
  1316. position.y = 1 - Math.max(0, Math.min(1, offsetY / boxH));
  1317. position.x = Math.max(0, Math.min(1, offsetX / boxW));
  1318. return position;
  1319. }
  1320. /**
  1321. * Determines, via duck typing, whether or not a value is a text node.
  1322. *
  1323. * @param {*} value
  1324. * Check if this value is a text node.
  1325. *
  1326. * @return {boolean}
  1327. * Will be `true` if the value is a text node, `false` otherwise.
  1328. */
  1329. function isTextNode(value) {
  1330. return isObject(value) && value.nodeType === 3;
  1331. }
  1332. /**
  1333. * Empties the contents of an element.
  1334. *
  1335. * @param {Element} el
  1336. * The element to empty children from
  1337. *
  1338. * @return {Element}
  1339. * The element with no children
  1340. */
  1341. function emptyEl(el) {
  1342. while (el.firstChild) {
  1343. el.removeChild(el.firstChild);
  1344. }
  1345. return el;
  1346. }
  1347. /**
  1348. * This is a mixed value that describes content to be injected into the DOM
  1349. * via some method. It can be of the following types:
  1350. *
  1351. * Type | Description
  1352. * -----------|-------------
  1353. * `string` | The value will be normalized into a text node.
  1354. * `Element` | The value will be accepted as-is.
  1355. * `Text` | A TextNode. The value will be accepted as-is.
  1356. * `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).
  1357. * `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.
  1358. *
  1359. * @typedef {string|Element|Text|Array|Function} ContentDescriptor
  1360. */
  1361. /**
  1362. * Normalizes content for eventual insertion into the DOM.
  1363. *
  1364. * This allows a wide range of content definition methods, but helps protect
  1365. * from falling into the trap of simply writing to `innerHTML`, which could
  1366. * be an XSS concern.
  1367. *
  1368. * The content for an element can be passed in multiple types and
  1369. * combinations, whose behavior is as follows:
  1370. *
  1371. * @param {ContentDescriptor} content
  1372. * A content descriptor value.
  1373. *
  1374. * @return {Array}
  1375. * All of the content that was passed in, normalized to an array of
  1376. * elements or text nodes.
  1377. */
  1378. function normalizeContent(content) {
  1379. // First, invoke content if it is a function. If it produces an array,
  1380. // that needs to happen before normalization.
  1381. if (typeof content === 'function') {
  1382. content = content();
  1383. }
  1384. // Next up, normalize to an array, so one or many items can be normalized,
  1385. // filtered, and returned.
  1386. return (Array.isArray(content) ? content : [content]).map(value => {
  1387. // First, invoke value if it is a function to produce a new value,
  1388. // which will be subsequently normalized to a Node of some kind.
  1389. if (typeof value === 'function') {
  1390. value = value();
  1391. }
  1392. if (isEl(value) || isTextNode(value)) {
  1393. return value;
  1394. }
  1395. if (typeof value === 'string' && /\S/.test(value)) {
  1396. return document.createTextNode(value);
  1397. }
  1398. }).filter(value => value);
  1399. }
  1400. /**
  1401. * Normalizes and appends content to an element.
  1402. *
  1403. * @param {Element} el
  1404. * Element to append normalized content to.
  1405. *
  1406. * @param {ContentDescriptor} content
  1407. * A content descriptor value.
  1408. *
  1409. * @return {Element}
  1410. * The element with appended normalized content.
  1411. */
  1412. function appendContent(el, content) {
  1413. normalizeContent(content).forEach(node => el.appendChild(node));
  1414. return el;
  1415. }
  1416. /**
  1417. * Normalizes and inserts content into an element; this is identical to
  1418. * `appendContent()`, except it empties the element first.
  1419. *
  1420. * @param {Element} el
  1421. * Element to insert normalized content into.
  1422. *
  1423. * @param {ContentDescriptor} content
  1424. * A content descriptor value.
  1425. *
  1426. * @return {Element}
  1427. * The element with inserted normalized content.
  1428. */
  1429. function insertContent(el, content) {
  1430. return appendContent(emptyEl(el), content);
  1431. }
  1432. /**
  1433. * Check if an event was a single left click.
  1434. *
  1435. * @param {Event} event
  1436. * Event object.
  1437. *
  1438. * @return {boolean}
  1439. * Will be `true` if a single left click, `false` otherwise.
  1440. */
  1441. function isSingleLeftClick(event) {
  1442. // Note: if you create something draggable, be sure to
  1443. // call it on both `mousedown` and `mousemove` event,
  1444. // otherwise `mousedown` should be enough for a button
  1445. if (event.button === undefined && event.buttons === undefined) {
  1446. // Why do we need `buttons` ?
  1447. // Because, middle mouse sometimes have this:
  1448. // e.button === 0 and e.buttons === 4
  1449. // Furthermore, we want to prevent combination click, something like
  1450. // HOLD middlemouse then left click, that would be
  1451. // e.button === 0, e.buttons === 5
  1452. // just `button` is not gonna work
  1453. // Alright, then what this block does ?
  1454. // this is for chrome `simulate mobile devices`
  1455. // I want to support this as well
  1456. return true;
  1457. }
  1458. if (event.button === 0 && event.buttons === undefined) {
  1459. // Touch screen, sometimes on some specific device, `buttons`
  1460. // doesn't have anything (safari on ios, blackberry...)
  1461. return true;
  1462. }
  1463. // `mouseup` event on a single left click has
  1464. // `button` and `buttons` equal to 0
  1465. if (event.type === 'mouseup' && event.button === 0 && event.buttons === 0) {
  1466. return true;
  1467. }
  1468. if (event.button !== 0 || event.buttons !== 1) {
  1469. // This is the reason we have those if else block above
  1470. // if any special case we can catch and let it slide
  1471. // we do it above, when get to here, this definitely
  1472. // is-not-left-click
  1473. return false;
  1474. }
  1475. return true;
  1476. }
  1477. /**
  1478. * Finds a single DOM element matching `selector` within the optional
  1479. * `context` of another DOM element (defaulting to `document`).
  1480. *
  1481. * @param {string} selector
  1482. * A valid CSS selector, which will be passed to `querySelector`.
  1483. *
  1484. * @param {Element|String} [context=document]
  1485. * A DOM element within which to query. Can also be a selector
  1486. * string in which case the first matching element will be used
  1487. * as context. If missing (or no element matches selector), falls
  1488. * back to `document`.
  1489. *
  1490. * @return {Element|null}
  1491. * The element that was found or null.
  1492. */
  1493. const $ = createQuerier('querySelector');
  1494. /**
  1495. * Finds a all DOM elements matching `selector` within the optional
  1496. * `context` of another DOM element (defaulting to `document`).
  1497. *
  1498. * @param {string} selector
  1499. * A valid CSS selector, which will be passed to `querySelectorAll`.
  1500. *
  1501. * @param {Element|String} [context=document]
  1502. * A DOM element within which to query. Can also be a selector
  1503. * string in which case the first matching element will be used
  1504. * as context. If missing (or no element matches selector), falls
  1505. * back to `document`.
  1506. *
  1507. * @return {NodeList}
  1508. * A element list of elements that were found. Will be empty if none
  1509. * were found.
  1510. *
  1511. */
  1512. const $$ = createQuerier('querySelectorAll');
  1513. /**
  1514. * A safe getComputedStyle.
  1515. *
  1516. * This is needed because in Firefox, if the player is loaded in an iframe with
  1517. * `display:none`, then `getComputedStyle` returns `null`, so, we do a
  1518. * null-check to make sure that the player doesn't break in these cases.
  1519. *
  1520. * @param {Element} el
  1521. * The element you want the computed style of
  1522. *
  1523. * @param {string} prop
  1524. * The property name you want
  1525. *
  1526. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  1527. */
  1528. function computedStyle(el, prop) {
  1529. if (!el || !prop) {
  1530. return '';
  1531. }
  1532. if (typeof window$1.getComputedStyle === 'function') {
  1533. let computedStyleValue;
  1534. try {
  1535. computedStyleValue = window$1.getComputedStyle(el);
  1536. } catch (e) {
  1537. return '';
  1538. }
  1539. return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : '';
  1540. }
  1541. return '';
  1542. }
  1543. var Dom = /*#__PURE__*/Object.freeze({
  1544. __proto__: null,
  1545. isReal: isReal,
  1546. isEl: isEl,
  1547. isInFrame: isInFrame,
  1548. createEl: createEl,
  1549. textContent: textContent,
  1550. prependTo: prependTo,
  1551. hasClass: hasClass,
  1552. addClass: addClass,
  1553. removeClass: removeClass,
  1554. toggleClass: toggleClass,
  1555. setAttributes: setAttributes,
  1556. getAttributes: getAttributes,
  1557. getAttribute: getAttribute,
  1558. setAttribute: setAttribute,
  1559. removeAttribute: removeAttribute,
  1560. blockTextSelection: blockTextSelection,
  1561. unblockTextSelection: unblockTextSelection,
  1562. getBoundingClientRect: getBoundingClientRect,
  1563. findPosition: findPosition,
  1564. getPointerPosition: getPointerPosition,
  1565. isTextNode: isTextNode,
  1566. emptyEl: emptyEl,
  1567. normalizeContent: normalizeContent,
  1568. appendContent: appendContent,
  1569. insertContent: insertContent,
  1570. isSingleLeftClick: isSingleLeftClick,
  1571. $: $,
  1572. $$: $$,
  1573. computedStyle: computedStyle
  1574. });
  1575. /**
  1576. * @file setup.js - Functions for setting up a player without
  1577. * user interaction based on the data-setup `attribute` of the video tag.
  1578. *
  1579. * @module setup
  1580. */
  1581. let _windowLoaded = false;
  1582. let videojs$1;
  1583. /**
  1584. * Set up any tags that have a data-setup `attribute` when the player is started.
  1585. */
  1586. const autoSetup = function () {
  1587. if (videojs$1.options.autoSetup === false) {
  1588. return;
  1589. }
  1590. const vids = Array.prototype.slice.call(document.getElementsByTagName('video'));
  1591. const audios = Array.prototype.slice.call(document.getElementsByTagName('audio'));
  1592. const divs = Array.prototype.slice.call(document.getElementsByTagName('video-js'));
  1593. const mediaEls = vids.concat(audios, divs);
  1594. // Check if any media elements exist
  1595. if (mediaEls && mediaEls.length > 0) {
  1596. for (let i = 0, e = mediaEls.length; i < e; i++) {
  1597. const mediaEl = mediaEls[i];
  1598. // Check if element exists, has getAttribute func.
  1599. if (mediaEl && mediaEl.getAttribute) {
  1600. // Make sure this player hasn't already been set up.
  1601. if (mediaEl.player === undefined) {
  1602. const options = mediaEl.getAttribute('data-setup');
  1603. // Check if data-setup attr exists.
  1604. // We only auto-setup if they've added the data-setup attr.
  1605. if (options !== null) {
  1606. // Create new video.js instance.
  1607. videojs$1(mediaEl);
  1608. }
  1609. }
  1610. // If getAttribute isn't defined, we need to wait for the DOM.
  1611. } else {
  1612. autoSetupTimeout(1);
  1613. break;
  1614. }
  1615. }
  1616. // No videos were found, so keep looping unless page is finished loading.
  1617. } else if (!_windowLoaded) {
  1618. autoSetupTimeout(1);
  1619. }
  1620. };
  1621. /**
  1622. * Wait until the page is loaded before running autoSetup. This will be called in
  1623. * autoSetup if `hasLoaded` returns false.
  1624. *
  1625. * @param {number} wait
  1626. * How long to wait in ms
  1627. *
  1628. * @param {module:videojs} [vjs]
  1629. * The videojs library function
  1630. */
  1631. function autoSetupTimeout(wait, vjs) {
  1632. // Protect against breakage in non-browser environments
  1633. if (!isReal()) {
  1634. return;
  1635. }
  1636. if (vjs) {
  1637. videojs$1 = vjs;
  1638. }
  1639. window$1.setTimeout(autoSetup, wait);
  1640. }
  1641. /**
  1642. * Used to set the internal tracking of window loaded state to true.
  1643. *
  1644. * @private
  1645. */
  1646. function setWindowLoaded() {
  1647. _windowLoaded = true;
  1648. window$1.removeEventListener('load', setWindowLoaded);
  1649. }
  1650. if (isReal()) {
  1651. if (document.readyState === 'complete') {
  1652. setWindowLoaded();
  1653. } else {
  1654. /**
  1655. * Listen for the load event on window, and set _windowLoaded to true.
  1656. *
  1657. * We use a standard event listener here to avoid incrementing the GUID
  1658. * before any players are created.
  1659. *
  1660. * @listens load
  1661. */
  1662. window$1.addEventListener('load', setWindowLoaded);
  1663. }
  1664. }
  1665. /**
  1666. * @file stylesheet.js
  1667. * @module stylesheet
  1668. */
  1669. /**
  1670. * Create a DOM style element given a className for it.
  1671. *
  1672. * @param {string} className
  1673. * The className to add to the created style element.
  1674. *
  1675. * @return {Element}
  1676. * The element that was created.
  1677. */
  1678. const createStyleElement = function (className) {
  1679. const style = document.createElement('style');
  1680. style.className = className;
  1681. return style;
  1682. };
  1683. /**
  1684. * Add text to a DOM element.
  1685. *
  1686. * @param {Element} el
  1687. * The Element to add text content to.
  1688. *
  1689. * @param {string} content
  1690. * The text to add to the element.
  1691. */
  1692. const setTextContent = function (el, content) {
  1693. if (el.styleSheet) {
  1694. el.styleSheet.cssText = content;
  1695. } else {
  1696. el.textContent = content;
  1697. }
  1698. };
  1699. /**
  1700. * @file dom-data.js
  1701. * @module dom-data
  1702. */
  1703. /**
  1704. * Element Data Store.
  1705. *
  1706. * Allows for binding data to an element without putting it directly on the
  1707. * element. Ex. Event listeners are stored here.
  1708. * (also from jsninja.com, slightly modified and updated for closure compiler)
  1709. *
  1710. * @type {Object}
  1711. * @private
  1712. */
  1713. var DomData = new WeakMap();
  1714. /**
  1715. * @file guid.js
  1716. * @module guid
  1717. */
  1718. // Default value for GUIDs. This allows us to reset the GUID counter in tests.
  1719. //
  1720. // The initial GUID is 3 because some users have come to rely on the first
  1721. // default player ID ending up as `vjs_video_3`.
  1722. //
  1723. // See: https://github.com/videojs/video.js/pull/6216
  1724. const _initialGuid = 3;
  1725. /**
  1726. * Unique ID for an element or function
  1727. *
  1728. * @type {Number}
  1729. */
  1730. let _guid = _initialGuid;
  1731. /**
  1732. * Get a unique auto-incrementing ID by number that has not been returned before.
  1733. *
  1734. * @return {number}
  1735. * A new unique ID.
  1736. */
  1737. function newGUID() {
  1738. return _guid++;
  1739. }
  1740. /**
  1741. * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
  1742. * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
  1743. * This should work very similarly to jQuery's events, however it's based off the book version which isn't as
  1744. * robust as jquery's, so there's probably some differences.
  1745. *
  1746. * @file events.js
  1747. * @module events
  1748. */
  1749. /**
  1750. * Clean up the listener cache and dispatchers
  1751. *
  1752. * @param {Element|Object} elem
  1753. * Element to clean up
  1754. *
  1755. * @param {string} type
  1756. * Type of event to clean up
  1757. */
  1758. function _cleanUpEvents(elem, type) {
  1759. if (!DomData.has(elem)) {
  1760. return;
  1761. }
  1762. const data = DomData.get(elem);
  1763. // Remove the events of a particular type if there are none left
  1764. if (data.handlers[type].length === 0) {
  1765. delete data.handlers[type];
  1766. // data.handlers[type] = null;
  1767. // Setting to null was causing an error with data.handlers
  1768. // Remove the meta-handler from the element
  1769. if (elem.removeEventListener) {
  1770. elem.removeEventListener(type, data.dispatcher, false);
  1771. } else if (elem.detachEvent) {
  1772. elem.detachEvent('on' + type, data.dispatcher);
  1773. }
  1774. }
  1775. // Remove the events object if there are no types left
  1776. if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
  1777. delete data.handlers;
  1778. delete data.dispatcher;
  1779. delete data.disabled;
  1780. }
  1781. // Finally remove the element data if there is no data left
  1782. if (Object.getOwnPropertyNames(data).length === 0) {
  1783. DomData.delete(elem);
  1784. }
  1785. }
  1786. /**
  1787. * Loops through an array of event types and calls the requested method for each type.
  1788. *
  1789. * @param {Function} fn
  1790. * The event method we want to use.
  1791. *
  1792. * @param {Element|Object} elem
  1793. * Element or object to bind listeners to
  1794. *
  1795. * @param {string} type
  1796. * Type of event to bind to.
  1797. *
  1798. * @param {Function} callback
  1799. * Event listener.
  1800. */
  1801. function _handleMultipleEvents(fn, elem, types, callback) {
  1802. types.forEach(function (type) {
  1803. // Call the event method for each one of the types
  1804. fn(elem, type, callback);
  1805. });
  1806. }
  1807. /**
  1808. * Fix a native event to have standard property values
  1809. *
  1810. * @param {Object} event
  1811. * Event object to fix.
  1812. *
  1813. * @return {Object}
  1814. * Fixed event object.
  1815. */
  1816. function fixEvent(event) {
  1817. if (event.fixed_) {
  1818. return event;
  1819. }
  1820. function returnTrue() {
  1821. return true;
  1822. }
  1823. function returnFalse() {
  1824. return false;
  1825. }
  1826. // Test if fixing up is needed
  1827. // Used to check if !event.stopPropagation instead of isPropagationStopped
  1828. // But native events return true for stopPropagation, but don't have
  1829. // other expected methods like isPropagationStopped. Seems to be a problem
  1830. // with the Javascript Ninja code. So we're just overriding all events now.
  1831. if (!event || !event.isPropagationStopped || !event.isImmediatePropagationStopped) {
  1832. const old = event || window$1.event;
  1833. event = {};
  1834. // Clone the old object so that we can modify the values event = {};
  1835. // IE8 Doesn't like when you mess with native event properties
  1836. // Firefox returns false for event.hasOwnProperty('type') and other props
  1837. // which makes copying more difficult.
  1838. // TODO: Probably best to create a whitelist of event props
  1839. for (const key in old) {
  1840. // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
  1841. // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
  1842. // and webkitMovementX/Y
  1843. // Lighthouse complains if Event.path is copied
  1844. if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY' && key !== 'path') {
  1845. // Chrome 32+ warns if you try to copy deprecated returnValue, but
  1846. // we still want to if preventDefault isn't supported (IE8).
  1847. if (!(key === 'returnValue' && old.preventDefault)) {
  1848. event[key] = old[key];
  1849. }
  1850. }
  1851. }
  1852. // The event occurred on this element
  1853. if (!event.target) {
  1854. event.target = event.srcElement || document;
  1855. }
  1856. // Handle which other element the event is related to
  1857. if (!event.relatedTarget) {
  1858. event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
  1859. }
  1860. // Stop the default browser action
  1861. event.preventDefault = function () {
  1862. if (old.preventDefault) {
  1863. old.preventDefault();
  1864. }
  1865. event.returnValue = false;
  1866. old.returnValue = false;
  1867. event.defaultPrevented = true;
  1868. };
  1869. event.defaultPrevented = false;
  1870. // Stop the event from bubbling
  1871. event.stopPropagation = function () {
  1872. if (old.stopPropagation) {
  1873. old.stopPropagation();
  1874. }
  1875. event.cancelBubble = true;
  1876. old.cancelBubble = true;
  1877. event.isPropagationStopped = returnTrue;
  1878. };
  1879. event.isPropagationStopped = returnFalse;
  1880. // Stop the event from bubbling and executing other handlers
  1881. event.stopImmediatePropagation = function () {
  1882. if (old.stopImmediatePropagation) {
  1883. old.stopImmediatePropagation();
  1884. }
  1885. event.isImmediatePropagationStopped = returnTrue;
  1886. event.stopPropagation();
  1887. };
  1888. event.isImmediatePropagationStopped = returnFalse;
  1889. // Handle mouse position
  1890. if (event.clientX !== null && event.clientX !== undefined) {
  1891. const doc = document.documentElement;
  1892. const body = document.body;
  1893. event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  1894. event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  1895. }
  1896. // Handle key presses
  1897. event.which = event.charCode || event.keyCode;
  1898. // Fix button for mouse clicks:
  1899. // 0 == left; 1 == middle; 2 == right
  1900. if (event.button !== null && event.button !== undefined) {
  1901. // The following is disabled because it does not pass videojs-standard
  1902. // and... yikes.
  1903. /* eslint-disable */
  1904. event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
  1905. /* eslint-enable */
  1906. }
  1907. }
  1908. event.fixed_ = true;
  1909. // Returns fixed-up instance
  1910. return event;
  1911. }
  1912. /**
  1913. * Whether passive event listeners are supported
  1914. */
  1915. let _supportsPassive;
  1916. const supportsPassive = function () {
  1917. if (typeof _supportsPassive !== 'boolean') {
  1918. _supportsPassive = false;
  1919. try {
  1920. const opts = Object.defineProperty({}, 'passive', {
  1921. get() {
  1922. _supportsPassive = true;
  1923. }
  1924. });
  1925. window$1.addEventListener('test', null, opts);
  1926. window$1.removeEventListener('test', null, opts);
  1927. } catch (e) {
  1928. // disregard
  1929. }
  1930. }
  1931. return _supportsPassive;
  1932. };
  1933. /**
  1934. * Touch events Chrome expects to be passive
  1935. */
  1936. const passiveEvents = ['touchstart', 'touchmove'];
  1937. /**
  1938. * Add an event listener to element
  1939. * It stores the handler function in a separate cache object
  1940. * and adds a generic handler to the element's event,
  1941. * along with a unique id (guid) to the element.
  1942. *
  1943. * @param {Element|Object} elem
  1944. * Element or object to bind listeners to
  1945. *
  1946. * @param {string|string[]} type
  1947. * Type of event to bind to.
  1948. *
  1949. * @param {Function} fn
  1950. * Event listener.
  1951. */
  1952. function on(elem, type, fn) {
  1953. if (Array.isArray(type)) {
  1954. return _handleMultipleEvents(on, elem, type, fn);
  1955. }
  1956. if (!DomData.has(elem)) {
  1957. DomData.set(elem, {});
  1958. }
  1959. const data = DomData.get(elem);
  1960. // We need a place to store all our handler data
  1961. if (!data.handlers) {
  1962. data.handlers = {};
  1963. }
  1964. if (!data.handlers[type]) {
  1965. data.handlers[type] = [];
  1966. }
  1967. if (!fn.guid) {
  1968. fn.guid = newGUID();
  1969. }
  1970. data.handlers[type].push(fn);
  1971. if (!data.dispatcher) {
  1972. data.disabled = false;
  1973. data.dispatcher = function (event, hash) {
  1974. if (data.disabled) {
  1975. return;
  1976. }
  1977. event = fixEvent(event);
  1978. const handlers = data.handlers[event.type];
  1979. if (handlers) {
  1980. // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
  1981. const handlersCopy = handlers.slice(0);
  1982. for (let m = 0, n = handlersCopy.length; m < n; m++) {
  1983. if (event.isImmediatePropagationStopped()) {
  1984. break;
  1985. } else {
  1986. try {
  1987. handlersCopy[m].call(elem, event, hash);
  1988. } catch (e) {
  1989. log$1.error(e);
  1990. }
  1991. }
  1992. }
  1993. }
  1994. };
  1995. }
  1996. if (data.handlers[type].length === 1) {
  1997. if (elem.addEventListener) {
  1998. let options = false;
  1999. if (supportsPassive() && passiveEvents.indexOf(type) > -1) {
  2000. options = {
  2001. passive: true
  2002. };
  2003. }
  2004. elem.addEventListener(type, data.dispatcher, options);
  2005. } else if (elem.attachEvent) {
  2006. elem.attachEvent('on' + type, data.dispatcher);
  2007. }
  2008. }
  2009. }
  2010. /**
  2011. * Removes event listeners from an element
  2012. *
  2013. * @param {Element|Object} elem
  2014. * Object to remove listeners from.
  2015. *
  2016. * @param {string|string[]} [type]
  2017. * Type of listener to remove. Don't include to remove all events from element.
  2018. *
  2019. * @param {Function} [fn]
  2020. * Specific listener to remove. Don't include to remove listeners for an event
  2021. * type.
  2022. */
  2023. function off(elem, type, fn) {
  2024. // Don't want to add a cache object through getElData if not needed
  2025. if (!DomData.has(elem)) {
  2026. return;
  2027. }
  2028. const data = DomData.get(elem);
  2029. // If no events exist, nothing to unbind
  2030. if (!data.handlers) {
  2031. return;
  2032. }
  2033. if (Array.isArray(type)) {
  2034. return _handleMultipleEvents(off, elem, type, fn);
  2035. }
  2036. // Utility function
  2037. const removeType = function (el, t) {
  2038. data.handlers[t] = [];
  2039. _cleanUpEvents(el, t);
  2040. };
  2041. // Are we removing all bound events?
  2042. if (type === undefined) {
  2043. for (const t in data.handlers) {
  2044. if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t)) {
  2045. removeType(elem, t);
  2046. }
  2047. }
  2048. return;
  2049. }
  2050. const handlers = data.handlers[type];
  2051. // If no handlers exist, nothing to unbind
  2052. if (!handlers) {
  2053. return;
  2054. }
  2055. // If no listener was provided, remove all listeners for type
  2056. if (!fn) {
  2057. removeType(elem, type);
  2058. return;
  2059. }
  2060. // We're only removing a single handler
  2061. if (fn.guid) {
  2062. for (let n = 0; n < handlers.length; n++) {
  2063. if (handlers[n].guid === fn.guid) {
  2064. handlers.splice(n--, 1);
  2065. }
  2066. }
  2067. }
  2068. _cleanUpEvents(elem, type);
  2069. }
  2070. /**
  2071. * Trigger an event for an element
  2072. *
  2073. * @param {Element|Object} elem
  2074. * Element to trigger an event on
  2075. *
  2076. * @param {EventTarget~Event|string} event
  2077. * A string (the type) or an event object with a type attribute
  2078. *
  2079. * @param {Object} [hash]
  2080. * data hash to pass along with the event
  2081. *
  2082. * @return {boolean|undefined}
  2083. * Returns the opposite of `defaultPrevented` if default was
  2084. * prevented. Otherwise, returns `undefined`
  2085. */
  2086. function trigger(elem, event, hash) {
  2087. // Fetches element data and a reference to the parent (for bubbling).
  2088. // Don't want to add a data object to cache for every parent,
  2089. // so checking hasElData first.
  2090. const elemData = DomData.has(elem) ? DomData.get(elem) : {};
  2091. const parent = elem.parentNode || elem.ownerDocument;
  2092. // type = event.type || event,
  2093. // handler;
  2094. // If an event name was passed as a string, creates an event out of it
  2095. if (typeof event === 'string') {
  2096. event = {
  2097. type: event,
  2098. target: elem
  2099. };
  2100. } else if (!event.target) {
  2101. event.target = elem;
  2102. }
  2103. // Normalizes the event properties.
  2104. event = fixEvent(event);
  2105. // If the passed element has a dispatcher, executes the established handlers.
  2106. if (elemData.dispatcher) {
  2107. elemData.dispatcher.call(elem, event, hash);
  2108. }
  2109. // Unless explicitly stopped or the event does not bubble (e.g. media events)
  2110. // recursively calls this function to bubble the event up the DOM.
  2111. if (parent && !event.isPropagationStopped() && event.bubbles === true) {
  2112. trigger.call(null, parent, event, hash);
  2113. // If at the top of the DOM, triggers the default action unless disabled.
  2114. } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) {
  2115. if (!DomData.has(event.target)) {
  2116. DomData.set(event.target, {});
  2117. }
  2118. const targetData = DomData.get(event.target);
  2119. // Checks if the target has a default action for this event.
  2120. if (event.target[event.type]) {
  2121. // Temporarily disables event dispatching on the target as we have already executed the handler.
  2122. targetData.disabled = true;
  2123. // Executes the default action.
  2124. if (typeof event.target[event.type] === 'function') {
  2125. event.target[event.type]();
  2126. }
  2127. // Re-enables event dispatching.
  2128. targetData.disabled = false;
  2129. }
  2130. }
  2131. // Inform the triggerer if the default was prevented by returning false
  2132. return !event.defaultPrevented;
  2133. }
  2134. /**
  2135. * Trigger a listener only once for an event.
  2136. *
  2137. * @param {Element|Object} elem
  2138. * Element or object to bind to.
  2139. *
  2140. * @param {string|string[]} type
  2141. * Name/type of event
  2142. *
  2143. * @param {Event~EventListener} fn
  2144. * Event listener function
  2145. */
  2146. function one(elem, type, fn) {
  2147. if (Array.isArray(type)) {
  2148. return _handleMultipleEvents(one, elem, type, fn);
  2149. }
  2150. const func = function () {
  2151. off(elem, type, func);
  2152. fn.apply(this, arguments);
  2153. };
  2154. // copy the guid to the new function so it can removed using the original function's ID
  2155. func.guid = fn.guid = fn.guid || newGUID();
  2156. on(elem, type, func);
  2157. }
  2158. /**
  2159. * Trigger a listener only once and then turn if off for all
  2160. * configured events
  2161. *
  2162. * @param {Element|Object} elem
  2163. * Element or object to bind to.
  2164. *
  2165. * @param {string|string[]} type
  2166. * Name/type of event
  2167. *
  2168. * @param {Event~EventListener} fn
  2169. * Event listener function
  2170. */
  2171. function any(elem, type, fn) {
  2172. const func = function () {
  2173. off(elem, type, func);
  2174. fn.apply(this, arguments);
  2175. };
  2176. // copy the guid to the new function so it can removed using the original function's ID
  2177. func.guid = fn.guid = fn.guid || newGUID();
  2178. // multiple ons, but one off for everything
  2179. on(elem, type, func);
  2180. }
  2181. var Events = /*#__PURE__*/Object.freeze({
  2182. __proto__: null,
  2183. fixEvent: fixEvent,
  2184. on: on,
  2185. off: off,
  2186. trigger: trigger,
  2187. one: one,
  2188. any: any
  2189. });
  2190. /**
  2191. * @file fn.js
  2192. * @module fn
  2193. */
  2194. const UPDATE_REFRESH_INTERVAL = 30;
  2195. /**
  2196. * A private, internal-only function for changing the context of a function.
  2197. *
  2198. * It also stores a unique id on the function so it can be easily removed from
  2199. * events.
  2200. *
  2201. * @private
  2202. * @function
  2203. * @param {*} context
  2204. * The object to bind as scope.
  2205. *
  2206. * @param {Function} fn
  2207. * The function to be bound to a scope.
  2208. *
  2209. * @param {number} [uid]
  2210. * An optional unique ID for the function to be set
  2211. *
  2212. * @return {Function}
  2213. * The new function that will be bound into the context given
  2214. */
  2215. const bind_ = function (context, fn, uid) {
  2216. // Make sure the function has a unique ID
  2217. if (!fn.guid) {
  2218. fn.guid = newGUID();
  2219. }
  2220. // Create the new function that changes the context
  2221. const bound = fn.bind(context);
  2222. // Allow for the ability to individualize this function
  2223. // Needed in the case where multiple objects might share the same prototype
  2224. // IF both items add an event listener with the same function, then you try to remove just one
  2225. // it will remove both because they both have the same guid.
  2226. // when using this, you need to use the bind method when you remove the listener as well.
  2227. // currently used in text tracks
  2228. bound.guid = uid ? uid + '_' + fn.guid : fn.guid;
  2229. return bound;
  2230. };
  2231. /**
  2232. * Wraps the given function, `fn`, with a new function that only invokes `fn`
  2233. * at most once per every `wait` milliseconds.
  2234. *
  2235. * @function
  2236. * @param {Function} fn
  2237. * The function to be throttled.
  2238. *
  2239. * @param {number} wait
  2240. * The number of milliseconds by which to throttle.
  2241. *
  2242. * @return {Function}
  2243. */
  2244. const throttle = function (fn, wait) {
  2245. let last = window$1.performance.now();
  2246. const throttled = function (...args) {
  2247. const now = window$1.performance.now();
  2248. if (now - last >= wait) {
  2249. fn(...args);
  2250. last = now;
  2251. }
  2252. };
  2253. return throttled;
  2254. };
  2255. /**
  2256. * Creates a debounced function that delays invoking `func` until after `wait`
  2257. * milliseconds have elapsed since the last time the debounced function was
  2258. * invoked.
  2259. *
  2260. * Inspired by lodash and underscore implementations.
  2261. *
  2262. * @function
  2263. * @param {Function} func
  2264. * The function to wrap with debounce behavior.
  2265. *
  2266. * @param {number} wait
  2267. * The number of milliseconds to wait after the last invocation.
  2268. *
  2269. * @param {boolean} [immediate]
  2270. * Whether or not to invoke the function immediately upon creation.
  2271. *
  2272. * @param {Object} [context=window]
  2273. * The "context" in which the debounced function should debounce. For
  2274. * example, if this function should be tied to a Video.js player,
  2275. * the player can be passed here. Alternatively, defaults to the
  2276. * global `window` object.
  2277. *
  2278. * @return {Function}
  2279. * A debounced function.
  2280. */
  2281. const debounce = function (func, wait, immediate, context = window$1) {
  2282. let timeout;
  2283. const cancel = () => {
  2284. context.clearTimeout(timeout);
  2285. timeout = null;
  2286. };
  2287. /* eslint-disable consistent-this */
  2288. const debounced = function () {
  2289. const self = this;
  2290. const args = arguments;
  2291. let later = function () {
  2292. timeout = null;
  2293. later = null;
  2294. if (!immediate) {
  2295. func.apply(self, args);
  2296. }
  2297. };
  2298. if (!timeout && immediate) {
  2299. func.apply(self, args);
  2300. }
  2301. context.clearTimeout(timeout);
  2302. timeout = context.setTimeout(later, wait);
  2303. };
  2304. /* eslint-enable consistent-this */
  2305. debounced.cancel = cancel;
  2306. return debounced;
  2307. };
  2308. var Fn = /*#__PURE__*/Object.freeze({
  2309. __proto__: null,
  2310. UPDATE_REFRESH_INTERVAL: UPDATE_REFRESH_INTERVAL,
  2311. bind_: bind_,
  2312. throttle: throttle,
  2313. debounce: debounce
  2314. });
  2315. /**
  2316. * @file src/js/event-target.js
  2317. */
  2318. let EVENT_MAP;
  2319. /**
  2320. * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It
  2321. * adds shorthand functions that wrap around lengthy functions. For example:
  2322. * the `on` function is a wrapper around `addEventListener`.
  2323. *
  2324. * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget}
  2325. * @class EventTarget
  2326. */
  2327. class EventTarget$2 {
  2328. /**
  2329. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  2330. * function that will get called when an event with a certain name gets triggered.
  2331. *
  2332. * @param {string|string[]} type
  2333. * An event name or an array of event names.
  2334. *
  2335. * @param {Function} fn
  2336. * The function to call with `EventTarget`s
  2337. */
  2338. on(type, fn) {
  2339. // Remove the addEventListener alias before calling Events.on
  2340. // so we don't get into an infinite type loop
  2341. const ael = this.addEventListener;
  2342. this.addEventListener = () => {};
  2343. on(this, type, fn);
  2344. this.addEventListener = ael;
  2345. }
  2346. /**
  2347. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  2348. * This makes it so that the `event listener` will no longer get called when the
  2349. * named event happens.
  2350. *
  2351. * @param {string|string[]} type
  2352. * An event name or an array of event names.
  2353. *
  2354. * @param {Function} fn
  2355. * The function to remove.
  2356. */
  2357. off(type, fn) {
  2358. off(this, type, fn);
  2359. }
  2360. /**
  2361. * This function will add an `event listener` that gets triggered only once. After the
  2362. * first trigger it will get removed. This is like adding an `event listener`
  2363. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  2364. *
  2365. * @param {string|string[]} type
  2366. * An event name or an array of event names.
  2367. *
  2368. * @param {Function} fn
  2369. * The function to be called once for each event name.
  2370. */
  2371. one(type, fn) {
  2372. // Remove the addEventListener aliasing Events.on
  2373. // so we don't get into an infinite type loop
  2374. const ael = this.addEventListener;
  2375. this.addEventListener = () => {};
  2376. one(this, type, fn);
  2377. this.addEventListener = ael;
  2378. }
  2379. /**
  2380. * This function will add an `event listener` that gets triggered only once and is
  2381. * removed from all events. This is like adding an array of `event listener`s
  2382. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  2383. * first time it is triggered.
  2384. *
  2385. * @param {string|string[]} type
  2386. * An event name or an array of event names.
  2387. *
  2388. * @param {Function} fn
  2389. * The function to be called once for each event name.
  2390. */
  2391. any(type, fn) {
  2392. // Remove the addEventListener aliasing Events.on
  2393. // so we don't get into an infinite type loop
  2394. const ael = this.addEventListener;
  2395. this.addEventListener = () => {};
  2396. any(this, type, fn);
  2397. this.addEventListener = ael;
  2398. }
  2399. /**
  2400. * This function causes an event to happen. This will then cause any `event listeners`
  2401. * that are waiting for that event, to get called. If there are no `event listeners`
  2402. * for an event then nothing will happen.
  2403. *
  2404. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  2405. * Trigger will also call the `on` + `uppercaseEventName` function.
  2406. *
  2407. * Example:
  2408. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  2409. * `onClick` if it exists.
  2410. *
  2411. * @param {string|EventTarget~Event|Object} event
  2412. * The name of the event, an `Event`, or an object with a key of type set to
  2413. * an event name.
  2414. */
  2415. trigger(event) {
  2416. const type = event.type || event;
  2417. // deprecation
  2418. // In a future version we should default target to `this`
  2419. // similar to how we default the target to `elem` in
  2420. // `Events.trigger`. Right now the default `target` will be
  2421. // `document` due to the `Event.fixEvent` call.
  2422. if (typeof event === 'string') {
  2423. event = {
  2424. type
  2425. };
  2426. }
  2427. event = fixEvent(event);
  2428. if (this.allowedEvents_[type] && this['on' + type]) {
  2429. this['on' + type](event);
  2430. }
  2431. trigger(this, event);
  2432. }
  2433. queueTrigger(event) {
  2434. // only set up EVENT_MAP if it'll be used
  2435. if (!EVENT_MAP) {
  2436. EVENT_MAP = new Map();
  2437. }
  2438. const type = event.type || event;
  2439. let map = EVENT_MAP.get(this);
  2440. if (!map) {
  2441. map = new Map();
  2442. EVENT_MAP.set(this, map);
  2443. }
  2444. const oldTimeout = map.get(type);
  2445. map.delete(type);
  2446. window$1.clearTimeout(oldTimeout);
  2447. const timeout = window$1.setTimeout(() => {
  2448. map.delete(type);
  2449. // if we cleared out all timeouts for the current target, delete its map
  2450. if (map.size === 0) {
  2451. map = null;
  2452. EVENT_MAP.delete(this);
  2453. }
  2454. this.trigger(event);
  2455. }, 0);
  2456. map.set(type, timeout);
  2457. }
  2458. }
  2459. /**
  2460. * A Custom DOM event.
  2461. *
  2462. * @typedef {CustomEvent} Event
  2463. * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent}
  2464. */
  2465. /**
  2466. * All event listeners should follow the following format.
  2467. *
  2468. * @callback EventTarget~EventListener
  2469. * @this {EventTarget}
  2470. *
  2471. * @param {Event} event
  2472. * the event that triggered this function
  2473. *
  2474. * @param {Object} [hash]
  2475. * hash of data sent during the event
  2476. */
  2477. /**
  2478. * An object containing event names as keys and booleans as values.
  2479. *
  2480. * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger}
  2481. * will have extra functionality. See that function for more information.
  2482. *
  2483. * @property EventTarget.prototype.allowedEvents_
  2484. * @private
  2485. */
  2486. EventTarget$2.prototype.allowedEvents_ = {};
  2487. /**
  2488. * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic
  2489. * the standard DOM API.
  2490. *
  2491. * @function
  2492. * @see {@link EventTarget#on}
  2493. */
  2494. EventTarget$2.prototype.addEventListener = EventTarget$2.prototype.on;
  2495. /**
  2496. * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic
  2497. * the standard DOM API.
  2498. *
  2499. * @function
  2500. * @see {@link EventTarget#off}
  2501. */
  2502. EventTarget$2.prototype.removeEventListener = EventTarget$2.prototype.off;
  2503. /**
  2504. * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic
  2505. * the standard DOM API.
  2506. *
  2507. * @function
  2508. * @see {@link EventTarget#trigger}
  2509. */
  2510. EventTarget$2.prototype.dispatchEvent = EventTarget$2.prototype.trigger;
  2511. /**
  2512. * @file mixins/evented.js
  2513. * @module evented
  2514. */
  2515. const objName = obj => {
  2516. if (typeof obj.name === 'function') {
  2517. return obj.name();
  2518. }
  2519. if (typeof obj.name === 'string') {
  2520. return obj.name;
  2521. }
  2522. if (obj.name_) {
  2523. return obj.name_;
  2524. }
  2525. if (obj.constructor && obj.constructor.name) {
  2526. return obj.constructor.name;
  2527. }
  2528. return typeof obj;
  2529. };
  2530. /**
  2531. * Returns whether or not an object has had the evented mixin applied.
  2532. *
  2533. * @param {Object} object
  2534. * An object to test.
  2535. *
  2536. * @return {boolean}
  2537. * Whether or not the object appears to be evented.
  2538. */
  2539. const isEvented = object => object instanceof EventTarget$2 || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(k => typeof object[k] === 'function');
  2540. /**
  2541. * Adds a callback to run after the evented mixin applied.
  2542. *
  2543. * @param {Object} object
  2544. * An object to Add
  2545. * @param {Function} callback
  2546. * The callback to run.
  2547. */
  2548. const addEventedCallback = (target, callback) => {
  2549. if (isEvented(target)) {
  2550. callback();
  2551. } else {
  2552. if (!target.eventedCallbacks) {
  2553. target.eventedCallbacks = [];
  2554. }
  2555. target.eventedCallbacks.push(callback);
  2556. }
  2557. };
  2558. /**
  2559. * Whether a value is a valid event type - non-empty string or array.
  2560. *
  2561. * @private
  2562. * @param {string|Array} type
  2563. * The type value to test.
  2564. *
  2565. * @return {boolean}
  2566. * Whether or not the type is a valid event type.
  2567. */
  2568. const isValidEventType = type =>
  2569. // The regex here verifies that the `type` contains at least one non-
  2570. // whitespace character.
  2571. typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length;
  2572. /**
  2573. * Validates a value to determine if it is a valid event target. Throws if not.
  2574. *
  2575. * @private
  2576. * @throws {Error}
  2577. * If the target does not appear to be a valid event target.
  2578. *
  2579. * @param {Object} target
  2580. * The object to test.
  2581. *
  2582. * @param {Object} obj
  2583. * The evented object we are validating for
  2584. *
  2585. * @param {string} fnName
  2586. * The name of the evented mixin function that called this.
  2587. */
  2588. const validateTarget = (target, obj, fnName) => {
  2589. if (!target || !target.nodeName && !isEvented(target)) {
  2590. throw new Error(`Invalid target for ${objName(obj)}#${fnName}; must be a DOM node or evented object.`);
  2591. }
  2592. };
  2593. /**
  2594. * Validates a value to determine if it is a valid event target. Throws if not.
  2595. *
  2596. * @private
  2597. * @throws {Error}
  2598. * If the type does not appear to be a valid event type.
  2599. *
  2600. * @param {string|Array} type
  2601. * The type to test.
  2602. *
  2603. * @param {Object} obj
  2604. * The evented object we are validating for
  2605. *
  2606. * @param {string} fnName
  2607. * The name of the evented mixin function that called this.
  2608. */
  2609. const validateEventType = (type, obj, fnName) => {
  2610. if (!isValidEventType(type)) {
  2611. throw new Error(`Invalid event type for ${objName(obj)}#${fnName}; must be a non-empty string or array.`);
  2612. }
  2613. };
  2614. /**
  2615. * Validates a value to determine if it is a valid listener. Throws if not.
  2616. *
  2617. * @private
  2618. * @throws {Error}
  2619. * If the listener is not a function.
  2620. *
  2621. * @param {Function} listener
  2622. * The listener to test.
  2623. *
  2624. * @param {Object} obj
  2625. * The evented object we are validating for
  2626. *
  2627. * @param {string} fnName
  2628. * The name of the evented mixin function that called this.
  2629. */
  2630. const validateListener = (listener, obj, fnName) => {
  2631. if (typeof listener !== 'function') {
  2632. throw new Error(`Invalid listener for ${objName(obj)}#${fnName}; must be a function.`);
  2633. }
  2634. };
  2635. /**
  2636. * Takes an array of arguments given to `on()` or `one()`, validates them, and
  2637. * normalizes them into an object.
  2638. *
  2639. * @private
  2640. * @param {Object} self
  2641. * The evented object on which `on()` or `one()` was called. This
  2642. * object will be bound as the `this` value for the listener.
  2643. *
  2644. * @param {Array} args
  2645. * An array of arguments passed to `on()` or `one()`.
  2646. *
  2647. * @param {string} fnName
  2648. * The name of the evented mixin function that called this.
  2649. *
  2650. * @return {Object}
  2651. * An object containing useful values for `on()` or `one()` calls.
  2652. */
  2653. const normalizeListenArgs = (self, args, fnName) => {
  2654. // If the number of arguments is less than 3, the target is always the
  2655. // evented object itself.
  2656. const isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_;
  2657. let target;
  2658. let type;
  2659. let listener;
  2660. if (isTargetingSelf) {
  2661. target = self.eventBusEl_;
  2662. // Deal with cases where we got 3 arguments, but we are still listening to
  2663. // the evented object itself.
  2664. if (args.length >= 3) {
  2665. args.shift();
  2666. }
  2667. [type, listener] = args;
  2668. } else {
  2669. [target, type, listener] = args;
  2670. }
  2671. validateTarget(target, self, fnName);
  2672. validateEventType(type, self, fnName);
  2673. validateListener(listener, self, fnName);
  2674. listener = bind_(self, listener);
  2675. return {
  2676. isTargetingSelf,
  2677. target,
  2678. type,
  2679. listener
  2680. };
  2681. };
  2682. /**
  2683. * Adds the listener to the event type(s) on the target, normalizing for
  2684. * the type of target.
  2685. *
  2686. * @private
  2687. * @param {Element|Object} target
  2688. * A DOM node or evented object.
  2689. *
  2690. * @param {string} method
  2691. * The event binding method to use ("on" or "one").
  2692. *
  2693. * @param {string|Array} type
  2694. * One or more event type(s).
  2695. *
  2696. * @param {Function} listener
  2697. * A listener function.
  2698. */
  2699. const listen = (target, method, type, listener) => {
  2700. validateTarget(target, target, method);
  2701. if (target.nodeName) {
  2702. Events[method](target, type, listener);
  2703. } else {
  2704. target[method](type, listener);
  2705. }
  2706. };
  2707. /**
  2708. * Contains methods that provide event capabilities to an object which is passed
  2709. * to {@link module:evented|evented}.
  2710. *
  2711. * @mixin EventedMixin
  2712. */
  2713. const EventedMixin = {
  2714. /**
  2715. * Add a listener to an event (or events) on this object or another evented
  2716. * object.
  2717. *
  2718. * @param {string|Array|Element|Object} targetOrType
  2719. * If this is a string or array, it represents the event type(s)
  2720. * that will trigger the listener.
  2721. *
  2722. * Another evented object can be passed here instead, which will
  2723. * cause the listener to listen for events on _that_ object.
  2724. *
  2725. * In either case, the listener's `this` value will be bound to
  2726. * this object.
  2727. *
  2728. * @param {string|Array|Function} typeOrListener
  2729. * If the first argument was a string or array, this should be the
  2730. * listener function. Otherwise, this is a string or array of event
  2731. * type(s).
  2732. *
  2733. * @param {Function} [listener]
  2734. * If the first argument was another evented object, this will be
  2735. * the listener function.
  2736. */
  2737. on(...args) {
  2738. const {
  2739. isTargetingSelf,
  2740. target,
  2741. type,
  2742. listener
  2743. } = normalizeListenArgs(this, args, 'on');
  2744. listen(target, 'on', type, listener);
  2745. // If this object is listening to another evented object.
  2746. if (!isTargetingSelf) {
  2747. // If this object is disposed, remove the listener.
  2748. const removeListenerOnDispose = () => this.off(target, type, listener);
  2749. // Use the same function ID as the listener so we can remove it later it
  2750. // using the ID of the original listener.
  2751. removeListenerOnDispose.guid = listener.guid;
  2752. // Add a listener to the target's dispose event as well. This ensures
  2753. // that if the target is disposed BEFORE this object, we remove the
  2754. // removal listener that was just added. Otherwise, we create a memory leak.
  2755. const removeRemoverOnTargetDispose = () => this.off('dispose', removeListenerOnDispose);
  2756. // Use the same function ID as the listener so we can remove it later
  2757. // it using the ID of the original listener.
  2758. removeRemoverOnTargetDispose.guid = listener.guid;
  2759. listen(this, 'on', 'dispose', removeListenerOnDispose);
  2760. listen(target, 'on', 'dispose', removeRemoverOnTargetDispose);
  2761. }
  2762. },
  2763. /**
  2764. * Add a listener to an event (or events) on this object or another evented
  2765. * object. The listener will be called once per event and then removed.
  2766. *
  2767. * @param {string|Array|Element|Object} targetOrType
  2768. * If this is a string or array, it represents the event type(s)
  2769. * that will trigger the listener.
  2770. *
  2771. * Another evented object can be passed here instead, which will
  2772. * cause the listener to listen for events on _that_ object.
  2773. *
  2774. * In either case, the listener's `this` value will be bound to
  2775. * this object.
  2776. *
  2777. * @param {string|Array|Function} typeOrListener
  2778. * If the first argument was a string or array, this should be the
  2779. * listener function. Otherwise, this is a string or array of event
  2780. * type(s).
  2781. *
  2782. * @param {Function} [listener]
  2783. * If the first argument was another evented object, this will be
  2784. * the listener function.
  2785. */
  2786. one(...args) {
  2787. const {
  2788. isTargetingSelf,
  2789. target,
  2790. type,
  2791. listener
  2792. } = normalizeListenArgs(this, args, 'one');
  2793. // Targeting this evented object.
  2794. if (isTargetingSelf) {
  2795. listen(target, 'one', type, listener);
  2796. // Targeting another evented object.
  2797. } else {
  2798. // TODO: This wrapper is incorrect! It should only
  2799. // remove the wrapper for the event type that called it.
  2800. // Instead all listeners are removed on the first trigger!
  2801. // see https://github.com/videojs/video.js/issues/5962
  2802. const wrapper = (...largs) => {
  2803. this.off(target, type, wrapper);
  2804. listener.apply(null, largs);
  2805. };
  2806. // Use the same function ID as the listener so we can remove it later
  2807. // it using the ID of the original listener.
  2808. wrapper.guid = listener.guid;
  2809. listen(target, 'one', type, wrapper);
  2810. }
  2811. },
  2812. /**
  2813. * Add a listener to an event (or events) on this object or another evented
  2814. * object. The listener will only be called once for the first event that is triggered
  2815. * then removed.
  2816. *
  2817. * @param {string|Array|Element|Object} targetOrType
  2818. * If this is a string or array, it represents the event type(s)
  2819. * that will trigger the listener.
  2820. *
  2821. * Another evented object can be passed here instead, which will
  2822. * cause the listener to listen for events on _that_ object.
  2823. *
  2824. * In either case, the listener's `this` value will be bound to
  2825. * this object.
  2826. *
  2827. * @param {string|Array|Function} typeOrListener
  2828. * If the first argument was a string or array, this should be the
  2829. * listener function. Otherwise, this is a string or array of event
  2830. * type(s).
  2831. *
  2832. * @param {Function} [listener]
  2833. * If the first argument was another evented object, this will be
  2834. * the listener function.
  2835. */
  2836. any(...args) {
  2837. const {
  2838. isTargetingSelf,
  2839. target,
  2840. type,
  2841. listener
  2842. } = normalizeListenArgs(this, args, 'any');
  2843. // Targeting this evented object.
  2844. if (isTargetingSelf) {
  2845. listen(target, 'any', type, listener);
  2846. // Targeting another evented object.
  2847. } else {
  2848. const wrapper = (...largs) => {
  2849. this.off(target, type, wrapper);
  2850. listener.apply(null, largs);
  2851. };
  2852. // Use the same function ID as the listener so we can remove it later
  2853. // it using the ID of the original listener.
  2854. wrapper.guid = listener.guid;
  2855. listen(target, 'any', type, wrapper);
  2856. }
  2857. },
  2858. /**
  2859. * Removes listener(s) from event(s) on an evented object.
  2860. *
  2861. * @param {string|Array|Element|Object} [targetOrType]
  2862. * If this is a string or array, it represents the event type(s).
  2863. *
  2864. * Another evented object can be passed here instead, in which case
  2865. * ALL 3 arguments are _required_.
  2866. *
  2867. * @param {string|Array|Function} [typeOrListener]
  2868. * If the first argument was a string or array, this may be the
  2869. * listener function. Otherwise, this is a string or array of event
  2870. * type(s).
  2871. *
  2872. * @param {Function} [listener]
  2873. * If the first argument was another evented object, this will be
  2874. * the listener function; otherwise, _all_ listeners bound to the
  2875. * event type(s) will be removed.
  2876. */
  2877. off(targetOrType, typeOrListener, listener) {
  2878. // Targeting this evented object.
  2879. if (!targetOrType || isValidEventType(targetOrType)) {
  2880. off(this.eventBusEl_, targetOrType, typeOrListener);
  2881. // Targeting another evented object.
  2882. } else {
  2883. const target = targetOrType;
  2884. const type = typeOrListener;
  2885. // Fail fast and in a meaningful way!
  2886. validateTarget(target, this, 'off');
  2887. validateEventType(type, this, 'off');
  2888. validateListener(listener, this, 'off');
  2889. // Ensure there's at least a guid, even if the function hasn't been used
  2890. listener = bind_(this, listener);
  2891. // Remove the dispose listener on this evented object, which was given
  2892. // the same guid as the event listener in on().
  2893. this.off('dispose', listener);
  2894. if (target.nodeName) {
  2895. off(target, type, listener);
  2896. off(target, 'dispose', listener);
  2897. } else if (isEvented(target)) {
  2898. target.off(type, listener);
  2899. target.off('dispose', listener);
  2900. }
  2901. }
  2902. },
  2903. /**
  2904. * Fire an event on this evented object, causing its listeners to be called.
  2905. *
  2906. * @param {string|Object} event
  2907. * An event type or an object with a type property.
  2908. *
  2909. * @param {Object} [hash]
  2910. * An additional object to pass along to listeners.
  2911. *
  2912. * @return {boolean}
  2913. * Whether or not the default behavior was prevented.
  2914. */
  2915. trigger(event, hash) {
  2916. validateTarget(this.eventBusEl_, this, 'trigger');
  2917. const type = event && typeof event !== 'string' ? event.type : event;
  2918. if (!isValidEventType(type)) {
  2919. 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.');
  2920. }
  2921. return trigger(this.eventBusEl_, event, hash);
  2922. }
  2923. };
  2924. /**
  2925. * Applies {@link module:evented~EventedMixin|EventedMixin} to a target object.
  2926. *
  2927. * @param {Object} target
  2928. * The object to which to add event methods.
  2929. *
  2930. * @param {Object} [options={}]
  2931. * Options for customizing the mixin behavior.
  2932. *
  2933. * @param {string} [options.eventBusKey]
  2934. * By default, adds a `eventBusEl_` DOM element to the target object,
  2935. * which is used as an event bus. If the target object already has a
  2936. * DOM element that should be used, pass its key here.
  2937. *
  2938. * @return {Object}
  2939. * The target object.
  2940. */
  2941. function evented(target, options = {}) {
  2942. const {
  2943. eventBusKey
  2944. } = options;
  2945. // Set or create the eventBusEl_.
  2946. if (eventBusKey) {
  2947. if (!target[eventBusKey].nodeName) {
  2948. throw new Error(`The eventBusKey "${eventBusKey}" does not refer to an element.`);
  2949. }
  2950. target.eventBusEl_ = target[eventBusKey];
  2951. } else {
  2952. target.eventBusEl_ = createEl('span', {
  2953. className: 'vjs-event-bus'
  2954. });
  2955. }
  2956. Object.assign(target, EventedMixin);
  2957. if (target.eventedCallbacks) {
  2958. target.eventedCallbacks.forEach(callback => {
  2959. callback();
  2960. });
  2961. }
  2962. // When any evented object is disposed, it removes all its listeners.
  2963. target.on('dispose', () => {
  2964. target.off();
  2965. [target, target.el_, target.eventBusEl_].forEach(function (val) {
  2966. if (val && DomData.has(val)) {
  2967. DomData.delete(val);
  2968. }
  2969. });
  2970. window$1.setTimeout(() => {
  2971. target.eventBusEl_ = null;
  2972. }, 0);
  2973. });
  2974. return target;
  2975. }
  2976. /**
  2977. * @file mixins/stateful.js
  2978. * @module stateful
  2979. */
  2980. /**
  2981. * Contains methods that provide statefulness to an object which is passed
  2982. * to {@link module:stateful}.
  2983. *
  2984. * @mixin StatefulMixin
  2985. */
  2986. const StatefulMixin = {
  2987. /**
  2988. * A hash containing arbitrary keys and values representing the state of
  2989. * the object.
  2990. *
  2991. * @type {Object}
  2992. */
  2993. state: {},
  2994. /**
  2995. * Set the state of an object by mutating its
  2996. * {@link module:stateful~StatefulMixin.state|state} object in place.
  2997. *
  2998. * @fires module:stateful~StatefulMixin#statechanged
  2999. * @param {Object|Function} stateUpdates
  3000. * A new set of properties to shallow-merge into the plugin state.
  3001. * Can be a plain object or a function returning a plain object.
  3002. *
  3003. * @return {Object|undefined}
  3004. * An object containing changes that occurred. If no changes
  3005. * occurred, returns `undefined`.
  3006. */
  3007. setState(stateUpdates) {
  3008. // Support providing the `stateUpdates` state as a function.
  3009. if (typeof stateUpdates === 'function') {
  3010. stateUpdates = stateUpdates();
  3011. }
  3012. let changes;
  3013. each(stateUpdates, (value, key) => {
  3014. // Record the change if the value is different from what's in the
  3015. // current state.
  3016. if (this.state[key] !== value) {
  3017. changes = changes || {};
  3018. changes[key] = {
  3019. from: this.state[key],
  3020. to: value
  3021. };
  3022. }
  3023. this.state[key] = value;
  3024. });
  3025. // Only trigger "statechange" if there were changes AND we have a trigger
  3026. // function. This allows us to not require that the target object be an
  3027. // evented object.
  3028. if (changes && isEvented(this)) {
  3029. /**
  3030. * An event triggered on an object that is both
  3031. * {@link module:stateful|stateful} and {@link module:evented|evented}
  3032. * indicating that its state has changed.
  3033. *
  3034. * @event module:stateful~StatefulMixin#statechanged
  3035. * @type {Object}
  3036. * @property {Object} changes
  3037. * A hash containing the properties that were changed and
  3038. * the values they were changed `from` and `to`.
  3039. */
  3040. this.trigger({
  3041. changes,
  3042. type: 'statechanged'
  3043. });
  3044. }
  3045. return changes;
  3046. }
  3047. };
  3048. /**
  3049. * Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target
  3050. * object.
  3051. *
  3052. * If the target object is {@link module:evented|evented} and has a
  3053. * `handleStateChanged` method, that method will be automatically bound to the
  3054. * `statechanged` event on itself.
  3055. *
  3056. * @param {Object} target
  3057. * The object to be made stateful.
  3058. *
  3059. * @param {Object} [defaultState]
  3060. * A default set of properties to populate the newly-stateful object's
  3061. * `state` property.
  3062. *
  3063. * @return {Object}
  3064. * Returns the `target`.
  3065. */
  3066. function stateful(target, defaultState) {
  3067. Object.assign(target, StatefulMixin);
  3068. // This happens after the mixing-in because we need to replace the `state`
  3069. // added in that step.
  3070. target.state = Object.assign({}, target.state, defaultState);
  3071. // Auto-bind the `handleStateChanged` method of the target object if it exists.
  3072. if (typeof target.handleStateChanged === 'function' && isEvented(target)) {
  3073. target.on('statechanged', target.handleStateChanged);
  3074. }
  3075. return target;
  3076. }
  3077. /**
  3078. * @file str.js
  3079. * @module to-lower-case
  3080. */
  3081. /**
  3082. * Lowercase the first letter of a string.
  3083. *
  3084. * @param {string} string
  3085. * String to be lowercased
  3086. *
  3087. * @return {string}
  3088. * The string with a lowercased first letter
  3089. */
  3090. const toLowerCase = function (string) {
  3091. if (typeof string !== 'string') {
  3092. return string;
  3093. }
  3094. return string.replace(/./, w => w.toLowerCase());
  3095. };
  3096. /**
  3097. * Uppercase the first letter of a string.
  3098. *
  3099. * @param {string} string
  3100. * String to be uppercased
  3101. *
  3102. * @return {string}
  3103. * The string with an uppercased first letter
  3104. */
  3105. const toTitleCase$1 = function (string) {
  3106. if (typeof string !== 'string') {
  3107. return string;
  3108. }
  3109. return string.replace(/./, w => w.toUpperCase());
  3110. };
  3111. /**
  3112. * Compares the TitleCase versions of the two strings for equality.
  3113. *
  3114. * @param {string} str1
  3115. * The first string to compare
  3116. *
  3117. * @param {string} str2
  3118. * The second string to compare
  3119. *
  3120. * @return {boolean}
  3121. * Whether the TitleCase versions of the strings are equal
  3122. */
  3123. const titleCaseEquals = function (str1, str2) {
  3124. return toTitleCase$1(str1) === toTitleCase$1(str2);
  3125. };
  3126. var Str = /*#__PURE__*/Object.freeze({
  3127. __proto__: null,
  3128. toLowerCase: toLowerCase,
  3129. toTitleCase: toTitleCase$1,
  3130. titleCaseEquals: titleCaseEquals
  3131. });
  3132. /**
  3133. * Player Component - Base class for all UI objects
  3134. *
  3135. * @file component.js
  3136. */
  3137. /**
  3138. * Base class for all UI Components.
  3139. * Components are UI objects which represent both a javascript object and an element
  3140. * in the DOM. They can be children of other components, and can have
  3141. * children themselves.
  3142. *
  3143. * Components can also use methods from {@link EventTarget}
  3144. */
  3145. class Component$1 {
  3146. /**
  3147. * A callback that is called when a component is ready. Does not have any
  3148. * parameters and any callback value will be ignored.
  3149. *
  3150. * @callback ReadyCallback
  3151. * @this Component
  3152. */
  3153. /**
  3154. * Creates an instance of this class.
  3155. *
  3156. * @param { import('./player').default } player
  3157. * The `Player` that this class should be attached to.
  3158. *
  3159. * @param {Object} [options]
  3160. * The key/value store of component options.
  3161. *
  3162. * @param {Object[]} [options.children]
  3163. * An array of children objects to initialize this component with. Children objects have
  3164. * a name property that will be used if more than one component of the same type needs to be
  3165. * added.
  3166. *
  3167. * @param {string} [options.className]
  3168. * A class or space separated list of classes to add the component
  3169. *
  3170. * @param {ReadyCallback} [ready]
  3171. * Function that gets called when the `Component` is ready.
  3172. */
  3173. constructor(player, options, ready) {
  3174. // The component might be the player itself and we can't pass `this` to super
  3175. if (!player && this.play) {
  3176. this.player_ = player = this; // eslint-disable-line
  3177. } else {
  3178. this.player_ = player;
  3179. }
  3180. this.isDisposed_ = false;
  3181. // Hold the reference to the parent component via `addChild` method
  3182. this.parentComponent_ = null;
  3183. // Make a copy of prototype.options_ to protect against overriding defaults
  3184. this.options_ = merge$1({}, this.options_);
  3185. // Updated options with supplied options
  3186. options = this.options_ = merge$1(this.options_, options);
  3187. // Get ID from options or options element if one is supplied
  3188. this.id_ = options.id || options.el && options.el.id;
  3189. // If there was no ID from the options, generate one
  3190. if (!this.id_) {
  3191. // Don't require the player ID function in the case of mock players
  3192. const id = player && player.id && player.id() || 'no_player';
  3193. this.id_ = `${id}_component_${newGUID()}`;
  3194. }
  3195. this.name_ = options.name || null;
  3196. // Create element if one wasn't provided in options
  3197. if (options.el) {
  3198. this.el_ = options.el;
  3199. } else if (options.createEl !== false) {
  3200. this.el_ = this.createEl();
  3201. }
  3202. if (options.className && this.el_) {
  3203. options.className.split(' ').forEach(c => this.addClass(c));
  3204. }
  3205. // Remove the placeholder event methods. If the component is evented, the
  3206. // real methods are added next
  3207. ['on', 'off', 'one', 'any', 'trigger'].forEach(fn => {
  3208. this[fn] = undefined;
  3209. });
  3210. // if evented is anything except false, we want to mixin in evented
  3211. if (options.evented !== false) {
  3212. // Make this an evented object and use `el_`, if available, as its event bus
  3213. evented(this, {
  3214. eventBusKey: this.el_ ? 'el_' : null
  3215. });
  3216. this.handleLanguagechange = this.handleLanguagechange.bind(this);
  3217. this.on(this.player_, 'languagechange', this.handleLanguagechange);
  3218. }
  3219. stateful(this, this.constructor.defaultState);
  3220. this.children_ = [];
  3221. this.childIndex_ = {};
  3222. this.childNameIndex_ = {};
  3223. this.setTimeoutIds_ = new Set();
  3224. this.setIntervalIds_ = new Set();
  3225. this.rafIds_ = new Set();
  3226. this.namedRafs_ = new Map();
  3227. this.clearingTimersOnDispose_ = false;
  3228. // Add any child components in options
  3229. if (options.initChildren !== false) {
  3230. this.initChildren();
  3231. }
  3232. // Don't want to trigger ready here or it will go before init is actually
  3233. // finished for all children that run this constructor
  3234. this.ready(ready);
  3235. if (options.reportTouchActivity !== false) {
  3236. this.enableTouchActivity();
  3237. }
  3238. }
  3239. // `on`, `off`, `one`, `any` and `trigger` are here so tsc includes them in definitions.
  3240. // They are replaced or removed in the constructor
  3241. /**
  3242. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  3243. * function that will get called when an event with a certain name gets triggered.
  3244. *
  3245. * @param {string|string[]} type
  3246. * An event name or an array of event names.
  3247. *
  3248. * @param {Function} fn
  3249. * The function to call with `EventTarget`s
  3250. */
  3251. on(type, fn) {}
  3252. /**
  3253. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  3254. * This makes it so that the `event listener` will no longer get called when the
  3255. * named event happens.
  3256. *
  3257. * @param {string|string[]} type
  3258. * An event name or an array of event names.
  3259. *
  3260. * @param {Function} fn
  3261. * The function to remove.
  3262. */
  3263. off(type, fn) {}
  3264. /**
  3265. * This function will add an `event listener` that gets triggered only once. After the
  3266. * first trigger it will get removed. This is like adding an `event listener`
  3267. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  3268. *
  3269. * @param {string|string[]} type
  3270. * An event name or an array of event names.
  3271. *
  3272. * @param {Function} fn
  3273. * The function to be called once for each event name.
  3274. */
  3275. one(type, fn) {}
  3276. /**
  3277. * This function will add an `event listener` that gets triggered only once and is
  3278. * removed from all events. This is like adding an array of `event listener`s
  3279. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  3280. * first time it is triggered.
  3281. *
  3282. * @param {string|string[]} type
  3283. * An event name or an array of event names.
  3284. *
  3285. * @param {Function} fn
  3286. * The function to be called once for each event name.
  3287. */
  3288. any(type, fn) {}
  3289. /**
  3290. * This function causes an event to happen. This will then cause any `event listeners`
  3291. * that are waiting for that event, to get called. If there are no `event listeners`
  3292. * for an event then nothing will happen.
  3293. *
  3294. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  3295. * Trigger will also call the `on` + `uppercaseEventName` function.
  3296. *
  3297. * Example:
  3298. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  3299. * `onClick` if it exists.
  3300. *
  3301. * @param {string|Event|Object} event
  3302. * The name of the event, an `Event`, or an object with a key of type set to
  3303. * an event name.
  3304. */
  3305. trigger(event) {}
  3306. /**
  3307. * Dispose of the `Component` and all child components.
  3308. *
  3309. * @fires Component#dispose
  3310. *
  3311. * @param {Object} options
  3312. * @param {Element} options.originalEl element with which to replace player element
  3313. */
  3314. dispose(options = {}) {
  3315. // Bail out if the component has already been disposed.
  3316. if (this.isDisposed_) {
  3317. return;
  3318. }
  3319. if (this.readyQueue_) {
  3320. this.readyQueue_.length = 0;
  3321. }
  3322. /**
  3323. * Triggered when a `Component` is disposed.
  3324. *
  3325. * @event Component#dispose
  3326. * @type {Event}
  3327. *
  3328. * @property {boolean} [bubbles=false]
  3329. * set to false so that the dispose event does not
  3330. * bubble up
  3331. */
  3332. this.trigger({
  3333. type: 'dispose',
  3334. bubbles: false
  3335. });
  3336. this.isDisposed_ = true;
  3337. // Dispose all children.
  3338. if (this.children_) {
  3339. for (let i = this.children_.length - 1; i >= 0; i--) {
  3340. if (this.children_[i].dispose) {
  3341. this.children_[i].dispose();
  3342. }
  3343. }
  3344. }
  3345. // Delete child references
  3346. this.children_ = null;
  3347. this.childIndex_ = null;
  3348. this.childNameIndex_ = null;
  3349. this.parentComponent_ = null;
  3350. if (this.el_) {
  3351. // Remove element from DOM
  3352. if (this.el_.parentNode) {
  3353. if (options.restoreEl) {
  3354. this.el_.parentNode.replaceChild(options.restoreEl, this.el_);
  3355. } else {
  3356. this.el_.parentNode.removeChild(this.el_);
  3357. }
  3358. }
  3359. this.el_ = null;
  3360. }
  3361. // remove reference to the player after disposing of the element
  3362. this.player_ = null;
  3363. }
  3364. /**
  3365. * Determine whether or not this component has been disposed.
  3366. *
  3367. * @return {boolean}
  3368. * If the component has been disposed, will be `true`. Otherwise, `false`.
  3369. */
  3370. isDisposed() {
  3371. return Boolean(this.isDisposed_);
  3372. }
  3373. /**
  3374. * Return the {@link Player} that the `Component` has attached to.
  3375. *
  3376. * @return { import('./player').default }
  3377. * The player that this `Component` has attached to.
  3378. */
  3379. player() {
  3380. return this.player_;
  3381. }
  3382. /**
  3383. * Deep merge of options objects with new options.
  3384. * > Note: When both `obj` and `options` contain properties whose values are objects.
  3385. * The two properties get merged using {@link module:obj.merge}
  3386. *
  3387. * @param {Object} obj
  3388. * The object that contains new options.
  3389. *
  3390. * @return {Object}
  3391. * A new object of `this.options_` and `obj` merged together.
  3392. */
  3393. options(obj) {
  3394. if (!obj) {
  3395. return this.options_;
  3396. }
  3397. this.options_ = merge$1(this.options_, obj);
  3398. return this.options_;
  3399. }
  3400. /**
  3401. * Get the `Component`s DOM element
  3402. *
  3403. * @return {Element}
  3404. * The DOM element for this `Component`.
  3405. */
  3406. el() {
  3407. return this.el_;
  3408. }
  3409. /**
  3410. * Create the `Component`s DOM element.
  3411. *
  3412. * @param {string} [tagName]
  3413. * Element's DOM node type. e.g. 'div'
  3414. *
  3415. * @param {Object} [properties]
  3416. * An object of properties that should be set.
  3417. *
  3418. * @param {Object} [attributes]
  3419. * An object of attributes that should be set.
  3420. *
  3421. * @return {Element}
  3422. * The element that gets created.
  3423. */
  3424. createEl(tagName, properties, attributes) {
  3425. return createEl(tagName, properties, attributes);
  3426. }
  3427. /**
  3428. * Localize a string given the string in english.
  3429. *
  3430. * If tokens are provided, it'll try and run a simple token replacement on the provided string.
  3431. * The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.
  3432. *
  3433. * If a `defaultValue` is provided, it'll use that over `string`,
  3434. * if a value isn't found in provided language files.
  3435. * This is useful if you want to have a descriptive key for token replacement
  3436. * but have a succinct localized string and not require `en.json` to be included.
  3437. *
  3438. * Currently, it is used for the progress bar timing.
  3439. * ```js
  3440. * {
  3441. * "progress bar timing: currentTime={1} duration={2}": "{1} of {2}"
  3442. * }
  3443. * ```
  3444. * It is then used like so:
  3445. * ```js
  3446. * this.localize('progress bar timing: currentTime={1} duration{2}',
  3447. * [this.player_.currentTime(), this.player_.duration()],
  3448. * '{1} of {2}');
  3449. * ```
  3450. *
  3451. * Which outputs something like: `01:23 of 24:56`.
  3452. *
  3453. *
  3454. * @param {string} string
  3455. * The string to localize and the key to lookup in the language files.
  3456. * @param {string[]} [tokens]
  3457. * If the current item has token replacements, provide the tokens here.
  3458. * @param {string} [defaultValue]
  3459. * Defaults to `string`. Can be a default value to use for token replacement
  3460. * if the lookup key is needed to be separate.
  3461. *
  3462. * @return {string}
  3463. * The localized string or if no localization exists the english string.
  3464. */
  3465. localize(string, tokens, defaultValue = string) {
  3466. const code = this.player_.language && this.player_.language();
  3467. const languages = this.player_.languages && this.player_.languages();
  3468. const language = languages && languages[code];
  3469. const primaryCode = code && code.split('-')[0];
  3470. const primaryLang = languages && languages[primaryCode];
  3471. let localizedString = defaultValue;
  3472. if (language && language[string]) {
  3473. localizedString = language[string];
  3474. } else if (primaryLang && primaryLang[string]) {
  3475. localizedString = primaryLang[string];
  3476. }
  3477. if (tokens) {
  3478. localizedString = localizedString.replace(/\{(\d+)\}/g, function (match, index) {
  3479. const value = tokens[index - 1];
  3480. let ret = value;
  3481. if (typeof value === 'undefined') {
  3482. ret = match;
  3483. }
  3484. return ret;
  3485. });
  3486. }
  3487. return localizedString;
  3488. }
  3489. /**
  3490. * Handles language change for the player in components. Should be overridden by sub-components.
  3491. *
  3492. * @abstract
  3493. */
  3494. handleLanguagechange() {}
  3495. /**
  3496. * Return the `Component`s DOM element. This is where children get inserted.
  3497. * This will usually be the the same as the element returned in {@link Component#el}.
  3498. *
  3499. * @return {Element}
  3500. * The content element for this `Component`.
  3501. */
  3502. contentEl() {
  3503. return this.contentEl_ || this.el_;
  3504. }
  3505. /**
  3506. * Get this `Component`s ID
  3507. *
  3508. * @return {string}
  3509. * The id of this `Component`
  3510. */
  3511. id() {
  3512. return this.id_;
  3513. }
  3514. /**
  3515. * Get the `Component`s name. The name gets used to reference the `Component`
  3516. * and is set during registration.
  3517. *
  3518. * @return {string}
  3519. * The name of this `Component`.
  3520. */
  3521. name() {
  3522. return this.name_;
  3523. }
  3524. /**
  3525. * Get an array of all child components
  3526. *
  3527. * @return {Array}
  3528. * The children
  3529. */
  3530. children() {
  3531. return this.children_;
  3532. }
  3533. /**
  3534. * Returns the child `Component` with the given `id`.
  3535. *
  3536. * @param {string} id
  3537. * The id of the child `Component` to get.
  3538. *
  3539. * @return {Component|undefined}
  3540. * The child `Component` with the given `id` or undefined.
  3541. */
  3542. getChildById(id) {
  3543. return this.childIndex_[id];
  3544. }
  3545. /**
  3546. * Returns the child `Component` with the given `name`.
  3547. *
  3548. * @param {string} name
  3549. * The name of the child `Component` to get.
  3550. *
  3551. * @return {Component|undefined}
  3552. * The child `Component` with the given `name` or undefined.
  3553. */
  3554. getChild(name) {
  3555. if (!name) {
  3556. return;
  3557. }
  3558. return this.childNameIndex_[name];
  3559. }
  3560. /**
  3561. * Returns the descendant `Component` following the givent
  3562. * descendant `names`. For instance ['foo', 'bar', 'baz'] would
  3563. * try to get 'foo' on the current component, 'bar' on the 'foo'
  3564. * component and 'baz' on the 'bar' component and return undefined
  3565. * if any of those don't exist.
  3566. *
  3567. * @param {...string[]|...string} names
  3568. * The name of the child `Component` to get.
  3569. *
  3570. * @return {Component|undefined}
  3571. * The descendant `Component` following the given descendant
  3572. * `names` or undefined.
  3573. */
  3574. getDescendant(...names) {
  3575. // flatten array argument into the main array
  3576. names = names.reduce((acc, n) => acc.concat(n), []);
  3577. let currentChild = this;
  3578. for (let i = 0; i < names.length; i++) {
  3579. currentChild = currentChild.getChild(names[i]);
  3580. if (!currentChild || !currentChild.getChild) {
  3581. return;
  3582. }
  3583. }
  3584. return currentChild;
  3585. }
  3586. /**
  3587. * Add a child `Component` inside the current `Component`.
  3588. *
  3589. *
  3590. * @param {string|Component} child
  3591. * The name or instance of a child to add.
  3592. *
  3593. * @param {Object} [options={}]
  3594. * The key/value store of options that will get passed to children of
  3595. * the child.
  3596. *
  3597. * @param {number} [index=this.children_.length]
  3598. * The index to attempt to add a child into.
  3599. *
  3600. * @return {Component}
  3601. * The `Component` that gets added as a child. When using a string the
  3602. * `Component` will get created by this process.
  3603. */
  3604. addChild(child, options = {}, index = this.children_.length) {
  3605. let component;
  3606. let componentName;
  3607. // If child is a string, create component with options
  3608. if (typeof child === 'string') {
  3609. componentName = toTitleCase$1(child);
  3610. const componentClassName = options.componentClass || componentName;
  3611. // Set name through options
  3612. options.name = componentName;
  3613. // Create a new object & element for this controls set
  3614. // If there's no .player_, this is a player
  3615. const ComponentClass = Component$1.getComponent(componentClassName);
  3616. if (!ComponentClass) {
  3617. throw new Error(`Component ${componentClassName} does not exist`);
  3618. }
  3619. // data stored directly on the videojs object may be
  3620. // misidentified as a component to retain
  3621. // backwards-compatibility with 4.x. check to make sure the
  3622. // component class can be instantiated.
  3623. if (typeof ComponentClass !== 'function') {
  3624. return null;
  3625. }
  3626. component = new ComponentClass(this.player_ || this, options);
  3627. // child is a component instance
  3628. } else {
  3629. component = child;
  3630. }
  3631. if (component.parentComponent_) {
  3632. component.parentComponent_.removeChild(component);
  3633. }
  3634. this.children_.splice(index, 0, component);
  3635. component.parentComponent_ = this;
  3636. if (typeof component.id === 'function') {
  3637. this.childIndex_[component.id()] = component;
  3638. }
  3639. // If a name wasn't used to create the component, check if we can use the
  3640. // name function of the component
  3641. componentName = componentName || component.name && toTitleCase$1(component.name());
  3642. if (componentName) {
  3643. this.childNameIndex_[componentName] = component;
  3644. this.childNameIndex_[toLowerCase(componentName)] = component;
  3645. }
  3646. // Add the UI object's element to the container div (box)
  3647. // Having an element is not required
  3648. if (typeof component.el === 'function' && component.el()) {
  3649. // If inserting before a component, insert before that component's element
  3650. let refNode = null;
  3651. if (this.children_[index + 1]) {
  3652. // Most children are components, but the video tech is an HTML element
  3653. if (this.children_[index + 1].el_) {
  3654. refNode = this.children_[index + 1].el_;
  3655. } else if (isEl(this.children_[index + 1])) {
  3656. refNode = this.children_[index + 1];
  3657. }
  3658. }
  3659. this.contentEl().insertBefore(component.el(), refNode);
  3660. }
  3661. // Return so it can stored on parent object if desired.
  3662. return component;
  3663. }
  3664. /**
  3665. * Remove a child `Component` from this `Component`s list of children. Also removes
  3666. * the child `Component`s element from this `Component`s element.
  3667. *
  3668. * @param {Component} component
  3669. * The child `Component` to remove.
  3670. */
  3671. removeChild(component) {
  3672. if (typeof component === 'string') {
  3673. component = this.getChild(component);
  3674. }
  3675. if (!component || !this.children_) {
  3676. return;
  3677. }
  3678. let childFound = false;
  3679. for (let i = this.children_.length - 1; i >= 0; i--) {
  3680. if (this.children_[i] === component) {
  3681. childFound = true;
  3682. this.children_.splice(i, 1);
  3683. break;
  3684. }
  3685. }
  3686. if (!childFound) {
  3687. return;
  3688. }
  3689. component.parentComponent_ = null;
  3690. this.childIndex_[component.id()] = null;
  3691. this.childNameIndex_[toTitleCase$1(component.name())] = null;
  3692. this.childNameIndex_[toLowerCase(component.name())] = null;
  3693. const compEl = component.el();
  3694. if (compEl && compEl.parentNode === this.contentEl()) {
  3695. this.contentEl().removeChild(component.el());
  3696. }
  3697. }
  3698. /**
  3699. * Add and initialize default child `Component`s based upon options.
  3700. */
  3701. initChildren() {
  3702. const children = this.options_.children;
  3703. if (children) {
  3704. // `this` is `parent`
  3705. const parentOptions = this.options_;
  3706. const handleAdd = child => {
  3707. const name = child.name;
  3708. let opts = child.opts;
  3709. // Allow options for children to be set at the parent options
  3710. // e.g. videojs(id, { controlBar: false });
  3711. // instead of videojs(id, { children: { controlBar: false });
  3712. if (parentOptions[name] !== undefined) {
  3713. opts = parentOptions[name];
  3714. }
  3715. // Allow for disabling default components
  3716. // e.g. options['children']['posterImage'] = false
  3717. if (opts === false) {
  3718. return;
  3719. }
  3720. // Allow options to be passed as a simple boolean if no configuration
  3721. // is necessary.
  3722. if (opts === true) {
  3723. opts = {};
  3724. }
  3725. // We also want to pass the original player options
  3726. // to each component as well so they don't need to
  3727. // reach back into the player for options later.
  3728. opts.playerOptions = this.options_.playerOptions;
  3729. // Create and add the child component.
  3730. // Add a direct reference to the child by name on the parent instance.
  3731. // If two of the same component are used, different names should be supplied
  3732. // for each
  3733. const newChild = this.addChild(name, opts);
  3734. if (newChild) {
  3735. this[name] = newChild;
  3736. }
  3737. };
  3738. // Allow for an array of children details to passed in the options
  3739. let workingChildren;
  3740. const Tech = Component$1.getComponent('Tech');
  3741. if (Array.isArray(children)) {
  3742. workingChildren = children;
  3743. } else {
  3744. workingChildren = Object.keys(children);
  3745. }
  3746. workingChildren
  3747. // children that are in this.options_ but also in workingChildren would
  3748. // give us extra children we do not want. So, we want to filter them out.
  3749. .concat(Object.keys(this.options_).filter(function (child) {
  3750. return !workingChildren.some(function (wchild) {
  3751. if (typeof wchild === 'string') {
  3752. return child === wchild;
  3753. }
  3754. return child === wchild.name;
  3755. });
  3756. })).map(child => {
  3757. let name;
  3758. let opts;
  3759. if (typeof child === 'string') {
  3760. name = child;
  3761. opts = children[name] || this.options_[name] || {};
  3762. } else {
  3763. name = child.name;
  3764. opts = child;
  3765. }
  3766. return {
  3767. name,
  3768. opts
  3769. };
  3770. }).filter(child => {
  3771. // we have to make sure that child.name isn't in the techOrder since
  3772. // techs are registered as Components but can't aren't compatible
  3773. // See https://github.com/videojs/video.js/issues/2772
  3774. const c = Component$1.getComponent(child.opts.componentClass || toTitleCase$1(child.name));
  3775. return c && !Tech.isTech(c);
  3776. }).forEach(handleAdd);
  3777. }
  3778. }
  3779. /**
  3780. * Builds the default DOM class name. Should be overridden by sub-components.
  3781. *
  3782. * @return {string}
  3783. * The DOM class name for this object.
  3784. *
  3785. * @abstract
  3786. */
  3787. buildCSSClass() {
  3788. // Child classes can include a function that does:
  3789. // return 'CLASS NAME' + this._super();
  3790. return '';
  3791. }
  3792. /**
  3793. * Bind a listener to the component's ready state.
  3794. * Different from event listeners in that if the ready event has already happened
  3795. * it will trigger the function immediately.
  3796. *
  3797. * @param {ReadyCallback} fn
  3798. * Function that gets called when the `Component` is ready.
  3799. *
  3800. * @return {Component}
  3801. * Returns itself; method can be chained.
  3802. */
  3803. ready(fn, sync = false) {
  3804. if (!fn) {
  3805. return;
  3806. }
  3807. if (!this.isReady_) {
  3808. this.readyQueue_ = this.readyQueue_ || [];
  3809. this.readyQueue_.push(fn);
  3810. return;
  3811. }
  3812. if (sync) {
  3813. fn.call(this);
  3814. } else {
  3815. // Call the function asynchronously by default for consistency
  3816. this.setTimeout(fn, 1);
  3817. }
  3818. }
  3819. /**
  3820. * Trigger all the ready listeners for this `Component`.
  3821. *
  3822. * @fires Component#ready
  3823. */
  3824. triggerReady() {
  3825. this.isReady_ = true;
  3826. // Ensure ready is triggered asynchronously
  3827. this.setTimeout(function () {
  3828. const readyQueue = this.readyQueue_;
  3829. // Reset Ready Queue
  3830. this.readyQueue_ = [];
  3831. if (readyQueue && readyQueue.length > 0) {
  3832. readyQueue.forEach(function (fn) {
  3833. fn.call(this);
  3834. }, this);
  3835. }
  3836. // Allow for using event listeners also
  3837. /**
  3838. * Triggered when a `Component` is ready.
  3839. *
  3840. * @event Component#ready
  3841. * @type {Event}
  3842. */
  3843. this.trigger('ready');
  3844. }, 1);
  3845. }
  3846. /**
  3847. * Find a single DOM element matching a `selector`. This can be within the `Component`s
  3848. * `contentEl()` or another custom context.
  3849. *
  3850. * @param {string} selector
  3851. * A valid CSS selector, which will be passed to `querySelector`.
  3852. *
  3853. * @param {Element|string} [context=this.contentEl()]
  3854. * A DOM element within which to query. Can also be a selector string in
  3855. * which case the first matching element will get used as context. If
  3856. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  3857. * nothing it falls back to `document`.
  3858. *
  3859. * @return {Element|null}
  3860. * the dom element that was found, or null
  3861. *
  3862. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  3863. */
  3864. $(selector, context) {
  3865. return $(selector, context || this.contentEl());
  3866. }
  3867. /**
  3868. * Finds all DOM element matching a `selector`. This can be within the `Component`s
  3869. * `contentEl()` or another custom context.
  3870. *
  3871. * @param {string} selector
  3872. * A valid CSS selector, which will be passed to `querySelectorAll`.
  3873. *
  3874. * @param {Element|string} [context=this.contentEl()]
  3875. * A DOM element within which to query. Can also be a selector string in
  3876. * which case the first matching element will get used as context. If
  3877. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  3878. * nothing it falls back to `document`.
  3879. *
  3880. * @return {NodeList}
  3881. * a list of dom elements that were found
  3882. *
  3883. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  3884. */
  3885. $$(selector, context) {
  3886. return $$(selector, context || this.contentEl());
  3887. }
  3888. /**
  3889. * Check if a component's element has a CSS class name.
  3890. *
  3891. * @param {string} classToCheck
  3892. * CSS class name to check.
  3893. *
  3894. * @return {boolean}
  3895. * - True if the `Component` has the class.
  3896. * - False if the `Component` does not have the class`
  3897. */
  3898. hasClass(classToCheck) {
  3899. return hasClass(this.el_, classToCheck);
  3900. }
  3901. /**
  3902. * Add a CSS class name to the `Component`s element.
  3903. *
  3904. * @param {...string} classesToAdd
  3905. * One or more CSS class name to add.
  3906. */
  3907. addClass(...classesToAdd) {
  3908. addClass(this.el_, ...classesToAdd);
  3909. }
  3910. /**
  3911. * Remove a CSS class name from the `Component`s element.
  3912. *
  3913. * @param {...string} classesToRemove
  3914. * One or more CSS class name to remove.
  3915. */
  3916. removeClass(...classesToRemove) {
  3917. removeClass(this.el_, ...classesToRemove);
  3918. }
  3919. /**
  3920. * Add or remove a CSS class name from the component's element.
  3921. * - `classToToggle` gets added when {@link Component#hasClass} would return false.
  3922. * - `classToToggle` gets removed when {@link Component#hasClass} would return true.
  3923. *
  3924. * @param {string} classToToggle
  3925. * The class to add or remove based on (@link Component#hasClass}
  3926. *
  3927. * @param {boolean|Dom~predicate} [predicate]
  3928. * An {@link Dom~predicate} function or a boolean
  3929. */
  3930. toggleClass(classToToggle, predicate) {
  3931. toggleClass(this.el_, classToToggle, predicate);
  3932. }
  3933. /**
  3934. * Show the `Component`s element if it is hidden by removing the
  3935. * 'vjs-hidden' class name from it.
  3936. */
  3937. show() {
  3938. this.removeClass('vjs-hidden');
  3939. }
  3940. /**
  3941. * Hide the `Component`s element if it is currently showing by adding the
  3942. * 'vjs-hidden` class name to it.
  3943. */
  3944. hide() {
  3945. this.addClass('vjs-hidden');
  3946. }
  3947. /**
  3948. * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing'
  3949. * class name to it. Used during fadeIn/fadeOut.
  3950. *
  3951. * @private
  3952. */
  3953. lockShowing() {
  3954. this.addClass('vjs-lock-showing');
  3955. }
  3956. /**
  3957. * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing'
  3958. * class name from it. Used during fadeIn/fadeOut.
  3959. *
  3960. * @private
  3961. */
  3962. unlockShowing() {
  3963. this.removeClass('vjs-lock-showing');
  3964. }
  3965. /**
  3966. * Get the value of an attribute on the `Component`s element.
  3967. *
  3968. * @param {string} attribute
  3969. * Name of the attribute to get the value from.
  3970. *
  3971. * @return {string|null}
  3972. * - The value of the attribute that was asked for.
  3973. * - Can be an empty string on some browsers if the attribute does not exist
  3974. * or has no value
  3975. * - Most browsers will return null if the attribute does not exist or has
  3976. * no value.
  3977. *
  3978. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute}
  3979. */
  3980. getAttribute(attribute) {
  3981. return getAttribute(this.el_, attribute);
  3982. }
  3983. /**
  3984. * Set the value of an attribute on the `Component`'s element
  3985. *
  3986. * @param {string} attribute
  3987. * Name of the attribute to set.
  3988. *
  3989. * @param {string} value
  3990. * Value to set the attribute to.
  3991. *
  3992. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute}
  3993. */
  3994. setAttribute(attribute, value) {
  3995. setAttribute(this.el_, attribute, value);
  3996. }
  3997. /**
  3998. * Remove an attribute from the `Component`s element.
  3999. *
  4000. * @param {string} attribute
  4001. * Name of the attribute to remove.
  4002. *
  4003. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute}
  4004. */
  4005. removeAttribute(attribute) {
  4006. removeAttribute(this.el_, attribute);
  4007. }
  4008. /**
  4009. * Get or set the width of the component based upon the CSS styles.
  4010. * See {@link Component#dimension} for more detailed information.
  4011. *
  4012. * @param {number|string} [num]
  4013. * The width that you want to set postfixed with '%', 'px' or nothing.
  4014. *
  4015. * @param {boolean} [skipListeners]
  4016. * Skip the componentresize event trigger
  4017. *
  4018. * @return {number|string}
  4019. * The width when getting, zero if there is no width. Can be a string
  4020. * postpixed with '%' or 'px'.
  4021. */
  4022. width(num, skipListeners) {
  4023. return this.dimension('width', num, skipListeners);
  4024. }
  4025. /**
  4026. * Get or set the height of the component based upon the CSS styles.
  4027. * See {@link Component#dimension} for more detailed information.
  4028. *
  4029. * @param {number|string} [num]
  4030. * The height that you want to set postfixed with '%', 'px' or nothing.
  4031. *
  4032. * @param {boolean} [skipListeners]
  4033. * Skip the componentresize event trigger
  4034. *
  4035. * @return {number|string}
  4036. * The width when getting, zero if there is no width. Can be a string
  4037. * postpixed with '%' or 'px'.
  4038. */
  4039. height(num, skipListeners) {
  4040. return this.dimension('height', num, skipListeners);
  4041. }
  4042. /**
  4043. * Set both the width and height of the `Component` element at the same time.
  4044. *
  4045. * @param {number|string} width
  4046. * Width to set the `Component`s element to.
  4047. *
  4048. * @param {number|string} height
  4049. * Height to set the `Component`s element to.
  4050. */
  4051. dimensions(width, height) {
  4052. // Skip componentresize listeners on width for optimization
  4053. this.width(width, true);
  4054. this.height(height);
  4055. }
  4056. /**
  4057. * Get or set width or height of the `Component` element. This is the shared code
  4058. * for the {@link Component#width} and {@link Component#height}.
  4059. *
  4060. * Things to know:
  4061. * - If the width or height in an number this will return the number postfixed with 'px'.
  4062. * - If the width/height is a percent this will return the percent postfixed with '%'
  4063. * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function
  4064. * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`.
  4065. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/}
  4066. * for more information
  4067. * - If you want the computed style of the component, use {@link Component#currentWidth}
  4068. * and {@link {Component#currentHeight}
  4069. *
  4070. * @fires Component#componentresize
  4071. *
  4072. * @param {string} widthOrHeight
  4073. 8 'width' or 'height'
  4074. *
  4075. * @param {number|string} [num]
  4076. 8 New dimension
  4077. *
  4078. * @param {boolean} [skipListeners]
  4079. * Skip componentresize event trigger
  4080. *
  4081. * @return {number}
  4082. * The dimension when getting or 0 if unset
  4083. */
  4084. dimension(widthOrHeight, num, skipListeners) {
  4085. if (num !== undefined) {
  4086. // Set to zero if null or literally NaN (NaN !== NaN)
  4087. if (num === null || num !== num) {
  4088. num = 0;
  4089. }
  4090. // Check if using css width/height (% or px) and adjust
  4091. if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {
  4092. this.el_.style[widthOrHeight] = num;
  4093. } else if (num === 'auto') {
  4094. this.el_.style[widthOrHeight] = '';
  4095. } else {
  4096. this.el_.style[widthOrHeight] = num + 'px';
  4097. }
  4098. // skipListeners allows us to avoid triggering the resize event when setting both width and height
  4099. if (!skipListeners) {
  4100. /**
  4101. * Triggered when a component is resized.
  4102. *
  4103. * @event Component#componentresize
  4104. * @type {Event}
  4105. */
  4106. this.trigger('componentresize');
  4107. }
  4108. return;
  4109. }
  4110. // Not setting a value, so getting it
  4111. // Make sure element exists
  4112. if (!this.el_) {
  4113. return 0;
  4114. }
  4115. // Get dimension value from style
  4116. const val = this.el_.style[widthOrHeight];
  4117. const pxIndex = val.indexOf('px');
  4118. if (pxIndex !== -1) {
  4119. // Return the pixel value with no 'px'
  4120. return parseInt(val.slice(0, pxIndex), 10);
  4121. }
  4122. // No px so using % or no style was set, so falling back to offsetWidth/height
  4123. // If component has display:none, offset will return 0
  4124. // TODO: handle display:none and no dimension style using px
  4125. return parseInt(this.el_['offset' + toTitleCase$1(widthOrHeight)], 10);
  4126. }
  4127. /**
  4128. * Get the computed width or the height of the component's element.
  4129. *
  4130. * Uses `window.getComputedStyle`.
  4131. *
  4132. * @param {string} widthOrHeight
  4133. * A string containing 'width' or 'height'. Whichever one you want to get.
  4134. *
  4135. * @return {number}
  4136. * The dimension that gets asked for or 0 if nothing was set
  4137. * for that dimension.
  4138. */
  4139. currentDimension(widthOrHeight) {
  4140. let computedWidthOrHeight = 0;
  4141. if (widthOrHeight !== 'width' && widthOrHeight !== 'height') {
  4142. throw new Error('currentDimension only accepts width or height value');
  4143. }
  4144. computedWidthOrHeight = computedStyle(this.el_, widthOrHeight);
  4145. // remove 'px' from variable and parse as integer
  4146. computedWidthOrHeight = parseFloat(computedWidthOrHeight);
  4147. // if the computed value is still 0, it's possible that the browser is lying
  4148. // and we want to check the offset values.
  4149. // This code also runs wherever getComputedStyle doesn't exist.
  4150. if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) {
  4151. const rule = `offset${toTitleCase$1(widthOrHeight)}`;
  4152. computedWidthOrHeight = this.el_[rule];
  4153. }
  4154. return computedWidthOrHeight;
  4155. }
  4156. /**
  4157. * An object that contains width and height values of the `Component`s
  4158. * computed style. Uses `window.getComputedStyle`.
  4159. *
  4160. * @typedef {Object} Component~DimensionObject
  4161. *
  4162. * @property {number} width
  4163. * The width of the `Component`s computed style.
  4164. *
  4165. * @property {number} height
  4166. * The height of the `Component`s computed style.
  4167. */
  4168. /**
  4169. * Get an object that contains computed width and height values of the
  4170. * component's element.
  4171. *
  4172. * Uses `window.getComputedStyle`.
  4173. *
  4174. * @return {Component~DimensionObject}
  4175. * The computed dimensions of the component's element.
  4176. */
  4177. currentDimensions() {
  4178. return {
  4179. width: this.currentDimension('width'),
  4180. height: this.currentDimension('height')
  4181. };
  4182. }
  4183. /**
  4184. * Get the computed width of the component's element.
  4185. *
  4186. * Uses `window.getComputedStyle`.
  4187. *
  4188. * @return {number}
  4189. * The computed width of the component's element.
  4190. */
  4191. currentWidth() {
  4192. return this.currentDimension('width');
  4193. }
  4194. /**
  4195. * Get the computed height of the component's element.
  4196. *
  4197. * Uses `window.getComputedStyle`.
  4198. *
  4199. * @return {number}
  4200. * The computed height of the component's element.
  4201. */
  4202. currentHeight() {
  4203. return this.currentDimension('height');
  4204. }
  4205. /**
  4206. * Set the focus to this component
  4207. */
  4208. focus() {
  4209. this.el_.focus();
  4210. }
  4211. /**
  4212. * Remove the focus from this component
  4213. */
  4214. blur() {
  4215. this.el_.blur();
  4216. }
  4217. /**
  4218. * When this Component receives a `keydown` event which it does not process,
  4219. * it passes the event to the Player for handling.
  4220. *
  4221. * @param {KeyboardEvent} event
  4222. * The `keydown` event that caused this function to be called.
  4223. */
  4224. handleKeyDown(event) {
  4225. if (this.player_) {
  4226. // We only stop propagation here because we want unhandled events to fall
  4227. // back to the browser. Exclude Tab for focus trapping.
  4228. if (!keycode.isEventKey(event, 'Tab')) {
  4229. event.stopPropagation();
  4230. }
  4231. this.player_.handleKeyDown(event);
  4232. }
  4233. }
  4234. /**
  4235. * Many components used to have a `handleKeyPress` method, which was poorly
  4236. * named because it listened to a `keydown` event. This method name now
  4237. * delegates to `handleKeyDown`. This means anyone calling `handleKeyPress`
  4238. * will not see their method calls stop working.
  4239. *
  4240. * @param {Event} event
  4241. * The event that caused this function to be called.
  4242. */
  4243. handleKeyPress(event) {
  4244. this.handleKeyDown(event);
  4245. }
  4246. /**
  4247. * Emit a 'tap' events when touch event support gets detected. This gets used to
  4248. * support toggling the controls through a tap on the video. They get enabled
  4249. * because every sub-component would have extra overhead otherwise.
  4250. *
  4251. * @private
  4252. * @fires Component#tap
  4253. * @listens Component#touchstart
  4254. * @listens Component#touchmove
  4255. * @listens Component#touchleave
  4256. * @listens Component#touchcancel
  4257. * @listens Component#touchend
  4258. */
  4259. emitTapEvents() {
  4260. // Track the start time so we can determine how long the touch lasted
  4261. let touchStart = 0;
  4262. let firstTouch = null;
  4263. // Maximum movement allowed during a touch event to still be considered a tap
  4264. // Other popular libs use anywhere from 2 (hammer.js) to 15,
  4265. // so 10 seems like a nice, round number.
  4266. const tapMovementThreshold = 10;
  4267. // The maximum length a touch can be while still being considered a tap
  4268. const touchTimeThreshold = 200;
  4269. let couldBeTap;
  4270. this.on('touchstart', function (event) {
  4271. // If more than one finger, don't consider treating this as a click
  4272. if (event.touches.length === 1) {
  4273. // Copy pageX/pageY from the object
  4274. firstTouch = {
  4275. pageX: event.touches[0].pageX,
  4276. pageY: event.touches[0].pageY
  4277. };
  4278. // Record start time so we can detect a tap vs. "touch and hold"
  4279. touchStart = window$1.performance.now();
  4280. // Reset couldBeTap tracking
  4281. couldBeTap = true;
  4282. }
  4283. });
  4284. this.on('touchmove', function (event) {
  4285. // If more than one finger, don't consider treating this as a click
  4286. if (event.touches.length > 1) {
  4287. couldBeTap = false;
  4288. } else if (firstTouch) {
  4289. // Some devices will throw touchmoves for all but the slightest of taps.
  4290. // So, if we moved only a small distance, this could still be a tap
  4291. const xdiff = event.touches[0].pageX - firstTouch.pageX;
  4292. const ydiff = event.touches[0].pageY - firstTouch.pageY;
  4293. const touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
  4294. if (touchDistance > tapMovementThreshold) {
  4295. couldBeTap = false;
  4296. }
  4297. }
  4298. });
  4299. const noTap = function () {
  4300. couldBeTap = false;
  4301. };
  4302. // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
  4303. this.on('touchleave', noTap);
  4304. this.on('touchcancel', noTap);
  4305. // When the touch ends, measure how long it took and trigger the appropriate
  4306. // event
  4307. this.on('touchend', function (event) {
  4308. firstTouch = null;
  4309. // Proceed only if the touchmove/leave/cancel event didn't happen
  4310. if (couldBeTap === true) {
  4311. // Measure how long the touch lasted
  4312. const touchTime = window$1.performance.now() - touchStart;
  4313. // Make sure the touch was less than the threshold to be considered a tap
  4314. if (touchTime < touchTimeThreshold) {
  4315. // Don't let browser turn this into a click
  4316. event.preventDefault();
  4317. /**
  4318. * Triggered when a `Component` is tapped.
  4319. *
  4320. * @event Component#tap
  4321. * @type {MouseEvent}
  4322. */
  4323. this.trigger('tap');
  4324. // It may be good to copy the touchend event object and change the
  4325. // type to tap, if the other event properties aren't exact after
  4326. // Events.fixEvent runs (e.g. event.target)
  4327. }
  4328. }
  4329. });
  4330. }
  4331. /**
  4332. * This function reports user activity whenever touch events happen. This can get
  4333. * turned off by any sub-components that wants touch events to act another way.
  4334. *
  4335. * Report user touch activity when touch events occur. User activity gets used to
  4336. * determine when controls should show/hide. It is simple when it comes to mouse
  4337. * events, because any mouse event should show the controls. So we capture mouse
  4338. * events that bubble up to the player and report activity when that happens.
  4339. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player
  4340. * controls. So touch events can't help us at the player level either.
  4341. *
  4342. * User activity gets checked asynchronously. So what could happen is a tap event
  4343. * on the video turns the controls off. Then the `touchend` event bubbles up to
  4344. * the player. Which, if it reported user activity, would turn the controls right
  4345. * back on. We also don't want to completely block touch events from bubbling up.
  4346. * Furthermore a `touchmove` event and anything other than a tap, should not turn
  4347. * controls back on.
  4348. *
  4349. * @listens Component#touchstart
  4350. * @listens Component#touchmove
  4351. * @listens Component#touchend
  4352. * @listens Component#touchcancel
  4353. */
  4354. enableTouchActivity() {
  4355. // Don't continue if the root player doesn't support reporting user activity
  4356. if (!this.player() || !this.player().reportUserActivity) {
  4357. return;
  4358. }
  4359. // listener for reporting that the user is active
  4360. const report = bind_(this.player(), this.player().reportUserActivity);
  4361. let touchHolding;
  4362. this.on('touchstart', function () {
  4363. report();
  4364. // For as long as the they are touching the device or have their mouse down,
  4365. // we consider them active even if they're not moving their finger or mouse.
  4366. // So we want to continue to update that they are active
  4367. this.clearInterval(touchHolding);
  4368. // report at the same interval as activityCheck
  4369. touchHolding = this.setInterval(report, 250);
  4370. });
  4371. const touchEnd = function (event) {
  4372. report();
  4373. // stop the interval that maintains activity if the touch is holding
  4374. this.clearInterval(touchHolding);
  4375. };
  4376. this.on('touchmove', report);
  4377. this.on('touchend', touchEnd);
  4378. this.on('touchcancel', touchEnd);
  4379. }
  4380. /**
  4381. * A callback that has no parameters and is bound into `Component`s context.
  4382. *
  4383. * @callback Component~GenericCallback
  4384. * @this Component
  4385. */
  4386. /**
  4387. * Creates a function that runs after an `x` millisecond timeout. This function is a
  4388. * wrapper around `window.setTimeout`. There are a few reasons to use this one
  4389. * instead though:
  4390. * 1. It gets cleared via {@link Component#clearTimeout} when
  4391. * {@link Component#dispose} gets called.
  4392. * 2. The function callback will gets turned into a {@link Component~GenericCallback}
  4393. *
  4394. * > Note: You can't use `window.clearTimeout` on the id returned by this function. This
  4395. * will cause its dispose listener not to get cleaned up! Please use
  4396. * {@link Component#clearTimeout} or {@link Component#dispose} instead.
  4397. *
  4398. * @param {Component~GenericCallback} fn
  4399. * The function that will be run after `timeout`.
  4400. *
  4401. * @param {number} timeout
  4402. * Timeout in milliseconds to delay before executing the specified function.
  4403. *
  4404. * @return {number}
  4405. * Returns a timeout ID that gets used to identify the timeout. It can also
  4406. * get used in {@link Component#clearTimeout} to clear the timeout that
  4407. * was set.
  4408. *
  4409. * @listens Component#dispose
  4410. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout}
  4411. */
  4412. setTimeout(fn, timeout) {
  4413. // declare as variables so they are properly available in timeout function
  4414. // eslint-disable-next-line
  4415. var timeoutId;
  4416. fn = bind_(this, fn);
  4417. this.clearTimersOnDispose_();
  4418. timeoutId = window$1.setTimeout(() => {
  4419. if (this.setTimeoutIds_.has(timeoutId)) {
  4420. this.setTimeoutIds_.delete(timeoutId);
  4421. }
  4422. fn();
  4423. }, timeout);
  4424. this.setTimeoutIds_.add(timeoutId);
  4425. return timeoutId;
  4426. }
  4427. /**
  4428. * Clears a timeout that gets created via `window.setTimeout` or
  4429. * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout}
  4430. * use this function instead of `window.clearTimout`. If you don't your dispose
  4431. * listener will not get cleaned up until {@link Component#dispose}!
  4432. *
  4433. * @param {number} timeoutId
  4434. * The id of the timeout to clear. The return value of
  4435. * {@link Component#setTimeout} or `window.setTimeout`.
  4436. *
  4437. * @return {number}
  4438. * Returns the timeout id that was cleared.
  4439. *
  4440. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout}
  4441. */
  4442. clearTimeout(timeoutId) {
  4443. if (this.setTimeoutIds_.has(timeoutId)) {
  4444. this.setTimeoutIds_.delete(timeoutId);
  4445. window$1.clearTimeout(timeoutId);
  4446. }
  4447. return timeoutId;
  4448. }
  4449. /**
  4450. * Creates a function that gets run every `x` milliseconds. This function is a wrapper
  4451. * around `window.setInterval`. There are a few reasons to use this one instead though.
  4452. * 1. It gets cleared via {@link Component#clearInterval} when
  4453. * {@link Component#dispose} gets called.
  4454. * 2. The function callback will be a {@link Component~GenericCallback}
  4455. *
  4456. * @param {Component~GenericCallback} fn
  4457. * The function to run every `x` seconds.
  4458. *
  4459. * @param {number} interval
  4460. * Execute the specified function every `x` milliseconds.
  4461. *
  4462. * @return {number}
  4463. * Returns an id that can be used to identify the interval. It can also be be used in
  4464. * {@link Component#clearInterval} to clear the interval.
  4465. *
  4466. * @listens Component#dispose
  4467. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval}
  4468. */
  4469. setInterval(fn, interval) {
  4470. fn = bind_(this, fn);
  4471. this.clearTimersOnDispose_();
  4472. const intervalId = window$1.setInterval(fn, interval);
  4473. this.setIntervalIds_.add(intervalId);
  4474. return intervalId;
  4475. }
  4476. /**
  4477. * Clears an interval that gets created via `window.setInterval` or
  4478. * {@link Component#setInterval}. If you set an interval via {@link Component#setInterval}
  4479. * use this function instead of `window.clearInterval`. If you don't your dispose
  4480. * listener will not get cleaned up until {@link Component#dispose}!
  4481. *
  4482. * @param {number} intervalId
  4483. * The id of the interval to clear. The return value of
  4484. * {@link Component#setInterval} or `window.setInterval`.
  4485. *
  4486. * @return {number}
  4487. * Returns the interval id that was cleared.
  4488. *
  4489. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval}
  4490. */
  4491. clearInterval(intervalId) {
  4492. if (this.setIntervalIds_.has(intervalId)) {
  4493. this.setIntervalIds_.delete(intervalId);
  4494. window$1.clearInterval(intervalId);
  4495. }
  4496. return intervalId;
  4497. }
  4498. /**
  4499. * Queues up a callback to be passed to requestAnimationFrame (rAF), but
  4500. * with a few extra bonuses:
  4501. *
  4502. * - Supports browsers that do not support rAF by falling back to
  4503. * {@link Component#setTimeout}.
  4504. *
  4505. * - The callback is turned into a {@link Component~GenericCallback} (i.e.
  4506. * bound to the component).
  4507. *
  4508. * - Automatic cancellation of the rAF callback is handled if the component
  4509. * is disposed before it is called.
  4510. *
  4511. * @param {Component~GenericCallback} fn
  4512. * A function that will be bound to this component and executed just
  4513. * before the browser's next repaint.
  4514. *
  4515. * @return {number}
  4516. * Returns an rAF ID that gets used to identify the timeout. It can
  4517. * also be used in {@link Component#cancelAnimationFrame} to cancel
  4518. * the animation frame callback.
  4519. *
  4520. * @listens Component#dispose
  4521. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}
  4522. */
  4523. requestAnimationFrame(fn) {
  4524. this.clearTimersOnDispose_();
  4525. // declare as variables so they are properly available in rAF function
  4526. // eslint-disable-next-line
  4527. var id;
  4528. fn = bind_(this, fn);
  4529. id = window$1.requestAnimationFrame(() => {
  4530. if (this.rafIds_.has(id)) {
  4531. this.rafIds_.delete(id);
  4532. }
  4533. fn();
  4534. });
  4535. this.rafIds_.add(id);
  4536. return id;
  4537. }
  4538. /**
  4539. * Request an animation frame, but only one named animation
  4540. * frame will be queued. Another will never be added until
  4541. * the previous one finishes.
  4542. *
  4543. * @param {string} name
  4544. * The name to give this requestAnimationFrame
  4545. *
  4546. * @param {Component~GenericCallback} fn
  4547. * A function that will be bound to this component and executed just
  4548. * before the browser's next repaint.
  4549. */
  4550. requestNamedAnimationFrame(name, fn) {
  4551. if (this.namedRafs_.has(name)) {
  4552. return;
  4553. }
  4554. this.clearTimersOnDispose_();
  4555. fn = bind_(this, fn);
  4556. const id = this.requestAnimationFrame(() => {
  4557. fn();
  4558. if (this.namedRafs_.has(name)) {
  4559. this.namedRafs_.delete(name);
  4560. }
  4561. });
  4562. this.namedRafs_.set(name, id);
  4563. return name;
  4564. }
  4565. /**
  4566. * Cancels a current named animation frame if it exists.
  4567. *
  4568. * @param {string} name
  4569. * The name of the requestAnimationFrame to cancel.
  4570. */
  4571. cancelNamedAnimationFrame(name) {
  4572. if (!this.namedRafs_.has(name)) {
  4573. return;
  4574. }
  4575. this.cancelAnimationFrame(this.namedRafs_.get(name));
  4576. this.namedRafs_.delete(name);
  4577. }
  4578. /**
  4579. * Cancels a queued callback passed to {@link Component#requestAnimationFrame}
  4580. * (rAF).
  4581. *
  4582. * If you queue an rAF callback via {@link Component#requestAnimationFrame},
  4583. * use this function instead of `window.cancelAnimationFrame`. If you don't,
  4584. * your dispose listener will not get cleaned up until {@link Component#dispose}!
  4585. *
  4586. * @param {number} id
  4587. * The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}.
  4588. *
  4589. * @return {number}
  4590. * Returns the rAF ID that was cleared.
  4591. *
  4592. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame}
  4593. */
  4594. cancelAnimationFrame(id) {
  4595. if (this.rafIds_.has(id)) {
  4596. this.rafIds_.delete(id);
  4597. window$1.cancelAnimationFrame(id);
  4598. }
  4599. return id;
  4600. }
  4601. /**
  4602. * A function to setup `requestAnimationFrame`, `setTimeout`,
  4603. * and `setInterval`, clearing on dispose.
  4604. *
  4605. * > Previously each timer added and removed dispose listeners on it's own.
  4606. * For better performance it was decided to batch them all, and use `Set`s
  4607. * to track outstanding timer ids.
  4608. *
  4609. * @private
  4610. */
  4611. clearTimersOnDispose_() {
  4612. if (this.clearingTimersOnDispose_) {
  4613. return;
  4614. }
  4615. this.clearingTimersOnDispose_ = true;
  4616. this.one('dispose', () => {
  4617. [['namedRafs_', 'cancelNamedAnimationFrame'], ['rafIds_', 'cancelAnimationFrame'], ['setTimeoutIds_', 'clearTimeout'], ['setIntervalIds_', 'clearInterval']].forEach(([idName, cancelName]) => {
  4618. // for a `Set` key will actually be the value again
  4619. // so forEach((val, val) =>` but for maps we want to use
  4620. // the key.
  4621. this[idName].forEach((val, key) => this[cancelName](key));
  4622. });
  4623. this.clearingTimersOnDispose_ = false;
  4624. });
  4625. }
  4626. /**
  4627. * Register a `Component` with `videojs` given the name and the component.
  4628. *
  4629. * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s
  4630. * should be registered using {@link Tech.registerTech} or
  4631. * {@link videojs:videojs.registerTech}.
  4632. *
  4633. * > NOTE: This function can also be seen on videojs as
  4634. * {@link videojs:videojs.registerComponent}.
  4635. *
  4636. * @param {string} name
  4637. * The name of the `Component` to register.
  4638. *
  4639. * @param {Component} ComponentToRegister
  4640. * The `Component` class to register.
  4641. *
  4642. * @return {Component}
  4643. * The `Component` that was registered.
  4644. */
  4645. static registerComponent(name, ComponentToRegister) {
  4646. if (typeof name !== 'string' || !name) {
  4647. throw new Error(`Illegal component name, "${name}"; must be a non-empty string.`);
  4648. }
  4649. const Tech = Component$1.getComponent('Tech');
  4650. // We need to make sure this check is only done if Tech has been registered.
  4651. const isTech = Tech && Tech.isTech(ComponentToRegister);
  4652. const isComp = Component$1 === ComponentToRegister || Component$1.prototype.isPrototypeOf(ComponentToRegister.prototype);
  4653. if (isTech || !isComp) {
  4654. let reason;
  4655. if (isTech) {
  4656. reason = 'techs must be registered using Tech.registerTech()';
  4657. } else {
  4658. reason = 'must be a Component subclass';
  4659. }
  4660. throw new Error(`Illegal component, "${name}"; ${reason}.`);
  4661. }
  4662. name = toTitleCase$1(name);
  4663. if (!Component$1.components_) {
  4664. Component$1.components_ = {};
  4665. }
  4666. const Player = Component$1.getComponent('Player');
  4667. if (name === 'Player' && Player && Player.players) {
  4668. const players = Player.players;
  4669. const playerNames = Object.keys(players);
  4670. // If we have players that were disposed, then their name will still be
  4671. // in Players.players. So, we must loop through and verify that the value
  4672. // for each item is not null. This allows registration of the Player component
  4673. // after all players have been disposed or before any were created.
  4674. if (players && playerNames.length > 0 && playerNames.map(pname => players[pname]).every(Boolean)) {
  4675. throw new Error('Can not register Player component after player has been created.');
  4676. }
  4677. }
  4678. Component$1.components_[name] = ComponentToRegister;
  4679. Component$1.components_[toLowerCase(name)] = ComponentToRegister;
  4680. return ComponentToRegister;
  4681. }
  4682. /**
  4683. * Get a `Component` based on the name it was registered with.
  4684. *
  4685. * @param {string} name
  4686. * The Name of the component to get.
  4687. *
  4688. * @return {Component}
  4689. * The `Component` that got registered under the given name.
  4690. */
  4691. static getComponent(name) {
  4692. if (!name || !Component$1.components_) {
  4693. return;
  4694. }
  4695. return Component$1.components_[name];
  4696. }
  4697. }
  4698. Component$1.registerComponent('Component', Component$1);
  4699. /**
  4700. * @file time.js
  4701. * @module time
  4702. */
  4703. /**
  4704. * Returns the time for the specified index at the start or end
  4705. * of a TimeRange object.
  4706. *
  4707. * @typedef {Function} TimeRangeIndex
  4708. *
  4709. * @param {number} [index=0]
  4710. * The range number to return the time for.
  4711. *
  4712. * @return {number}
  4713. * The time offset at the specified index.
  4714. *
  4715. * @deprecated The index argument must be provided.
  4716. * In the future, leaving it out will throw an error.
  4717. */
  4718. /**
  4719. * An object that contains ranges of time, which mimics {@link TimeRanges}.
  4720. *
  4721. * @typedef {Object} TimeRange
  4722. *
  4723. * @property {number} length
  4724. * The number of time ranges represented by this object.
  4725. *
  4726. * @property {module:time~TimeRangeIndex} start
  4727. * Returns the time offset at which a specified time range begins.
  4728. *
  4729. * @property {module:time~TimeRangeIndex} end
  4730. * Returns the time offset at which a specified time range ends.
  4731. *
  4732. * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges
  4733. */
  4734. /**
  4735. * Check if any of the time ranges are over the maximum index.
  4736. *
  4737. * @private
  4738. * @param {string} fnName
  4739. * The function name to use for logging
  4740. *
  4741. * @param {number} index
  4742. * The index to check
  4743. *
  4744. * @param {number} maxIndex
  4745. * The maximum possible index
  4746. *
  4747. * @throws {Error} if the timeRanges provided are over the maxIndex
  4748. */
  4749. function rangeCheck(fnName, index, maxIndex) {
  4750. if (typeof index !== 'number' || index < 0 || index > maxIndex) {
  4751. throw new Error(`Failed to execute '${fnName}' on 'TimeRanges': The index provided (${index}) is non-numeric or out of bounds (0-${maxIndex}).`);
  4752. }
  4753. }
  4754. /**
  4755. * Get the time for the specified index at the start or end
  4756. * of a TimeRange object.
  4757. *
  4758. * @private
  4759. * @param {string} fnName
  4760. * The function name to use for logging
  4761. *
  4762. * @param {string} valueIndex
  4763. * The property that should be used to get the time. should be
  4764. * 'start' or 'end'
  4765. *
  4766. * @param {Array} ranges
  4767. * An array of time ranges
  4768. *
  4769. * @param {Array} [rangeIndex=0]
  4770. * The index to start the search at
  4771. *
  4772. * @return {number}
  4773. * The time that offset at the specified index.
  4774. *
  4775. * @deprecated rangeIndex must be set to a value, in the future this will throw an error.
  4776. * @throws {Error} if rangeIndex is more than the length of ranges
  4777. */
  4778. function getRange(fnName, valueIndex, ranges, rangeIndex) {
  4779. rangeCheck(fnName, rangeIndex, ranges.length - 1);
  4780. return ranges[rangeIndex][valueIndex];
  4781. }
  4782. /**
  4783. * Create a time range object given ranges of time.
  4784. *
  4785. * @private
  4786. * @param {Array} [ranges]
  4787. * An array of time ranges.
  4788. *
  4789. * @return {TimeRange}
  4790. */
  4791. function createTimeRangesObj(ranges) {
  4792. let timeRangesObj;
  4793. if (ranges === undefined || ranges.length === 0) {
  4794. timeRangesObj = {
  4795. length: 0,
  4796. start() {
  4797. throw new Error('This TimeRanges object is empty');
  4798. },
  4799. end() {
  4800. throw new Error('This TimeRanges object is empty');
  4801. }
  4802. };
  4803. } else {
  4804. timeRangesObj = {
  4805. length: ranges.length,
  4806. start: getRange.bind(null, 'start', 0, ranges),
  4807. end: getRange.bind(null, 'end', 1, ranges)
  4808. };
  4809. }
  4810. if (window$1.Symbol && window$1.Symbol.iterator) {
  4811. timeRangesObj[window$1.Symbol.iterator] = () => (ranges || []).values();
  4812. }
  4813. return timeRangesObj;
  4814. }
  4815. /**
  4816. * Create a `TimeRange` object which mimics an
  4817. * {@link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges|HTML5 TimeRanges instance}.
  4818. *
  4819. * @param {number|Array[]} start
  4820. * The start of a single range (a number) or an array of ranges (an
  4821. * array of arrays of two numbers each).
  4822. *
  4823. * @param {number} end
  4824. * The end of a single range. Cannot be used with the array form of
  4825. * the `start` argument.
  4826. *
  4827. * @return {TimeRange}
  4828. */
  4829. function createTimeRanges$1(start, end) {
  4830. if (Array.isArray(start)) {
  4831. return createTimeRangesObj(start);
  4832. } else if (start === undefined || end === undefined) {
  4833. return createTimeRangesObj();
  4834. }
  4835. return createTimeRangesObj([[start, end]]);
  4836. }
  4837. /**
  4838. * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in
  4839. * seconds) will force a number of leading zeros to cover the length of the
  4840. * guide.
  4841. *
  4842. * @private
  4843. * @param {number} seconds
  4844. * Number of seconds to be turned into a string
  4845. *
  4846. * @param {number} guide
  4847. * Number (in seconds) to model the string after
  4848. *
  4849. * @return {string}
  4850. * Time formatted as H:MM:SS or M:SS
  4851. */
  4852. const defaultImplementation = function (seconds, guide) {
  4853. seconds = seconds < 0 ? 0 : seconds;
  4854. let s = Math.floor(seconds % 60);
  4855. let m = Math.floor(seconds / 60 % 60);
  4856. let h = Math.floor(seconds / 3600);
  4857. const gm = Math.floor(guide / 60 % 60);
  4858. const gh = Math.floor(guide / 3600);
  4859. // handle invalid times
  4860. if (isNaN(seconds) || seconds === Infinity) {
  4861. // '-' is false for all relational operators (e.g. <, >=) so this setting
  4862. // will add the minimum number of fields specified by the guide
  4863. h = m = s = '-';
  4864. }
  4865. // Check if we need to show hours
  4866. h = h > 0 || gh > 0 ? h + ':' : '';
  4867. // If hours are showing, we may need to add a leading zero.
  4868. // Always show at least one digit of minutes.
  4869. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':';
  4870. // Check if leading zero is need for seconds
  4871. s = s < 10 ? '0' + s : s;
  4872. return h + m + s;
  4873. };
  4874. // Internal pointer to the current implementation.
  4875. let implementation = defaultImplementation;
  4876. /**
  4877. * Replaces the default formatTime implementation with a custom implementation.
  4878. *
  4879. * @param {Function} customImplementation
  4880. * A function which will be used in place of the default formatTime
  4881. * implementation. Will receive the current time in seconds and the
  4882. * guide (in seconds) as arguments.
  4883. */
  4884. function setFormatTime(customImplementation) {
  4885. implementation = customImplementation;
  4886. }
  4887. /**
  4888. * Resets formatTime to the default implementation.
  4889. */
  4890. function resetFormatTime() {
  4891. implementation = defaultImplementation;
  4892. }
  4893. /**
  4894. * Delegates to either the default time formatting function or a custom
  4895. * function supplied via `setFormatTime`.
  4896. *
  4897. * Formats seconds as a time string (H:MM:SS or M:SS). Supplying a
  4898. * guide (in seconds) will force a number of leading zeros to cover the
  4899. * length of the guide.
  4900. *
  4901. * @example formatTime(125, 600) === "02:05"
  4902. * @param {number} seconds
  4903. * Number of seconds to be turned into a string
  4904. *
  4905. * @param {number} guide
  4906. * Number (in seconds) to model the string after
  4907. *
  4908. * @return {string}
  4909. * Time formatted as H:MM:SS or M:SS
  4910. */
  4911. function formatTime(seconds, guide = seconds) {
  4912. return implementation(seconds, guide);
  4913. }
  4914. var Time = /*#__PURE__*/Object.freeze({
  4915. __proto__: null,
  4916. createTimeRanges: createTimeRanges$1,
  4917. createTimeRange: createTimeRanges$1,
  4918. setFormatTime: setFormatTime,
  4919. resetFormatTime: resetFormatTime,
  4920. formatTime: formatTime
  4921. });
  4922. /**
  4923. * @file buffer.js
  4924. * @module buffer
  4925. */
  4926. /**
  4927. * Compute the percentage of the media that has been buffered.
  4928. *
  4929. * @param { import('./time').TimeRange } buffered
  4930. * The current `TimeRanges` object representing buffered time ranges
  4931. *
  4932. * @param {number} duration
  4933. * Total duration of the media
  4934. *
  4935. * @return {number}
  4936. * Percent buffered of the total duration in decimal form.
  4937. */
  4938. function bufferedPercent(buffered, duration) {
  4939. let bufferedDuration = 0;
  4940. let start;
  4941. let end;
  4942. if (!duration) {
  4943. return 0;
  4944. }
  4945. if (!buffered || !buffered.length) {
  4946. buffered = createTimeRanges$1(0, 0);
  4947. }
  4948. for (let i = 0; i < buffered.length; i++) {
  4949. start = buffered.start(i);
  4950. end = buffered.end(i);
  4951. // buffered end can be bigger than duration by a very small fraction
  4952. if (end > duration) {
  4953. end = duration;
  4954. }
  4955. bufferedDuration += end - start;
  4956. }
  4957. return bufferedDuration / duration;
  4958. }
  4959. /**
  4960. * @file media-error.js
  4961. */
  4962. /**
  4963. * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class.
  4964. *
  4965. * @param {number|string|Object|MediaError} value
  4966. * This can be of multiple types:
  4967. * - number: should be a standard error code
  4968. * - string: an error message (the code will be 0)
  4969. * - Object: arbitrary properties
  4970. * - `MediaError` (native): used to populate a video.js `MediaError` object
  4971. * - `MediaError` (video.js): will return itself if it's already a
  4972. * video.js `MediaError` object.
  4973. *
  4974. * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror}
  4975. * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes}
  4976. *
  4977. * @class MediaError
  4978. */
  4979. function MediaError(value) {
  4980. // Allow redundant calls to this constructor to avoid having `instanceof`
  4981. // checks peppered around the code.
  4982. if (value instanceof MediaError) {
  4983. return value;
  4984. }
  4985. if (typeof value === 'number') {
  4986. this.code = value;
  4987. } else if (typeof value === 'string') {
  4988. // default code is zero, so this is a custom error
  4989. this.message = value;
  4990. } else if (isObject(value)) {
  4991. // We assign the `code` property manually because native `MediaError` objects
  4992. // do not expose it as an own/enumerable property of the object.
  4993. if (typeof value.code === 'number') {
  4994. this.code = value.code;
  4995. }
  4996. Object.assign(this, value);
  4997. }
  4998. if (!this.message) {
  4999. this.message = MediaError.defaultMessages[this.code] || '';
  5000. }
  5001. }
  5002. /**
  5003. * The error code that refers two one of the defined `MediaError` types
  5004. *
  5005. * @type {Number}
  5006. */
  5007. MediaError.prototype.code = 0;
  5008. /**
  5009. * An optional message that to show with the error. Message is not part of the HTML5
  5010. * video spec but allows for more informative custom errors.
  5011. *
  5012. * @type {String}
  5013. */
  5014. MediaError.prototype.message = '';
  5015. /**
  5016. * An optional status code that can be set by plugins to allow even more detail about
  5017. * the error. For example a plugin might provide a specific HTTP status code and an
  5018. * error message for that code. Then when the plugin gets that error this class will
  5019. * know how to display an error message for it. This allows a custom message to show
  5020. * up on the `Player` error overlay.
  5021. *
  5022. * @type {Array}
  5023. */
  5024. MediaError.prototype.status = null;
  5025. /**
  5026. * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the
  5027. * specification listed under {@link MediaError} for more information.
  5028. *
  5029. * @enum {array}
  5030. * @readonly
  5031. * @property {string} 0 - MEDIA_ERR_CUSTOM
  5032. * @property {string} 1 - MEDIA_ERR_ABORTED
  5033. * @property {string} 2 - MEDIA_ERR_NETWORK
  5034. * @property {string} 3 - MEDIA_ERR_DECODE
  5035. * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED
  5036. * @property {string} 5 - MEDIA_ERR_ENCRYPTED
  5037. */
  5038. MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED'];
  5039. /**
  5040. * The default `MediaError` messages based on the {@link MediaError.errorTypes}.
  5041. *
  5042. * @type {Array}
  5043. * @constant
  5044. */
  5045. MediaError.defaultMessages = {
  5046. 1: 'You aborted the media playback',
  5047. 2: 'A network error caused the media download to fail part-way.',
  5048. 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
  5049. 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
  5050. 5: 'The media is encrypted and we do not have the keys to decrypt it.'
  5051. };
  5052. // Add types as properties on MediaError
  5053. // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  5054. for (let errNum = 0; errNum < MediaError.errorTypes.length; errNum++) {
  5055. MediaError[MediaError.errorTypes[errNum]] = errNum;
  5056. // values should be accessible on both the class and instance
  5057. MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
  5058. }
  5059. /**
  5060. * Returns whether an object is `Promise`-like (i.e. has a `then` method).
  5061. *
  5062. * @param {Object} value
  5063. * An object that may or may not be `Promise`-like.
  5064. *
  5065. * @return {boolean}
  5066. * Whether or not the object is `Promise`-like.
  5067. */
  5068. function isPromise(value) {
  5069. return value !== undefined && value !== null && typeof value.then === 'function';
  5070. }
  5071. /**
  5072. * Silence a Promise-like object.
  5073. *
  5074. * This is useful for avoiding non-harmful, but potentially confusing "uncaught
  5075. * play promise" rejection error messages.
  5076. *
  5077. * @param {Object} value
  5078. * An object that may or may not be `Promise`-like.
  5079. */
  5080. function silencePromise(value) {
  5081. if (isPromise(value)) {
  5082. value.then(null, e => {});
  5083. }
  5084. }
  5085. /**
  5086. * @file text-track-list-converter.js Utilities for capturing text track state and
  5087. * re-creating tracks based on a capture.
  5088. *
  5089. * @module text-track-list-converter
  5090. */
  5091. /**
  5092. * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that
  5093. * represents the {@link TextTrack}'s state.
  5094. *
  5095. * @param {TextTrack} track
  5096. * The text track to query.
  5097. *
  5098. * @return {Object}
  5099. * A serializable javascript representation of the TextTrack.
  5100. * @private
  5101. */
  5102. const trackToJson_ = function (track) {
  5103. const ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce((acc, prop, i) => {
  5104. if (track[prop]) {
  5105. acc[prop] = track[prop];
  5106. }
  5107. return acc;
  5108. }, {
  5109. cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {
  5110. return {
  5111. startTime: cue.startTime,
  5112. endTime: cue.endTime,
  5113. text: cue.text,
  5114. id: cue.id
  5115. };
  5116. })
  5117. });
  5118. return ret;
  5119. };
  5120. /**
  5121. * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the
  5122. * state of all {@link TextTrack}s currently configured. The return array is compatible with
  5123. * {@link text-track-list-converter:jsonToTextTracks}.
  5124. *
  5125. * @param { import('../tech/tech').default } tech
  5126. * The tech object to query
  5127. *
  5128. * @return {Array}
  5129. * A serializable javascript representation of the {@link Tech}s
  5130. * {@link TextTrackList}.
  5131. */
  5132. const textTracksToJson = function (tech) {
  5133. const trackEls = tech.$$('track');
  5134. const trackObjs = Array.prototype.map.call(trackEls, t => t.track);
  5135. const tracks = Array.prototype.map.call(trackEls, function (trackEl) {
  5136. const json = trackToJson_(trackEl.track);
  5137. if (trackEl.src) {
  5138. json.src = trackEl.src;
  5139. }
  5140. return json;
  5141. });
  5142. return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
  5143. return trackObjs.indexOf(track) === -1;
  5144. }).map(trackToJson_));
  5145. };
  5146. /**
  5147. * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript
  5148. * object {@link TextTrack} representations.
  5149. *
  5150. * @param {Array} json
  5151. * An array of `TextTrack` representation objects, like those that would be
  5152. * produced by `textTracksToJson`.
  5153. *
  5154. * @param {Tech} tech
  5155. * The `Tech` to create the `TextTrack`s on.
  5156. */
  5157. const jsonToTextTracks = function (json, tech) {
  5158. json.forEach(function (track) {
  5159. const addedTrack = tech.addRemoteTextTrack(track).track;
  5160. if (!track.src && track.cues) {
  5161. track.cues.forEach(cue => addedTrack.addCue(cue));
  5162. }
  5163. });
  5164. return tech.textTracks();
  5165. };
  5166. var textTrackConverter = {
  5167. textTracksToJson,
  5168. jsonToTextTracks,
  5169. trackToJson_
  5170. };
  5171. /**
  5172. * @file modal-dialog.js
  5173. */
  5174. const MODAL_CLASS_NAME = 'vjs-modal-dialog';
  5175. /**
  5176. * The `ModalDialog` displays over the video and its controls, which blocks
  5177. * interaction with the player until it is closed.
  5178. *
  5179. * Modal dialogs include a "Close" button and will close when that button
  5180. * is activated - or when ESC is pressed anywhere.
  5181. *
  5182. * @extends Component
  5183. */
  5184. class ModalDialog extends Component$1 {
  5185. /**
  5186. * Create an instance of this class.
  5187. *
  5188. * @param { import('./player').default } player
  5189. * The `Player` that this class should be attached to.
  5190. *
  5191. * @param {Object} [options]
  5192. * The key/value store of player options.
  5193. *
  5194. * @param { import('./utils/dom').ContentDescriptor} [options.content=undefined]
  5195. * Provide customized content for this modal.
  5196. *
  5197. * @param {string} [options.description]
  5198. * A text description for the modal, primarily for accessibility.
  5199. *
  5200. * @param {boolean} [options.fillAlways=false]
  5201. * Normally, modals are automatically filled only the first time
  5202. * they open. This tells the modal to refresh its content
  5203. * every time it opens.
  5204. *
  5205. * @param {string} [options.label]
  5206. * A text label for the modal, primarily for accessibility.
  5207. *
  5208. * @param {boolean} [options.pauseOnOpen=true]
  5209. * If `true`, playback will will be paused if playing when
  5210. * the modal opens, and resumed when it closes.
  5211. *
  5212. * @param {boolean} [options.temporary=true]
  5213. * If `true`, the modal can only be opened once; it will be
  5214. * disposed as soon as it's closed.
  5215. *
  5216. * @param {boolean} [options.uncloseable=false]
  5217. * If `true`, the user will not be able to close the modal
  5218. * through the UI in the normal ways. Programmatic closing is
  5219. * still possible.
  5220. */
  5221. constructor(player, options) {
  5222. super(player, options);
  5223. this.handleKeyDown_ = e => this.handleKeyDown(e);
  5224. this.close_ = e => this.close(e);
  5225. this.opened_ = this.hasBeenOpened_ = this.hasBeenFilled_ = false;
  5226. this.closeable(!this.options_.uncloseable);
  5227. this.content(this.options_.content);
  5228. // Make sure the contentEl is defined AFTER any children are initialized
  5229. // because we only want the contents of the modal in the contentEl
  5230. // (not the UI elements like the close button).
  5231. this.contentEl_ = createEl('div', {
  5232. className: `${MODAL_CLASS_NAME}-content`
  5233. }, {
  5234. role: 'document'
  5235. });
  5236. this.descEl_ = createEl('p', {
  5237. className: `${MODAL_CLASS_NAME}-description vjs-control-text`,
  5238. id: this.el().getAttribute('aria-describedby')
  5239. });
  5240. textContent(this.descEl_, this.description());
  5241. this.el_.appendChild(this.descEl_);
  5242. this.el_.appendChild(this.contentEl_);
  5243. }
  5244. /**
  5245. * Create the `ModalDialog`'s DOM element
  5246. *
  5247. * @return {Element}
  5248. * The DOM element that gets created.
  5249. */
  5250. createEl() {
  5251. return super.createEl('div', {
  5252. className: this.buildCSSClass(),
  5253. tabIndex: -1
  5254. }, {
  5255. 'aria-describedby': `${this.id()}_description`,
  5256. 'aria-hidden': 'true',
  5257. 'aria-label': this.label(),
  5258. 'role': 'dialog'
  5259. });
  5260. }
  5261. dispose() {
  5262. this.contentEl_ = null;
  5263. this.descEl_ = null;
  5264. this.previouslyActiveEl_ = null;
  5265. super.dispose();
  5266. }
  5267. /**
  5268. * Builds the default DOM `className`.
  5269. *
  5270. * @return {string}
  5271. * The DOM `className` for this object.
  5272. */
  5273. buildCSSClass() {
  5274. return `${MODAL_CLASS_NAME} vjs-hidden ${super.buildCSSClass()}`;
  5275. }
  5276. /**
  5277. * Returns the label string for this modal. Primarily used for accessibility.
  5278. *
  5279. * @return {string}
  5280. * the localized or raw label of this modal.
  5281. */
  5282. label() {
  5283. return this.localize(this.options_.label || 'Modal Window');
  5284. }
  5285. /**
  5286. * Returns the description string for this modal. Primarily used for
  5287. * accessibility.
  5288. *
  5289. * @return {string}
  5290. * The localized or raw description of this modal.
  5291. */
  5292. description() {
  5293. let desc = this.options_.description || this.localize('This is a modal window.');
  5294. // Append a universal closeability message if the modal is closeable.
  5295. if (this.closeable()) {
  5296. desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.');
  5297. }
  5298. return desc;
  5299. }
  5300. /**
  5301. * Opens the modal.
  5302. *
  5303. * @fires ModalDialog#beforemodalopen
  5304. * @fires ModalDialog#modalopen
  5305. */
  5306. open() {
  5307. if (!this.opened_) {
  5308. const player = this.player();
  5309. /**
  5310. * Fired just before a `ModalDialog` is opened.
  5311. *
  5312. * @event ModalDialog#beforemodalopen
  5313. * @type {Event}
  5314. */
  5315. this.trigger('beforemodalopen');
  5316. this.opened_ = true;
  5317. // Fill content if the modal has never opened before and
  5318. // never been filled.
  5319. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {
  5320. this.fill();
  5321. }
  5322. // If the player was playing, pause it and take note of its previously
  5323. // playing state.
  5324. this.wasPlaying_ = !player.paused();
  5325. if (this.options_.pauseOnOpen && this.wasPlaying_) {
  5326. player.pause();
  5327. }
  5328. this.on('keydown', this.handleKeyDown_);
  5329. // Hide controls and note if they were enabled.
  5330. this.hadControls_ = player.controls();
  5331. player.controls(false);
  5332. this.show();
  5333. this.conditionalFocus_();
  5334. this.el().setAttribute('aria-hidden', 'false');
  5335. /**
  5336. * Fired just after a `ModalDialog` is opened.
  5337. *
  5338. * @event ModalDialog#modalopen
  5339. * @type {Event}
  5340. */
  5341. this.trigger('modalopen');
  5342. this.hasBeenOpened_ = true;
  5343. }
  5344. }
  5345. /**
  5346. * If the `ModalDialog` is currently open or closed.
  5347. *
  5348. * @param {boolean} [value]
  5349. * If given, it will open (`true`) or close (`false`) the modal.
  5350. *
  5351. * @return {boolean}
  5352. * the current open state of the modaldialog
  5353. */
  5354. opened(value) {
  5355. if (typeof value === 'boolean') {
  5356. this[value ? 'open' : 'close']();
  5357. }
  5358. return this.opened_;
  5359. }
  5360. /**
  5361. * Closes the modal, does nothing if the `ModalDialog` is
  5362. * not open.
  5363. *
  5364. * @fires ModalDialog#beforemodalclose
  5365. * @fires ModalDialog#modalclose
  5366. */
  5367. close() {
  5368. if (!this.opened_) {
  5369. return;
  5370. }
  5371. const player = this.player();
  5372. /**
  5373. * Fired just before a `ModalDialog` is closed.
  5374. *
  5375. * @event ModalDialog#beforemodalclose
  5376. * @type {Event}
  5377. */
  5378. this.trigger('beforemodalclose');
  5379. this.opened_ = false;
  5380. if (this.wasPlaying_ && this.options_.pauseOnOpen) {
  5381. player.play();
  5382. }
  5383. this.off('keydown', this.handleKeyDown_);
  5384. if (this.hadControls_) {
  5385. player.controls(true);
  5386. }
  5387. this.hide();
  5388. this.el().setAttribute('aria-hidden', 'true');
  5389. /**
  5390. * Fired just after a `ModalDialog` is closed.
  5391. *
  5392. * @event ModalDialog#modalclose
  5393. * @type {Event}
  5394. */
  5395. this.trigger('modalclose');
  5396. this.conditionalBlur_();
  5397. if (this.options_.temporary) {
  5398. this.dispose();
  5399. }
  5400. }
  5401. /**
  5402. * Check to see if the `ModalDialog` is closeable via the UI.
  5403. *
  5404. * @param {boolean} [value]
  5405. * If given as a boolean, it will set the `closeable` option.
  5406. *
  5407. * @return {boolean}
  5408. * Returns the final value of the closable option.
  5409. */
  5410. closeable(value) {
  5411. if (typeof value === 'boolean') {
  5412. const closeable = this.closeable_ = !!value;
  5413. let close = this.getChild('closeButton');
  5414. // If this is being made closeable and has no close button, add one.
  5415. if (closeable && !close) {
  5416. // The close button should be a child of the modal - not its
  5417. // content element, so temporarily change the content element.
  5418. const temp = this.contentEl_;
  5419. this.contentEl_ = this.el_;
  5420. close = this.addChild('closeButton', {
  5421. controlText: 'Close Modal Dialog'
  5422. });
  5423. this.contentEl_ = temp;
  5424. this.on(close, 'close', this.close_);
  5425. }
  5426. // If this is being made uncloseable and has a close button, remove it.
  5427. if (!closeable && close) {
  5428. this.off(close, 'close', this.close_);
  5429. this.removeChild(close);
  5430. close.dispose();
  5431. }
  5432. }
  5433. return this.closeable_;
  5434. }
  5435. /**
  5436. * Fill the modal's content element with the modal's "content" option.
  5437. * The content element will be emptied before this change takes place.
  5438. */
  5439. fill() {
  5440. this.fillWith(this.content());
  5441. }
  5442. /**
  5443. * Fill the modal's content element with arbitrary content.
  5444. * The content element will be emptied before this change takes place.
  5445. *
  5446. * @fires ModalDialog#beforemodalfill
  5447. * @fires ModalDialog#modalfill
  5448. *
  5449. * @param { import('./utils/dom').ContentDescriptor} [content]
  5450. * The same rules apply to this as apply to the `content` option.
  5451. */
  5452. fillWith(content) {
  5453. const contentEl = this.contentEl();
  5454. const parentEl = contentEl.parentNode;
  5455. const nextSiblingEl = contentEl.nextSibling;
  5456. /**
  5457. * Fired just before a `ModalDialog` is filled with content.
  5458. *
  5459. * @event ModalDialog#beforemodalfill
  5460. * @type {Event}
  5461. */
  5462. this.trigger('beforemodalfill');
  5463. this.hasBeenFilled_ = true;
  5464. // Detach the content element from the DOM before performing
  5465. // manipulation to avoid modifying the live DOM multiple times.
  5466. parentEl.removeChild(contentEl);
  5467. this.empty();
  5468. insertContent(contentEl, content);
  5469. /**
  5470. * Fired just after a `ModalDialog` is filled with content.
  5471. *
  5472. * @event ModalDialog#modalfill
  5473. * @type {Event}
  5474. */
  5475. this.trigger('modalfill');
  5476. // Re-inject the re-filled content element.
  5477. if (nextSiblingEl) {
  5478. parentEl.insertBefore(contentEl, nextSiblingEl);
  5479. } else {
  5480. parentEl.appendChild(contentEl);
  5481. }
  5482. // make sure that the close button is last in the dialog DOM
  5483. const closeButton = this.getChild('closeButton');
  5484. if (closeButton) {
  5485. parentEl.appendChild(closeButton.el_);
  5486. }
  5487. }
  5488. /**
  5489. * Empties the content element. This happens anytime the modal is filled.
  5490. *
  5491. * @fires ModalDialog#beforemodalempty
  5492. * @fires ModalDialog#modalempty
  5493. */
  5494. empty() {
  5495. /**
  5496. * Fired just before a `ModalDialog` is emptied.
  5497. *
  5498. * @event ModalDialog#beforemodalempty
  5499. * @type {Event}
  5500. */
  5501. this.trigger('beforemodalempty');
  5502. emptyEl(this.contentEl());
  5503. /**
  5504. * Fired just after a `ModalDialog` is emptied.
  5505. *
  5506. * @event ModalDialog#modalempty
  5507. * @type {Event}
  5508. */
  5509. this.trigger('modalempty');
  5510. }
  5511. /**
  5512. * Gets or sets the modal content, which gets normalized before being
  5513. * rendered into the DOM.
  5514. *
  5515. * This does not update the DOM or fill the modal, but it is called during
  5516. * that process.
  5517. *
  5518. * @param { import('./utils/dom').ContentDescriptor} [value]
  5519. * If defined, sets the internal content value to be used on the
  5520. * next call(s) to `fill`. This value is normalized before being
  5521. * inserted. To "clear" the internal content value, pass `null`.
  5522. *
  5523. * @return { import('./utils/dom').ContentDescriptor}
  5524. * The current content of the modal dialog
  5525. */
  5526. content(value) {
  5527. if (typeof value !== 'undefined') {
  5528. this.content_ = value;
  5529. }
  5530. return this.content_;
  5531. }
  5532. /**
  5533. * conditionally focus the modal dialog if focus was previously on the player.
  5534. *
  5535. * @private
  5536. */
  5537. conditionalFocus_() {
  5538. const activeEl = document.activeElement;
  5539. const playerEl = this.player_.el_;
  5540. this.previouslyActiveEl_ = null;
  5541. if (playerEl.contains(activeEl) || playerEl === activeEl) {
  5542. this.previouslyActiveEl_ = activeEl;
  5543. this.focus();
  5544. }
  5545. }
  5546. /**
  5547. * conditionally blur the element and refocus the last focused element
  5548. *
  5549. * @private
  5550. */
  5551. conditionalBlur_() {
  5552. if (this.previouslyActiveEl_) {
  5553. this.previouslyActiveEl_.focus();
  5554. this.previouslyActiveEl_ = null;
  5555. }
  5556. }
  5557. /**
  5558. * Keydown handler. Attached when modal is focused.
  5559. *
  5560. * @listens keydown
  5561. */
  5562. handleKeyDown(event) {
  5563. // Do not allow keydowns to reach out of the modal dialog.
  5564. event.stopPropagation();
  5565. if (keycode.isEventKey(event, 'Escape') && this.closeable()) {
  5566. event.preventDefault();
  5567. this.close();
  5568. return;
  5569. }
  5570. // exit early if it isn't a tab key
  5571. if (!keycode.isEventKey(event, 'Tab')) {
  5572. return;
  5573. }
  5574. const focusableEls = this.focusableEls_();
  5575. const activeEl = this.el_.querySelector(':focus');
  5576. let focusIndex;
  5577. for (let i = 0; i < focusableEls.length; i++) {
  5578. if (activeEl === focusableEls[i]) {
  5579. focusIndex = i;
  5580. break;
  5581. }
  5582. }
  5583. if (document.activeElement === this.el_) {
  5584. focusIndex = 0;
  5585. }
  5586. if (event.shiftKey && focusIndex === 0) {
  5587. focusableEls[focusableEls.length - 1].focus();
  5588. event.preventDefault();
  5589. } else if (!event.shiftKey && focusIndex === focusableEls.length - 1) {
  5590. focusableEls[0].focus();
  5591. event.preventDefault();
  5592. }
  5593. }
  5594. /**
  5595. * get all focusable elements
  5596. *
  5597. * @private
  5598. */
  5599. focusableEls_() {
  5600. const allChildren = this.el_.querySelectorAll('*');
  5601. return Array.prototype.filter.call(allChildren, child => {
  5602. return (child instanceof window$1.HTMLAnchorElement || child instanceof window$1.HTMLAreaElement) && child.hasAttribute('href') || (child instanceof window$1.HTMLInputElement || child instanceof window$1.HTMLSelectElement || child instanceof window$1.HTMLTextAreaElement || child instanceof window$1.HTMLButtonElement) && !child.hasAttribute('disabled') || child instanceof window$1.HTMLIFrameElement || child instanceof window$1.HTMLObjectElement || child instanceof window$1.HTMLEmbedElement || child.hasAttribute('tabindex') && child.getAttribute('tabindex') !== -1 || child.hasAttribute('contenteditable');
  5603. });
  5604. }
  5605. }
  5606. /**
  5607. * Default options for `ModalDialog` default options.
  5608. *
  5609. * @type {Object}
  5610. * @private
  5611. */
  5612. ModalDialog.prototype.options_ = {
  5613. pauseOnOpen: true,
  5614. temporary: true
  5615. };
  5616. Component$1.registerComponent('ModalDialog', ModalDialog);
  5617. /**
  5618. * @file track-list.js
  5619. */
  5620. /**
  5621. * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and
  5622. * {@link VideoTrackList}
  5623. *
  5624. * @extends EventTarget
  5625. */
  5626. class TrackList extends EventTarget$2 {
  5627. /**
  5628. * Create an instance of this class
  5629. *
  5630. * @param { import('./track').default[] } tracks
  5631. * A list of tracks to initialize the list with.
  5632. *
  5633. * @abstract
  5634. */
  5635. constructor(tracks = []) {
  5636. super();
  5637. this.tracks_ = [];
  5638. /**
  5639. * @memberof TrackList
  5640. * @member {number} length
  5641. * The current number of `Track`s in the this Trackist.
  5642. * @instance
  5643. */
  5644. Object.defineProperty(this, 'length', {
  5645. get() {
  5646. return this.tracks_.length;
  5647. }
  5648. });
  5649. for (let i = 0; i < tracks.length; i++) {
  5650. this.addTrack(tracks[i]);
  5651. }
  5652. }
  5653. /**
  5654. * Add a {@link Track} to the `TrackList`
  5655. *
  5656. * @param { import('./track').default } track
  5657. * The audio, video, or text track to add to the list.
  5658. *
  5659. * @fires TrackList#addtrack
  5660. */
  5661. addTrack(track) {
  5662. const index = this.tracks_.length;
  5663. if (!('' + index in this)) {
  5664. Object.defineProperty(this, index, {
  5665. get() {
  5666. return this.tracks_[index];
  5667. }
  5668. });
  5669. }
  5670. // Do not add duplicate tracks
  5671. if (this.tracks_.indexOf(track) === -1) {
  5672. this.tracks_.push(track);
  5673. /**
  5674. * Triggered when a track is added to a track list.
  5675. *
  5676. * @event TrackList#addtrack
  5677. * @type {Event}
  5678. * @property {Track} track
  5679. * A reference to track that was added.
  5680. */
  5681. this.trigger({
  5682. track,
  5683. type: 'addtrack',
  5684. target: this
  5685. });
  5686. }
  5687. /**
  5688. * Triggered when a track label is changed.
  5689. *
  5690. * @event TrackList#addtrack
  5691. * @type {Event}
  5692. * @property {Track} track
  5693. * A reference to track that was added.
  5694. */
  5695. track.labelchange_ = () => {
  5696. this.trigger({
  5697. track,
  5698. type: 'labelchange',
  5699. target: this
  5700. });
  5701. };
  5702. if (isEvented(track)) {
  5703. track.addEventListener('labelchange', track.labelchange_);
  5704. }
  5705. }
  5706. /**
  5707. * Remove a {@link Track} from the `TrackList`
  5708. *
  5709. * @param { import('./track').default } rtrack
  5710. * The audio, video, or text track to remove from the list.
  5711. *
  5712. * @fires TrackList#removetrack
  5713. */
  5714. removeTrack(rtrack) {
  5715. let track;
  5716. for (let i = 0, l = this.length; i < l; i++) {
  5717. if (this[i] === rtrack) {
  5718. track = this[i];
  5719. if (track.off) {
  5720. track.off();
  5721. }
  5722. this.tracks_.splice(i, 1);
  5723. break;
  5724. }
  5725. }
  5726. if (!track) {
  5727. return;
  5728. }
  5729. /**
  5730. * Triggered when a track is removed from track list.
  5731. *
  5732. * @event TrackList#removetrack
  5733. * @type {Event}
  5734. * @property {Track} track
  5735. * A reference to track that was removed.
  5736. */
  5737. this.trigger({
  5738. track,
  5739. type: 'removetrack',
  5740. target: this
  5741. });
  5742. }
  5743. /**
  5744. * Get a Track from the TrackList by a tracks id
  5745. *
  5746. * @param {string} id - the id of the track to get
  5747. * @method getTrackById
  5748. * @return { import('./track').default }
  5749. * @private
  5750. */
  5751. getTrackById(id) {
  5752. let result = null;
  5753. for (let i = 0, l = this.length; i < l; i++) {
  5754. const track = this[i];
  5755. if (track.id === id) {
  5756. result = track;
  5757. break;
  5758. }
  5759. }
  5760. return result;
  5761. }
  5762. }
  5763. /**
  5764. * Triggered when a different track is selected/enabled.
  5765. *
  5766. * @event TrackList#change
  5767. * @type {Event}
  5768. */
  5769. /**
  5770. * Events that can be called with on + eventName. See {@link EventHandler}.
  5771. *
  5772. * @property {Object} TrackList#allowedEvents_
  5773. * @private
  5774. */
  5775. TrackList.prototype.allowedEvents_ = {
  5776. change: 'change',
  5777. addtrack: 'addtrack',
  5778. removetrack: 'removetrack',
  5779. labelchange: 'labelchange'
  5780. };
  5781. // emulate attribute EventHandler support to allow for feature detection
  5782. for (const event in TrackList.prototype.allowedEvents_) {
  5783. TrackList.prototype['on' + event] = null;
  5784. }
  5785. /**
  5786. * @file audio-track-list.js
  5787. */
  5788. /**
  5789. * Anywhere we call this function we diverge from the spec
  5790. * as we only support one enabled audiotrack at a time
  5791. *
  5792. * @param {AudioTrackList} list
  5793. * list to work on
  5794. *
  5795. * @param { import('./audio-track').default } track
  5796. * The track to skip
  5797. *
  5798. * @private
  5799. */
  5800. const disableOthers$1 = function (list, track) {
  5801. for (let i = 0; i < list.length; i++) {
  5802. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  5803. continue;
  5804. }
  5805. // another audio track is enabled, disable it
  5806. list[i].enabled = false;
  5807. }
  5808. };
  5809. /**
  5810. * The current list of {@link AudioTrack} for a media file.
  5811. *
  5812. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist}
  5813. * @extends TrackList
  5814. */
  5815. class AudioTrackList extends TrackList {
  5816. /**
  5817. * Create an instance of this class.
  5818. *
  5819. * @param {AudioTrack[]} [tracks=[]]
  5820. * A list of `AudioTrack` to instantiate the list with.
  5821. */
  5822. constructor(tracks = []) {
  5823. // make sure only 1 track is enabled
  5824. // sorted from last index to first index
  5825. for (let i = tracks.length - 1; i >= 0; i--) {
  5826. if (tracks[i].enabled) {
  5827. disableOthers$1(tracks, tracks[i]);
  5828. break;
  5829. }
  5830. }
  5831. super(tracks);
  5832. this.changing_ = false;
  5833. }
  5834. /**
  5835. * Add an {@link AudioTrack} to the `AudioTrackList`.
  5836. *
  5837. * @param { import('./audio-track').default } track
  5838. * The AudioTrack to add to the list
  5839. *
  5840. * @fires TrackList#addtrack
  5841. */
  5842. addTrack(track) {
  5843. if (track.enabled) {
  5844. disableOthers$1(this, track);
  5845. }
  5846. super.addTrack(track);
  5847. // native tracks don't have this
  5848. if (!track.addEventListener) {
  5849. return;
  5850. }
  5851. track.enabledChange_ = () => {
  5852. // when we are disabling other tracks (since we don't support
  5853. // more than one track at a time) we will set changing_
  5854. // to true so that we don't trigger additional change events
  5855. if (this.changing_) {
  5856. return;
  5857. }
  5858. this.changing_ = true;
  5859. disableOthers$1(this, track);
  5860. this.changing_ = false;
  5861. this.trigger('change');
  5862. };
  5863. /**
  5864. * @listens AudioTrack#enabledchange
  5865. * @fires TrackList#change
  5866. */
  5867. track.addEventListener('enabledchange', track.enabledChange_);
  5868. }
  5869. removeTrack(rtrack) {
  5870. super.removeTrack(rtrack);
  5871. if (rtrack.removeEventListener && rtrack.enabledChange_) {
  5872. rtrack.removeEventListener('enabledchange', rtrack.enabledChange_);
  5873. rtrack.enabledChange_ = null;
  5874. }
  5875. }
  5876. }
  5877. /**
  5878. * @file video-track-list.js
  5879. */
  5880. /**
  5881. * Un-select all other {@link VideoTrack}s that are selected.
  5882. *
  5883. * @param {VideoTrackList} list
  5884. * list to work on
  5885. *
  5886. * @param { import('./video-track').default } track
  5887. * The track to skip
  5888. *
  5889. * @private
  5890. */
  5891. const disableOthers = function (list, track) {
  5892. for (let i = 0; i < list.length; i++) {
  5893. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  5894. continue;
  5895. }
  5896. // another video track is enabled, disable it
  5897. list[i].selected = false;
  5898. }
  5899. };
  5900. /**
  5901. * The current list of {@link VideoTrack} for a video.
  5902. *
  5903. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist}
  5904. * @extends TrackList
  5905. */
  5906. class VideoTrackList extends TrackList {
  5907. /**
  5908. * Create an instance of this class.
  5909. *
  5910. * @param {VideoTrack[]} [tracks=[]]
  5911. * A list of `VideoTrack` to instantiate the list with.
  5912. */
  5913. constructor(tracks = []) {
  5914. // make sure only 1 track is enabled
  5915. // sorted from last index to first index
  5916. for (let i = tracks.length - 1; i >= 0; i--) {
  5917. if (tracks[i].selected) {
  5918. disableOthers(tracks, tracks[i]);
  5919. break;
  5920. }
  5921. }
  5922. super(tracks);
  5923. this.changing_ = false;
  5924. /**
  5925. * @member {number} VideoTrackList#selectedIndex
  5926. * The current index of the selected {@link VideoTrack`}.
  5927. */
  5928. Object.defineProperty(this, 'selectedIndex', {
  5929. get() {
  5930. for (let i = 0; i < this.length; i++) {
  5931. if (this[i].selected) {
  5932. return i;
  5933. }
  5934. }
  5935. return -1;
  5936. },
  5937. set() {}
  5938. });
  5939. }
  5940. /**
  5941. * Add a {@link VideoTrack} to the `VideoTrackList`.
  5942. *
  5943. * @param { import('./video-track').default } track
  5944. * The VideoTrack to add to the list
  5945. *
  5946. * @fires TrackList#addtrack
  5947. */
  5948. addTrack(track) {
  5949. if (track.selected) {
  5950. disableOthers(this, track);
  5951. }
  5952. super.addTrack(track);
  5953. // native tracks don't have this
  5954. if (!track.addEventListener) {
  5955. return;
  5956. }
  5957. track.selectedChange_ = () => {
  5958. if (this.changing_) {
  5959. return;
  5960. }
  5961. this.changing_ = true;
  5962. disableOthers(this, track);
  5963. this.changing_ = false;
  5964. this.trigger('change');
  5965. };
  5966. /**
  5967. * @listens VideoTrack#selectedchange
  5968. * @fires TrackList#change
  5969. */
  5970. track.addEventListener('selectedchange', track.selectedChange_);
  5971. }
  5972. removeTrack(rtrack) {
  5973. super.removeTrack(rtrack);
  5974. if (rtrack.removeEventListener && rtrack.selectedChange_) {
  5975. rtrack.removeEventListener('selectedchange', rtrack.selectedChange_);
  5976. rtrack.selectedChange_ = null;
  5977. }
  5978. }
  5979. }
  5980. /**
  5981. * @file text-track-list.js
  5982. */
  5983. /**
  5984. * The current list of {@link TextTrack} for a media file.
  5985. *
  5986. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist}
  5987. * @extends TrackList
  5988. */
  5989. class TextTrackList extends TrackList {
  5990. /**
  5991. * Add a {@link TextTrack} to the `TextTrackList`
  5992. *
  5993. * @param { import('./text-track').default } track
  5994. * The text track to add to the list.
  5995. *
  5996. * @fires TrackList#addtrack
  5997. */
  5998. addTrack(track) {
  5999. super.addTrack(track);
  6000. if (!this.queueChange_) {
  6001. this.queueChange_ = () => this.queueTrigger('change');
  6002. }
  6003. if (!this.triggerSelectedlanguagechange) {
  6004. this.triggerSelectedlanguagechange_ = () => this.trigger('selectedlanguagechange');
  6005. }
  6006. /**
  6007. * @listens TextTrack#modechange
  6008. * @fires TrackList#change
  6009. */
  6010. track.addEventListener('modechange', this.queueChange_);
  6011. const nonLanguageTextTrackKind = ['metadata', 'chapters'];
  6012. if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) {
  6013. track.addEventListener('modechange', this.triggerSelectedlanguagechange_);
  6014. }
  6015. }
  6016. removeTrack(rtrack) {
  6017. super.removeTrack(rtrack);
  6018. // manually remove the event handlers we added
  6019. if (rtrack.removeEventListener) {
  6020. if (this.queueChange_) {
  6021. rtrack.removeEventListener('modechange', this.queueChange_);
  6022. }
  6023. if (this.selectedlanguagechange_) {
  6024. rtrack.removeEventListener('modechange', this.triggerSelectedlanguagechange_);
  6025. }
  6026. }
  6027. }
  6028. }
  6029. /**
  6030. * @file html-track-element-list.js
  6031. */
  6032. /**
  6033. * The current list of {@link HtmlTrackElement}s.
  6034. */
  6035. class HtmlTrackElementList {
  6036. /**
  6037. * Create an instance of this class.
  6038. *
  6039. * @param {HtmlTrackElement[]} [tracks=[]]
  6040. * A list of `HtmlTrackElement` to instantiate the list with.
  6041. */
  6042. constructor(trackElements = []) {
  6043. this.trackElements_ = [];
  6044. /**
  6045. * @memberof HtmlTrackElementList
  6046. * @member {number} length
  6047. * The current number of `Track`s in the this Trackist.
  6048. * @instance
  6049. */
  6050. Object.defineProperty(this, 'length', {
  6051. get() {
  6052. return this.trackElements_.length;
  6053. }
  6054. });
  6055. for (let i = 0, length = trackElements.length; i < length; i++) {
  6056. this.addTrackElement_(trackElements[i]);
  6057. }
  6058. }
  6059. /**
  6060. * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList`
  6061. *
  6062. * @param {HtmlTrackElement} trackElement
  6063. * The track element to add to the list.
  6064. *
  6065. * @private
  6066. */
  6067. addTrackElement_(trackElement) {
  6068. const index = this.trackElements_.length;
  6069. if (!('' + index in this)) {
  6070. Object.defineProperty(this, index, {
  6071. get() {
  6072. return this.trackElements_[index];
  6073. }
  6074. });
  6075. }
  6076. // Do not add duplicate elements
  6077. if (this.trackElements_.indexOf(trackElement) === -1) {
  6078. this.trackElements_.push(trackElement);
  6079. }
  6080. }
  6081. /**
  6082. * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an
  6083. * {@link TextTrack}.
  6084. *
  6085. * @param {TextTrack} track
  6086. * The track associated with a track element.
  6087. *
  6088. * @return {HtmlTrackElement|undefined}
  6089. * The track element that was found or undefined.
  6090. *
  6091. * @private
  6092. */
  6093. getTrackElementByTrack_(track) {
  6094. let trackElement_;
  6095. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6096. if (track === this.trackElements_[i].track) {
  6097. trackElement_ = this.trackElements_[i];
  6098. break;
  6099. }
  6100. }
  6101. return trackElement_;
  6102. }
  6103. /**
  6104. * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList`
  6105. *
  6106. * @param {HtmlTrackElement} trackElement
  6107. * The track element to remove from the list.
  6108. *
  6109. * @private
  6110. */
  6111. removeTrackElement_(trackElement) {
  6112. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6113. if (trackElement === this.trackElements_[i]) {
  6114. if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === 'function') {
  6115. this.trackElements_[i].track.off();
  6116. }
  6117. if (typeof this.trackElements_[i].off === 'function') {
  6118. this.trackElements_[i].off();
  6119. }
  6120. this.trackElements_.splice(i, 1);
  6121. break;
  6122. }
  6123. }
  6124. }
  6125. }
  6126. /**
  6127. * @file text-track-cue-list.js
  6128. */
  6129. /**
  6130. * @typedef {Object} TextTrackCueList~TextTrackCue
  6131. *
  6132. * @property {string} id
  6133. * The unique id for this text track cue
  6134. *
  6135. * @property {number} startTime
  6136. * The start time for this text track cue
  6137. *
  6138. * @property {number} endTime
  6139. * The end time for this text track cue
  6140. *
  6141. * @property {boolean} pauseOnExit
  6142. * Pause when the end time is reached if true.
  6143. *
  6144. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue}
  6145. */
  6146. /**
  6147. * A List of TextTrackCues.
  6148. *
  6149. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist}
  6150. */
  6151. class TextTrackCueList {
  6152. /**
  6153. * Create an instance of this class..
  6154. *
  6155. * @param {Array} cues
  6156. * A list of cues to be initialized with
  6157. */
  6158. constructor(cues) {
  6159. TextTrackCueList.prototype.setCues_.call(this, cues);
  6160. /**
  6161. * @memberof TextTrackCueList
  6162. * @member {number} length
  6163. * The current number of `TextTrackCue`s in the TextTrackCueList.
  6164. * @instance
  6165. */
  6166. Object.defineProperty(this, 'length', {
  6167. get() {
  6168. return this.length_;
  6169. }
  6170. });
  6171. }
  6172. /**
  6173. * A setter for cues in this list. Creates getters
  6174. * an an index for the cues.
  6175. *
  6176. * @param {Array} cues
  6177. * An array of cues to set
  6178. *
  6179. * @private
  6180. */
  6181. setCues_(cues) {
  6182. const oldLength = this.length || 0;
  6183. let i = 0;
  6184. const l = cues.length;
  6185. this.cues_ = cues;
  6186. this.length_ = cues.length;
  6187. const defineProp = function (index) {
  6188. if (!('' + index in this)) {
  6189. Object.defineProperty(this, '' + index, {
  6190. get() {
  6191. return this.cues_[index];
  6192. }
  6193. });
  6194. }
  6195. };
  6196. if (oldLength < l) {
  6197. i = oldLength;
  6198. for (; i < l; i++) {
  6199. defineProp.call(this, i);
  6200. }
  6201. }
  6202. }
  6203. /**
  6204. * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id.
  6205. *
  6206. * @param {string} id
  6207. * The id of the cue that should be searched for.
  6208. *
  6209. * @return {TextTrackCueList~TextTrackCue|null}
  6210. * A single cue or null if none was found.
  6211. */
  6212. getCueById(id) {
  6213. let result = null;
  6214. for (let i = 0, l = this.length; i < l; i++) {
  6215. const cue = this[i];
  6216. if (cue.id === id) {
  6217. result = cue;
  6218. break;
  6219. }
  6220. }
  6221. return result;
  6222. }
  6223. }
  6224. /**
  6225. * @file track-kinds.js
  6226. */
  6227. /**
  6228. * All possible `VideoTrackKind`s
  6229. *
  6230. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind
  6231. * @typedef VideoTrack~Kind
  6232. * @enum
  6233. */
  6234. const VideoTrackKind = {
  6235. alternative: 'alternative',
  6236. captions: 'captions',
  6237. main: 'main',
  6238. sign: 'sign',
  6239. subtitles: 'subtitles',
  6240. commentary: 'commentary'
  6241. };
  6242. /**
  6243. * All possible `AudioTrackKind`s
  6244. *
  6245. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind
  6246. * @typedef AudioTrack~Kind
  6247. * @enum
  6248. */
  6249. const AudioTrackKind = {
  6250. 'alternative': 'alternative',
  6251. 'descriptions': 'descriptions',
  6252. 'main': 'main',
  6253. 'main-desc': 'main-desc',
  6254. 'translation': 'translation',
  6255. 'commentary': 'commentary'
  6256. };
  6257. /**
  6258. * All possible `TextTrackKind`s
  6259. *
  6260. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind
  6261. * @typedef TextTrack~Kind
  6262. * @enum
  6263. */
  6264. const TextTrackKind = {
  6265. subtitles: 'subtitles',
  6266. captions: 'captions',
  6267. descriptions: 'descriptions',
  6268. chapters: 'chapters',
  6269. metadata: 'metadata'
  6270. };
  6271. /**
  6272. * All possible `TextTrackMode`s
  6273. *
  6274. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
  6275. * @typedef TextTrack~Mode
  6276. * @enum
  6277. */
  6278. const TextTrackMode = {
  6279. disabled: 'disabled',
  6280. hidden: 'hidden',
  6281. showing: 'showing'
  6282. };
  6283. /**
  6284. * @file track.js
  6285. */
  6286. /**
  6287. * A Track class that contains all of the common functionality for {@link AudioTrack},
  6288. * {@link VideoTrack}, and {@link TextTrack}.
  6289. *
  6290. * > Note: This class should not be used directly
  6291. *
  6292. * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html}
  6293. * @extends EventTarget
  6294. * @abstract
  6295. */
  6296. class Track extends EventTarget$2 {
  6297. /**
  6298. * Create an instance of this class.
  6299. *
  6300. * @param {Object} [options={}]
  6301. * Object of option names and values
  6302. *
  6303. * @param {string} [options.kind='']
  6304. * A valid kind for the track type you are creating.
  6305. *
  6306. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6307. * A unique id for this AudioTrack.
  6308. *
  6309. * @param {string} [options.label='']
  6310. * The menu label for this track.
  6311. *
  6312. * @param {string} [options.language='']
  6313. * A valid two character language code.
  6314. *
  6315. * @abstract
  6316. */
  6317. constructor(options = {}) {
  6318. super();
  6319. const trackProps = {
  6320. id: options.id || 'vjs_track_' + newGUID(),
  6321. kind: options.kind || '',
  6322. language: options.language || ''
  6323. };
  6324. let label = options.label || '';
  6325. /**
  6326. * @memberof Track
  6327. * @member {string} id
  6328. * The id of this track. Cannot be changed after creation.
  6329. * @instance
  6330. *
  6331. * @readonly
  6332. */
  6333. /**
  6334. * @memberof Track
  6335. * @member {string} kind
  6336. * The kind of track that this is. Cannot be changed after creation.
  6337. * @instance
  6338. *
  6339. * @readonly
  6340. */
  6341. /**
  6342. * @memberof Track
  6343. * @member {string} language
  6344. * The two letter language code for this track. Cannot be changed after
  6345. * creation.
  6346. * @instance
  6347. *
  6348. * @readonly
  6349. */
  6350. for (const key in trackProps) {
  6351. Object.defineProperty(this, key, {
  6352. get() {
  6353. return trackProps[key];
  6354. },
  6355. set() {}
  6356. });
  6357. }
  6358. /**
  6359. * @memberof Track
  6360. * @member {string} label
  6361. * The label of this track. Cannot be changed after creation.
  6362. * @instance
  6363. *
  6364. * @fires Track#labelchange
  6365. */
  6366. Object.defineProperty(this, 'label', {
  6367. get() {
  6368. return label;
  6369. },
  6370. set(newLabel) {
  6371. if (newLabel !== label) {
  6372. label = newLabel;
  6373. /**
  6374. * An event that fires when label changes on this track.
  6375. *
  6376. * > Note: This is not part of the spec!
  6377. *
  6378. * @event Track#labelchange
  6379. * @type {Event}
  6380. */
  6381. this.trigger('labelchange');
  6382. }
  6383. }
  6384. });
  6385. }
  6386. }
  6387. /**
  6388. * @file url.js
  6389. * @module url
  6390. */
  6391. /**
  6392. * @typedef {Object} url:URLObject
  6393. *
  6394. * @property {string} protocol
  6395. * The protocol of the url that was parsed.
  6396. *
  6397. * @property {string} hostname
  6398. * The hostname of the url that was parsed.
  6399. *
  6400. * @property {string} port
  6401. * The port of the url that was parsed.
  6402. *
  6403. * @property {string} pathname
  6404. * The pathname of the url that was parsed.
  6405. *
  6406. * @property {string} search
  6407. * The search query of the url that was parsed.
  6408. *
  6409. * @property {string} hash
  6410. * The hash of the url that was parsed.
  6411. *
  6412. * @property {string} host
  6413. * The host of the url that was parsed.
  6414. */
  6415. /**
  6416. * Resolve and parse the elements of a URL.
  6417. *
  6418. * @function
  6419. * @param {String} url
  6420. * The url to parse
  6421. *
  6422. * @return {url:URLObject}
  6423. * An object of url details
  6424. */
  6425. const parseUrl = function (url) {
  6426. // This entire method can be replace with URL once we are able to drop IE11
  6427. const props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];
  6428. // add the url to an anchor and let the browser parse the URL
  6429. const a = document.createElement('a');
  6430. a.href = url;
  6431. // Copy the specific URL properties to a new object
  6432. // This is also needed for IE because the anchor loses its
  6433. // properties when it's removed from the dom
  6434. const details = {};
  6435. for (let i = 0; i < props.length; i++) {
  6436. details[props[i]] = a[props[i]];
  6437. }
  6438. // IE adds the port to the host property unlike everyone else. If
  6439. // a port identifier is added for standard ports, strip it.
  6440. if (details.protocol === 'http:') {
  6441. details.host = details.host.replace(/:80$/, '');
  6442. }
  6443. if (details.protocol === 'https:') {
  6444. details.host = details.host.replace(/:443$/, '');
  6445. }
  6446. if (!details.protocol) {
  6447. details.protocol = window$1.location.protocol;
  6448. }
  6449. /* istanbul ignore if */
  6450. if (!details.host) {
  6451. details.host = window$1.location.host;
  6452. }
  6453. return details;
  6454. };
  6455. /**
  6456. * Get absolute version of relative URL.
  6457. *
  6458. * @function
  6459. * @param {string} url
  6460. * URL to make absolute
  6461. *
  6462. * @return {string}
  6463. * Absolute URL
  6464. *
  6465. * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  6466. */
  6467. const getAbsoluteURL = function (url) {
  6468. // Check if absolute URL
  6469. if (!url.match(/^https?:\/\//)) {
  6470. // Add the url to an anchor and let the browser parse it to convert to an absolute url
  6471. const a = document.createElement('a');
  6472. a.href = url;
  6473. url = a.href;
  6474. }
  6475. return url;
  6476. };
  6477. /**
  6478. * Returns the extension of the passed file name. It will return an empty string
  6479. * if passed an invalid path.
  6480. *
  6481. * @function
  6482. * @param {string} path
  6483. * The fileName path like '/path/to/file.mp4'
  6484. *
  6485. * @return {string}
  6486. * The extension in lower case or an empty string if no
  6487. * extension could be found.
  6488. */
  6489. const getFileExtension = function (path) {
  6490. if (typeof path === 'string') {
  6491. const splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/;
  6492. const pathParts = splitPathRe.exec(path);
  6493. if (pathParts) {
  6494. return pathParts.pop().toLowerCase();
  6495. }
  6496. }
  6497. return '';
  6498. };
  6499. /**
  6500. * Returns whether the url passed is a cross domain request or not.
  6501. *
  6502. * @function
  6503. * @param {string} url
  6504. * The url to check.
  6505. *
  6506. * @param {Object} [winLoc]
  6507. * the domain to check the url against, defaults to window.location
  6508. *
  6509. * @param {string} [winLoc.protocol]
  6510. * The window location protocol defaults to window.location.protocol
  6511. *
  6512. * @param {string} [winLoc.host]
  6513. * The window location host defaults to window.location.host
  6514. *
  6515. * @return {boolean}
  6516. * Whether it is a cross domain request or not.
  6517. */
  6518. const isCrossOrigin = function (url, winLoc = window$1.location) {
  6519. const urlInfo = parseUrl(url);
  6520. // IE8 protocol relative urls will return ':' for protocol
  6521. const srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol;
  6522. // Check if url is for another domain/origin
  6523. // IE8 doesn't know location.origin, so we won't rely on it here
  6524. const crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host;
  6525. return crossOrigin;
  6526. };
  6527. var Url = /*#__PURE__*/Object.freeze({
  6528. __proto__: null,
  6529. parseUrl: parseUrl,
  6530. getAbsoluteURL: getAbsoluteURL,
  6531. getFileExtension: getFileExtension,
  6532. isCrossOrigin: isCrossOrigin
  6533. });
  6534. /**
  6535. * @file text-track.js
  6536. */
  6537. /**
  6538. * Takes a webvtt file contents and parses it into cues
  6539. *
  6540. * @param {string} srcContent
  6541. * webVTT file contents
  6542. *
  6543. * @param {TextTrack} track
  6544. * TextTrack to add cues to. Cues come from the srcContent.
  6545. *
  6546. * @private
  6547. */
  6548. const parseCues = function (srcContent, track) {
  6549. const parser = new window$1.WebVTT.Parser(window$1, window$1.vttjs, window$1.WebVTT.StringDecoder());
  6550. const errors = [];
  6551. parser.oncue = function (cue) {
  6552. track.addCue(cue);
  6553. };
  6554. parser.onparsingerror = function (error) {
  6555. errors.push(error);
  6556. };
  6557. parser.onflush = function () {
  6558. track.trigger({
  6559. type: 'loadeddata',
  6560. target: track
  6561. });
  6562. };
  6563. parser.parse(srcContent);
  6564. if (errors.length > 0) {
  6565. if (window$1.console && window$1.console.groupCollapsed) {
  6566. window$1.console.groupCollapsed(`Text Track parsing errors for ${track.src}`);
  6567. }
  6568. errors.forEach(error => log$1.error(error));
  6569. if (window$1.console && window$1.console.groupEnd) {
  6570. window$1.console.groupEnd();
  6571. }
  6572. }
  6573. parser.flush();
  6574. };
  6575. /**
  6576. * Load a `TextTrack` from a specified url.
  6577. *
  6578. * @param {string} src
  6579. * Url to load track from.
  6580. *
  6581. * @param {TextTrack} track
  6582. * Track to add cues to. Comes from the content at the end of `url`.
  6583. *
  6584. * @private
  6585. */
  6586. const loadTrack = function (src, track) {
  6587. const opts = {
  6588. uri: src
  6589. };
  6590. const crossOrigin = isCrossOrigin(src);
  6591. if (crossOrigin) {
  6592. opts.cors = crossOrigin;
  6593. }
  6594. const withCredentials = track.tech_.crossOrigin() === 'use-credentials';
  6595. if (withCredentials) {
  6596. opts.withCredentials = withCredentials;
  6597. }
  6598. XHR(opts, bind_(this, function (err, response, responseBody) {
  6599. if (err) {
  6600. return log$1.error(err, response);
  6601. }
  6602. track.loaded_ = true;
  6603. // Make sure that vttjs has loaded, otherwise, wait till it finished loading
  6604. // NOTE: this is only used for the alt/video.novtt.js build
  6605. if (typeof window$1.WebVTT !== 'function') {
  6606. if (track.tech_) {
  6607. // to prevent use before define eslint error, we define loadHandler
  6608. // as a let here
  6609. track.tech_.any(['vttjsloaded', 'vttjserror'], event => {
  6610. if (event.type === 'vttjserror') {
  6611. log$1.error(`vttjs failed to load, stopping trying to process ${track.src}`);
  6612. return;
  6613. }
  6614. return parseCues(responseBody, track);
  6615. });
  6616. }
  6617. } else {
  6618. parseCues(responseBody, track);
  6619. }
  6620. }));
  6621. };
  6622. /**
  6623. * A representation of a single `TextTrack`.
  6624. *
  6625. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack}
  6626. * @extends Track
  6627. */
  6628. class TextTrack extends Track {
  6629. /**
  6630. * Create an instance of this class.
  6631. *
  6632. * @param {Object} options={}
  6633. * Object of option names and values
  6634. *
  6635. * @param { import('../tech/tech').default } options.tech
  6636. * A reference to the tech that owns this TextTrack.
  6637. *
  6638. * @param {TextTrack~Kind} [options.kind='subtitles']
  6639. * A valid text track kind.
  6640. *
  6641. * @param {TextTrack~Mode} [options.mode='disabled']
  6642. * A valid text track mode.
  6643. *
  6644. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6645. * A unique id for this TextTrack.
  6646. *
  6647. * @param {string} [options.label='']
  6648. * The menu label for this track.
  6649. *
  6650. * @param {string} [options.language='']
  6651. * A valid two character language code.
  6652. *
  6653. * @param {string} [options.srclang='']
  6654. * A valid two character language code. An alternative, but deprioritized
  6655. * version of `options.language`
  6656. *
  6657. * @param {string} [options.src]
  6658. * A url to TextTrack cues.
  6659. *
  6660. * @param {boolean} [options.default]
  6661. * If this track should default to on or off.
  6662. */
  6663. constructor(options = {}) {
  6664. if (!options.tech) {
  6665. throw new Error('A tech was not provided.');
  6666. }
  6667. const settings = merge$1(options, {
  6668. kind: TextTrackKind[options.kind] || 'subtitles',
  6669. language: options.language || options.srclang || ''
  6670. });
  6671. let mode = TextTrackMode[settings.mode] || 'disabled';
  6672. const default_ = settings.default;
  6673. if (settings.kind === 'metadata' || settings.kind === 'chapters') {
  6674. mode = 'hidden';
  6675. }
  6676. super(settings);
  6677. this.tech_ = settings.tech;
  6678. this.cues_ = [];
  6679. this.activeCues_ = [];
  6680. this.preload_ = this.tech_.preloadTextTracks !== false;
  6681. const cues = new TextTrackCueList(this.cues_);
  6682. const activeCues = new TextTrackCueList(this.activeCues_);
  6683. let changed = false;
  6684. this.timeupdateHandler = bind_(this, function (event = {}) {
  6685. if (this.tech_.isDisposed()) {
  6686. return;
  6687. }
  6688. if (!this.tech_.isReady_) {
  6689. if (event.type !== 'timeupdate') {
  6690. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  6691. }
  6692. return;
  6693. }
  6694. // Accessing this.activeCues for the side-effects of updating itself
  6695. // due to its nature as a getter function. Do not remove or cues will
  6696. // stop updating!
  6697. // Use the setter to prevent deletion from uglify (pure_getters rule)
  6698. this.activeCues = this.activeCues;
  6699. if (changed) {
  6700. this.trigger('cuechange');
  6701. changed = false;
  6702. }
  6703. if (event.type !== 'timeupdate') {
  6704. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  6705. }
  6706. });
  6707. const disposeHandler = () => {
  6708. this.stopTracking();
  6709. };
  6710. this.tech_.one('dispose', disposeHandler);
  6711. if (mode !== 'disabled') {
  6712. this.startTracking();
  6713. }
  6714. Object.defineProperties(this, {
  6715. /**
  6716. * @memberof TextTrack
  6717. * @member {boolean} default
  6718. * If this track was set to be on or off by default. Cannot be changed after
  6719. * creation.
  6720. * @instance
  6721. *
  6722. * @readonly
  6723. */
  6724. default: {
  6725. get() {
  6726. return default_;
  6727. },
  6728. set() {}
  6729. },
  6730. /**
  6731. * @memberof TextTrack
  6732. * @member {string} mode
  6733. * Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will
  6734. * not be set if setting to an invalid mode.
  6735. * @instance
  6736. *
  6737. * @fires TextTrack#modechange
  6738. */
  6739. mode: {
  6740. get() {
  6741. return mode;
  6742. },
  6743. set(newMode) {
  6744. if (!TextTrackMode[newMode]) {
  6745. return;
  6746. }
  6747. if (mode === newMode) {
  6748. return;
  6749. }
  6750. mode = newMode;
  6751. if (!this.preload_ && mode !== 'disabled' && this.cues.length === 0) {
  6752. // On-demand load.
  6753. loadTrack(this.src, this);
  6754. }
  6755. this.stopTracking();
  6756. if (mode !== 'disabled') {
  6757. this.startTracking();
  6758. }
  6759. /**
  6760. * An event that fires when mode changes on this track. This allows
  6761. * the TextTrackList that holds this track to act accordingly.
  6762. *
  6763. * > Note: This is not part of the spec!
  6764. *
  6765. * @event TextTrack#modechange
  6766. * @type {Event}
  6767. */
  6768. this.trigger('modechange');
  6769. }
  6770. },
  6771. /**
  6772. * @memberof TextTrack
  6773. * @member {TextTrackCueList} cues
  6774. * The text track cue list for this TextTrack.
  6775. * @instance
  6776. */
  6777. cues: {
  6778. get() {
  6779. if (!this.loaded_) {
  6780. return null;
  6781. }
  6782. return cues;
  6783. },
  6784. set() {}
  6785. },
  6786. /**
  6787. * @memberof TextTrack
  6788. * @member {TextTrackCueList} activeCues
  6789. * The list text track cues that are currently active for this TextTrack.
  6790. * @instance
  6791. */
  6792. activeCues: {
  6793. get() {
  6794. if (!this.loaded_) {
  6795. return null;
  6796. }
  6797. // nothing to do
  6798. if (this.cues.length === 0) {
  6799. return activeCues;
  6800. }
  6801. const ct = this.tech_.currentTime();
  6802. const active = [];
  6803. for (let i = 0, l = this.cues.length; i < l; i++) {
  6804. const cue = this.cues[i];
  6805. if (cue.startTime <= ct && cue.endTime >= ct) {
  6806. active.push(cue);
  6807. }
  6808. }
  6809. changed = false;
  6810. if (active.length !== this.activeCues_.length) {
  6811. changed = true;
  6812. } else {
  6813. for (let i = 0; i < active.length; i++) {
  6814. if (this.activeCues_.indexOf(active[i]) === -1) {
  6815. changed = true;
  6816. }
  6817. }
  6818. }
  6819. this.activeCues_ = active;
  6820. activeCues.setCues_(this.activeCues_);
  6821. return activeCues;
  6822. },
  6823. // /!\ Keep this setter empty (see the timeupdate handler above)
  6824. set() {}
  6825. }
  6826. });
  6827. if (settings.src) {
  6828. this.src = settings.src;
  6829. if (!this.preload_) {
  6830. // Tracks will load on-demand.
  6831. // Act like we're loaded for other purposes.
  6832. this.loaded_ = true;
  6833. }
  6834. if (this.preload_ || settings.kind !== 'subtitles' && settings.kind !== 'captions') {
  6835. loadTrack(this.src, this);
  6836. }
  6837. } else {
  6838. this.loaded_ = true;
  6839. }
  6840. }
  6841. startTracking() {
  6842. // More precise cues based on requestVideoFrameCallback with a requestAnimationFram fallback
  6843. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  6844. // Also listen to timeupdate in case rVFC/rAF stops (window in background, audio in video el)
  6845. this.tech_.on('timeupdate', this.timeupdateHandler);
  6846. }
  6847. stopTracking() {
  6848. if (this.rvf_) {
  6849. this.tech_.cancelVideoFrameCallback(this.rvf_);
  6850. this.rvf_ = undefined;
  6851. }
  6852. this.tech_.off('timeupdate', this.timeupdateHandler);
  6853. }
  6854. /**
  6855. * Add a cue to the internal list of cues.
  6856. *
  6857. * @param {TextTrack~Cue} cue
  6858. * The cue to add to our internal list
  6859. */
  6860. addCue(originalCue) {
  6861. let cue = originalCue;
  6862. if (window$1.vttjs && !(originalCue instanceof window$1.vttjs.VTTCue)) {
  6863. cue = new window$1.vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text);
  6864. for (const prop in originalCue) {
  6865. if (!(prop in cue)) {
  6866. cue[prop] = originalCue[prop];
  6867. }
  6868. }
  6869. // make sure that `id` is copied over
  6870. cue.id = originalCue.id;
  6871. cue.originalCue_ = originalCue;
  6872. }
  6873. const tracks = this.tech_.textTracks();
  6874. for (let i = 0; i < tracks.length; i++) {
  6875. if (tracks[i] !== this) {
  6876. tracks[i].removeCue(cue);
  6877. }
  6878. }
  6879. this.cues_.push(cue);
  6880. this.cues.setCues_(this.cues_);
  6881. }
  6882. /**
  6883. * Remove a cue from our internal list
  6884. *
  6885. * @param {TextTrack~Cue} removeCue
  6886. * The cue to remove from our internal list
  6887. */
  6888. removeCue(removeCue) {
  6889. let i = this.cues_.length;
  6890. while (i--) {
  6891. const cue = this.cues_[i];
  6892. if (cue === removeCue || cue.originalCue_ && cue.originalCue_ === removeCue) {
  6893. this.cues_.splice(i, 1);
  6894. this.cues.setCues_(this.cues_);
  6895. break;
  6896. }
  6897. }
  6898. }
  6899. }
  6900. /**
  6901. * cuechange - One or more cues in the track have become active or stopped being active.
  6902. */
  6903. TextTrack.prototype.allowedEvents_ = {
  6904. cuechange: 'cuechange'
  6905. };
  6906. /**
  6907. * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList}
  6908. * only one `AudioTrack` in the list will be enabled at a time.
  6909. *
  6910. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack}
  6911. * @extends Track
  6912. */
  6913. class AudioTrack extends Track {
  6914. /**
  6915. * Create an instance of this class.
  6916. *
  6917. * @param {Object} [options={}]
  6918. * Object of option names and values
  6919. *
  6920. * @param {AudioTrack~Kind} [options.kind='']
  6921. * A valid audio track kind
  6922. *
  6923. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6924. * A unique id for this AudioTrack.
  6925. *
  6926. * @param {string} [options.label='']
  6927. * The menu label for this track.
  6928. *
  6929. * @param {string} [options.language='']
  6930. * A valid two character language code.
  6931. *
  6932. * @param {boolean} [options.enabled]
  6933. * If this track is the one that is currently playing. If this track is part of
  6934. * an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled.
  6935. */
  6936. constructor(options = {}) {
  6937. const settings = merge$1(options, {
  6938. kind: AudioTrackKind[options.kind] || ''
  6939. });
  6940. super(settings);
  6941. let enabled = false;
  6942. /**
  6943. * @memberof AudioTrack
  6944. * @member {boolean} enabled
  6945. * If this `AudioTrack` is enabled or not. When setting this will
  6946. * fire {@link AudioTrack#enabledchange} if the state of enabled is changed.
  6947. * @instance
  6948. *
  6949. * @fires VideoTrack#selectedchange
  6950. */
  6951. Object.defineProperty(this, 'enabled', {
  6952. get() {
  6953. return enabled;
  6954. },
  6955. set(newEnabled) {
  6956. // an invalid or unchanged value
  6957. if (typeof newEnabled !== 'boolean' || newEnabled === enabled) {
  6958. return;
  6959. }
  6960. enabled = newEnabled;
  6961. /**
  6962. * An event that fires when enabled changes on this track. This allows
  6963. * the AudioTrackList that holds this track to act accordingly.
  6964. *
  6965. * > Note: This is not part of the spec! Native tracks will do
  6966. * this internally without an event.
  6967. *
  6968. * @event AudioTrack#enabledchange
  6969. * @type {Event}
  6970. */
  6971. this.trigger('enabledchange');
  6972. }
  6973. });
  6974. // if the user sets this track to selected then
  6975. // set selected to that true value otherwise
  6976. // we keep it false
  6977. if (settings.enabled) {
  6978. this.enabled = settings.enabled;
  6979. }
  6980. this.loaded_ = true;
  6981. }
  6982. }
  6983. /**
  6984. * A representation of a single `VideoTrack`.
  6985. *
  6986. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack}
  6987. * @extends Track
  6988. */
  6989. class VideoTrack extends Track {
  6990. /**
  6991. * Create an instance of this class.
  6992. *
  6993. * @param {Object} [options={}]
  6994. * Object of option names and values
  6995. *
  6996. * @param {string} [options.kind='']
  6997. * A valid {@link VideoTrack~Kind}
  6998. *
  6999. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7000. * A unique id for this AudioTrack.
  7001. *
  7002. * @param {string} [options.label='']
  7003. * The menu label for this track.
  7004. *
  7005. * @param {string} [options.language='']
  7006. * A valid two character language code.
  7007. *
  7008. * @param {boolean} [options.selected]
  7009. * If this track is the one that is currently playing.
  7010. */
  7011. constructor(options = {}) {
  7012. const settings = merge$1(options, {
  7013. kind: VideoTrackKind[options.kind] || ''
  7014. });
  7015. super(settings);
  7016. let selected = false;
  7017. /**
  7018. * @memberof VideoTrack
  7019. * @member {boolean} selected
  7020. * If this `VideoTrack` is selected or not. When setting this will
  7021. * fire {@link VideoTrack#selectedchange} if the state of selected changed.
  7022. * @instance
  7023. *
  7024. * @fires VideoTrack#selectedchange
  7025. */
  7026. Object.defineProperty(this, 'selected', {
  7027. get() {
  7028. return selected;
  7029. },
  7030. set(newSelected) {
  7031. // an invalid or unchanged value
  7032. if (typeof newSelected !== 'boolean' || newSelected === selected) {
  7033. return;
  7034. }
  7035. selected = newSelected;
  7036. /**
  7037. * An event that fires when selected changes on this track. This allows
  7038. * the VideoTrackList that holds this track to act accordingly.
  7039. *
  7040. * > Note: This is not part of the spec! Native tracks will do
  7041. * this internally without an event.
  7042. *
  7043. * @event VideoTrack#selectedchange
  7044. * @type {Event}
  7045. */
  7046. this.trigger('selectedchange');
  7047. }
  7048. });
  7049. // if the user sets this track to selected then
  7050. // set selected to that true value otherwise
  7051. // we keep it false
  7052. if (settings.selected) {
  7053. this.selected = settings.selected;
  7054. }
  7055. }
  7056. }
  7057. /**
  7058. * @file html-track-element.js
  7059. */
  7060. /**
  7061. * A single track represented in the DOM.
  7062. *
  7063. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement}
  7064. * @extends EventTarget
  7065. */
  7066. class HTMLTrackElement extends EventTarget$2 {
  7067. /**
  7068. * Create an instance of this class.
  7069. *
  7070. * @param {Object} options={}
  7071. * Object of option names and values
  7072. *
  7073. * @param { import('../tech/tech').default } options.tech
  7074. * A reference to the tech that owns this HTMLTrackElement.
  7075. *
  7076. * @param {TextTrack~Kind} [options.kind='subtitles']
  7077. * A valid text track kind.
  7078. *
  7079. * @param {TextTrack~Mode} [options.mode='disabled']
  7080. * A valid text track mode.
  7081. *
  7082. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7083. * A unique id for this TextTrack.
  7084. *
  7085. * @param {string} [options.label='']
  7086. * The menu label for this track.
  7087. *
  7088. * @param {string} [options.language='']
  7089. * A valid two character language code.
  7090. *
  7091. * @param {string} [options.srclang='']
  7092. * A valid two character language code. An alternative, but deprioritized
  7093. * version of `options.language`
  7094. *
  7095. * @param {string} [options.src]
  7096. * A url to TextTrack cues.
  7097. *
  7098. * @param {boolean} [options.default]
  7099. * If this track should default to on or off.
  7100. */
  7101. constructor(options = {}) {
  7102. super();
  7103. let readyState;
  7104. const track = new TextTrack(options);
  7105. this.kind = track.kind;
  7106. this.src = track.src;
  7107. this.srclang = track.language;
  7108. this.label = track.label;
  7109. this.default = track.default;
  7110. Object.defineProperties(this, {
  7111. /**
  7112. * @memberof HTMLTrackElement
  7113. * @member {HTMLTrackElement~ReadyState} readyState
  7114. * The current ready state of the track element.
  7115. * @instance
  7116. */
  7117. readyState: {
  7118. get() {
  7119. return readyState;
  7120. }
  7121. },
  7122. /**
  7123. * @memberof HTMLTrackElement
  7124. * @member {TextTrack} track
  7125. * The underlying TextTrack object.
  7126. * @instance
  7127. *
  7128. */
  7129. track: {
  7130. get() {
  7131. return track;
  7132. }
  7133. }
  7134. });
  7135. readyState = HTMLTrackElement.NONE;
  7136. /**
  7137. * @listens TextTrack#loadeddata
  7138. * @fires HTMLTrackElement#load
  7139. */
  7140. track.addEventListener('loadeddata', () => {
  7141. readyState = HTMLTrackElement.LOADED;
  7142. this.trigger({
  7143. type: 'load',
  7144. target: this
  7145. });
  7146. });
  7147. }
  7148. }
  7149. HTMLTrackElement.prototype.allowedEvents_ = {
  7150. load: 'load'
  7151. };
  7152. /**
  7153. * The text track not loaded state.
  7154. *
  7155. * @type {number}
  7156. * @static
  7157. */
  7158. HTMLTrackElement.NONE = 0;
  7159. /**
  7160. * The text track loading state.
  7161. *
  7162. * @type {number}
  7163. * @static
  7164. */
  7165. HTMLTrackElement.LOADING = 1;
  7166. /**
  7167. * The text track loaded state.
  7168. *
  7169. * @type {number}
  7170. * @static
  7171. */
  7172. HTMLTrackElement.LOADED = 2;
  7173. /**
  7174. * The text track failed to load state.
  7175. *
  7176. * @type {number}
  7177. * @static
  7178. */
  7179. HTMLTrackElement.ERROR = 3;
  7180. /*
  7181. * This file contains all track properties that are used in
  7182. * player.js, tech.js, html5.js and possibly other techs in the future.
  7183. */
  7184. const NORMAL = {
  7185. audio: {
  7186. ListClass: AudioTrackList,
  7187. TrackClass: AudioTrack,
  7188. capitalName: 'Audio'
  7189. },
  7190. video: {
  7191. ListClass: VideoTrackList,
  7192. TrackClass: VideoTrack,
  7193. capitalName: 'Video'
  7194. },
  7195. text: {
  7196. ListClass: TextTrackList,
  7197. TrackClass: TextTrack,
  7198. capitalName: 'Text'
  7199. }
  7200. };
  7201. Object.keys(NORMAL).forEach(function (type) {
  7202. NORMAL[type].getterName = `${type}Tracks`;
  7203. NORMAL[type].privateName = `${type}Tracks_`;
  7204. });
  7205. const REMOTE = {
  7206. remoteText: {
  7207. ListClass: TextTrackList,
  7208. TrackClass: TextTrack,
  7209. capitalName: 'RemoteText',
  7210. getterName: 'remoteTextTracks',
  7211. privateName: 'remoteTextTracks_'
  7212. },
  7213. remoteTextEl: {
  7214. ListClass: HtmlTrackElementList,
  7215. TrackClass: HTMLTrackElement,
  7216. capitalName: 'RemoteTextTrackEls',
  7217. getterName: 'remoteTextTrackEls',
  7218. privateName: 'remoteTextTrackEls_'
  7219. }
  7220. };
  7221. const ALL = Object.assign({}, NORMAL, REMOTE);
  7222. REMOTE.names = Object.keys(REMOTE);
  7223. NORMAL.names = Object.keys(NORMAL);
  7224. ALL.names = [].concat(REMOTE.names).concat(NORMAL.names);
  7225. /**
  7226. * @file tech.js
  7227. */
  7228. /**
  7229. * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
  7230. * that just contains the src url alone.
  7231. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
  7232. * `var SourceString = 'http://example.com/some-video.mp4';`
  7233. *
  7234. * @typedef {Object|string} Tech~SourceObject
  7235. *
  7236. * @property {string} src
  7237. * The url to the source
  7238. *
  7239. * @property {string} type
  7240. * The mime type of the source
  7241. */
  7242. /**
  7243. * A function used by {@link Tech} to create a new {@link TextTrack}.
  7244. *
  7245. * @private
  7246. *
  7247. * @param {Tech} self
  7248. * An instance of the Tech class.
  7249. *
  7250. * @param {string} kind
  7251. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  7252. *
  7253. * @param {string} [label]
  7254. * Label to identify the text track
  7255. *
  7256. * @param {string} [language]
  7257. * Two letter language abbreviation
  7258. *
  7259. * @param {Object} [options={}]
  7260. * An object with additional text track options
  7261. *
  7262. * @return {TextTrack}
  7263. * The text track that was created.
  7264. */
  7265. function createTrackHelper(self, kind, label, language, options = {}) {
  7266. const tracks = self.textTracks();
  7267. options.kind = kind;
  7268. if (label) {
  7269. options.label = label;
  7270. }
  7271. if (language) {
  7272. options.language = language;
  7273. }
  7274. options.tech = self;
  7275. const track = new ALL.text.TrackClass(options);
  7276. tracks.addTrack(track);
  7277. return track;
  7278. }
  7279. /**
  7280. * This is the base class for media playback technology controllers, such as
  7281. * {@link HTML5}
  7282. *
  7283. * @extends Component
  7284. */
  7285. class Tech extends Component$1 {
  7286. /**
  7287. * Create an instance of this Tech.
  7288. *
  7289. * @param {Object} [options]
  7290. * The key/value store of player options.
  7291. *
  7292. * @param {Function} [ready]
  7293. * Callback function to call when the `HTML5` Tech is ready.
  7294. */
  7295. constructor(options = {}, ready = function () {}) {
  7296. // we don't want the tech to report user activity automatically.
  7297. // This is done manually in addControlsListeners
  7298. options.reportTouchActivity = false;
  7299. super(null, options, ready);
  7300. this.onDurationChange_ = e => this.onDurationChange(e);
  7301. this.trackProgress_ = e => this.trackProgress(e);
  7302. this.trackCurrentTime_ = e => this.trackCurrentTime(e);
  7303. this.stopTrackingCurrentTime_ = e => this.stopTrackingCurrentTime(e);
  7304. this.disposeSourceHandler_ = e => this.disposeSourceHandler(e);
  7305. this.queuedHanders_ = new Set();
  7306. // keep track of whether the current source has played at all to
  7307. // implement a very limited played()
  7308. this.hasStarted_ = false;
  7309. this.on('playing', function () {
  7310. this.hasStarted_ = true;
  7311. });
  7312. this.on('loadstart', function () {
  7313. this.hasStarted_ = false;
  7314. });
  7315. ALL.names.forEach(name => {
  7316. const props = ALL[name];
  7317. if (options && options[props.getterName]) {
  7318. this[props.privateName] = options[props.getterName];
  7319. }
  7320. });
  7321. // Manually track progress in cases where the browser/tech doesn't report it.
  7322. if (!this.featuresProgressEvents) {
  7323. this.manualProgressOn();
  7324. }
  7325. // Manually track timeupdates in cases where the browser/tech doesn't report it.
  7326. if (!this.featuresTimeupdateEvents) {
  7327. this.manualTimeUpdatesOn();
  7328. }
  7329. ['Text', 'Audio', 'Video'].forEach(track => {
  7330. if (options[`native${track}Tracks`] === false) {
  7331. this[`featuresNative${track}Tracks`] = false;
  7332. }
  7333. });
  7334. if (options.nativeCaptions === false || options.nativeTextTracks === false) {
  7335. this.featuresNativeTextTracks = false;
  7336. } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
  7337. this.featuresNativeTextTracks = true;
  7338. }
  7339. if (!this.featuresNativeTextTracks) {
  7340. this.emulateTextTracks();
  7341. }
  7342. this.preloadTextTracks = options.preloadTextTracks !== false;
  7343. this.autoRemoteTextTracks_ = new ALL.text.ListClass();
  7344. this.initTrackListeners();
  7345. // Turn on component tap events only if not using native controls
  7346. if (!options.nativeControlsForTouch) {
  7347. this.emitTapEvents();
  7348. }
  7349. if (this.constructor) {
  7350. this.name_ = this.constructor.name || 'Unknown Tech';
  7351. }
  7352. }
  7353. /**
  7354. * A special function to trigger source set in a way that will allow player
  7355. * to re-trigger if the player or tech are not ready yet.
  7356. *
  7357. * @fires Tech#sourceset
  7358. * @param {string} src The source string at the time of the source changing.
  7359. */
  7360. triggerSourceset(src) {
  7361. if (!this.isReady_) {
  7362. // on initial ready we have to trigger source set
  7363. // 1ms after ready so that player can watch for it.
  7364. this.one('ready', () => this.setTimeout(() => this.triggerSourceset(src), 1));
  7365. }
  7366. /**
  7367. * Fired when the source is set on the tech causing the media element
  7368. * to reload.
  7369. *
  7370. * @see {@link Player#event:sourceset}
  7371. * @event Tech#sourceset
  7372. * @type {Event}
  7373. */
  7374. this.trigger({
  7375. src,
  7376. type: 'sourceset'
  7377. });
  7378. }
  7379. /* Fallbacks for unsupported event types
  7380. ================================================================================ */
  7381. /**
  7382. * Polyfill the `progress` event for browsers that don't support it natively.
  7383. *
  7384. * @see {@link Tech#trackProgress}
  7385. */
  7386. manualProgressOn() {
  7387. this.on('durationchange', this.onDurationChange_);
  7388. this.manualProgress = true;
  7389. // Trigger progress watching when a source begins loading
  7390. this.one('ready', this.trackProgress_);
  7391. }
  7392. /**
  7393. * Turn off the polyfill for `progress` events that was created in
  7394. * {@link Tech#manualProgressOn}
  7395. */
  7396. manualProgressOff() {
  7397. this.manualProgress = false;
  7398. this.stopTrackingProgress();
  7399. this.off('durationchange', this.onDurationChange_);
  7400. }
  7401. /**
  7402. * This is used to trigger a `progress` event when the buffered percent changes. It
  7403. * sets an interval function that will be called every 500 milliseconds to check if the
  7404. * buffer end percent has changed.
  7405. *
  7406. * > This function is called by {@link Tech#manualProgressOn}
  7407. *
  7408. * @param {Event} event
  7409. * The `ready` event that caused this to run.
  7410. *
  7411. * @listens Tech#ready
  7412. * @fires Tech#progress
  7413. */
  7414. trackProgress(event) {
  7415. this.stopTrackingProgress();
  7416. this.progressInterval = this.setInterval(bind_(this, function () {
  7417. // Don't trigger unless buffered amount is greater than last time
  7418. const numBufferedPercent = this.bufferedPercent();
  7419. if (this.bufferedPercent_ !== numBufferedPercent) {
  7420. /**
  7421. * See {@link Player#progress}
  7422. *
  7423. * @event Tech#progress
  7424. * @type {Event}
  7425. */
  7426. this.trigger('progress');
  7427. }
  7428. this.bufferedPercent_ = numBufferedPercent;
  7429. if (numBufferedPercent === 1) {
  7430. this.stopTrackingProgress();
  7431. }
  7432. }), 500);
  7433. }
  7434. /**
  7435. * Update our internal duration on a `durationchange` event by calling
  7436. * {@link Tech#duration}.
  7437. *
  7438. * @param {Event} event
  7439. * The `durationchange` event that caused this to run.
  7440. *
  7441. * @listens Tech#durationchange
  7442. */
  7443. onDurationChange(event) {
  7444. this.duration_ = this.duration();
  7445. }
  7446. /**
  7447. * Get and create a `TimeRange` object for buffering.
  7448. *
  7449. * @return { import('../utils/time').TimeRange }
  7450. * The time range object that was created.
  7451. */
  7452. buffered() {
  7453. return createTimeRanges$1(0, 0);
  7454. }
  7455. /**
  7456. * Get the percentage of the current video that is currently buffered.
  7457. *
  7458. * @return {number}
  7459. * A number from 0 to 1 that represents the decimal percentage of the
  7460. * video that is buffered.
  7461. *
  7462. */
  7463. bufferedPercent() {
  7464. return bufferedPercent(this.buffered(), this.duration_);
  7465. }
  7466. /**
  7467. * Turn off the polyfill for `progress` events that was created in
  7468. * {@link Tech#manualProgressOn}
  7469. * Stop manually tracking progress events by clearing the interval that was set in
  7470. * {@link Tech#trackProgress}.
  7471. */
  7472. stopTrackingProgress() {
  7473. this.clearInterval(this.progressInterval);
  7474. }
  7475. /**
  7476. * Polyfill the `timeupdate` event for browsers that don't support it.
  7477. *
  7478. * @see {@link Tech#trackCurrentTime}
  7479. */
  7480. manualTimeUpdatesOn() {
  7481. this.manualTimeUpdates = true;
  7482. this.on('play', this.trackCurrentTime_);
  7483. this.on('pause', this.stopTrackingCurrentTime_);
  7484. }
  7485. /**
  7486. * Turn off the polyfill for `timeupdate` events that was created in
  7487. * {@link Tech#manualTimeUpdatesOn}
  7488. */
  7489. manualTimeUpdatesOff() {
  7490. this.manualTimeUpdates = false;
  7491. this.stopTrackingCurrentTime();
  7492. this.off('play', this.trackCurrentTime_);
  7493. this.off('pause', this.stopTrackingCurrentTime_);
  7494. }
  7495. /**
  7496. * Sets up an interval function to track current time and trigger `timeupdate` every
  7497. * 250 milliseconds.
  7498. *
  7499. * @listens Tech#play
  7500. * @triggers Tech#timeupdate
  7501. */
  7502. trackCurrentTime() {
  7503. if (this.currentTimeInterval) {
  7504. this.stopTrackingCurrentTime();
  7505. }
  7506. this.currentTimeInterval = this.setInterval(function () {
  7507. /**
  7508. * Triggered at an interval of 250ms to indicated that time is passing in the video.
  7509. *
  7510. * @event Tech#timeupdate
  7511. * @type {Event}
  7512. */
  7513. this.trigger({
  7514. type: 'timeupdate',
  7515. target: this,
  7516. manuallyTriggered: true
  7517. });
  7518. // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  7519. }, 250);
  7520. }
  7521. /**
  7522. * Stop the interval function created in {@link Tech#trackCurrentTime} so that the
  7523. * `timeupdate` event is no longer triggered.
  7524. *
  7525. * @listens {Tech#pause}
  7526. */
  7527. stopTrackingCurrentTime() {
  7528. this.clearInterval(this.currentTimeInterval);
  7529. // #1002 - if the video ends right before the next timeupdate would happen,
  7530. // the progress bar won't make it all the way to the end
  7531. this.trigger({
  7532. type: 'timeupdate',
  7533. target: this,
  7534. manuallyTriggered: true
  7535. });
  7536. }
  7537. /**
  7538. * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},
  7539. * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.
  7540. *
  7541. * @fires Component#dispose
  7542. */
  7543. dispose() {
  7544. // clear out all tracks because we can't reuse them between techs
  7545. this.clearTracks(NORMAL.names);
  7546. // Turn off any manual progress or timeupdate tracking
  7547. if (this.manualProgress) {
  7548. this.manualProgressOff();
  7549. }
  7550. if (this.manualTimeUpdates) {
  7551. this.manualTimeUpdatesOff();
  7552. }
  7553. super.dispose();
  7554. }
  7555. /**
  7556. * Clear out a single `TrackList` or an array of `TrackLists` given their names.
  7557. *
  7558. * > Note: Techs without source handlers should call this between sources for `video`
  7559. * & `audio` tracks. You don't want to use them between tracks!
  7560. *
  7561. * @param {string[]|string} types
  7562. * TrackList names to clear, valid names are `video`, `audio`, and
  7563. * `text`.
  7564. */
  7565. clearTracks(types) {
  7566. types = [].concat(types);
  7567. // clear out all tracks because we can't reuse them between techs
  7568. types.forEach(type => {
  7569. const list = this[`${type}Tracks`]() || [];
  7570. let i = list.length;
  7571. while (i--) {
  7572. const track = list[i];
  7573. if (type === 'text') {
  7574. this.removeRemoteTextTrack(track);
  7575. }
  7576. list.removeTrack(track);
  7577. }
  7578. });
  7579. }
  7580. /**
  7581. * Remove any TextTracks added via addRemoteTextTrack that are
  7582. * flagged for automatic garbage collection
  7583. */
  7584. cleanupAutoTextTracks() {
  7585. const list = this.autoRemoteTextTracks_ || [];
  7586. let i = list.length;
  7587. while (i--) {
  7588. const track = list[i];
  7589. this.removeRemoteTextTrack(track);
  7590. }
  7591. }
  7592. /**
  7593. * Reset the tech, which will removes all sources and reset the internal readyState.
  7594. *
  7595. * @abstract
  7596. */
  7597. reset() {}
  7598. /**
  7599. * Get the value of `crossOrigin` from the tech.
  7600. *
  7601. * @abstract
  7602. *
  7603. * @see {Html5#crossOrigin}
  7604. */
  7605. crossOrigin() {}
  7606. /**
  7607. * Set the value of `crossOrigin` on the tech.
  7608. *
  7609. * @abstract
  7610. *
  7611. * @param {string} crossOrigin the crossOrigin value
  7612. * @see {Html5#setCrossOrigin}
  7613. */
  7614. setCrossOrigin() {}
  7615. /**
  7616. * Get or set an error on the Tech.
  7617. *
  7618. * @param {MediaError} [err]
  7619. * Error to set on the Tech
  7620. *
  7621. * @return {MediaError|null}
  7622. * The current error object on the tech, or null if there isn't one.
  7623. */
  7624. error(err) {
  7625. if (err !== undefined) {
  7626. this.error_ = new MediaError(err);
  7627. this.trigger('error');
  7628. }
  7629. return this.error_;
  7630. }
  7631. /**
  7632. * Returns the `TimeRange`s that have been played through for the current source.
  7633. *
  7634. * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.
  7635. * It only checks whether the source has played at all or not.
  7636. *
  7637. * @return {TimeRange}
  7638. * - A single time range if this video has played
  7639. * - An empty set of ranges if not.
  7640. */
  7641. played() {
  7642. if (this.hasStarted_) {
  7643. return createTimeRanges$1(0, 0);
  7644. }
  7645. return createTimeRanges$1();
  7646. }
  7647. /**
  7648. * Start playback
  7649. *
  7650. * @abstract
  7651. *
  7652. * @see {Html5#play}
  7653. */
  7654. play() {}
  7655. /**
  7656. * Set whether we are scrubbing or not
  7657. *
  7658. * @abstract
  7659. * @param {boolean} _isScrubbing
  7660. * - true for we are currently scrubbing
  7661. * - false for we are no longer scrubbing
  7662. *
  7663. * @see {Html5#setScrubbing}
  7664. */
  7665. setScrubbing(_isScrubbing) {}
  7666. /**
  7667. * Get whether we are scrubbing or not
  7668. *
  7669. * @abstract
  7670. *
  7671. * @see {Html5#scrubbing}
  7672. */
  7673. scrubbing() {}
  7674. /**
  7675. * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was
  7676. * previously called.
  7677. *
  7678. * @param {number} _seconds
  7679. * Set the current time of the media to this.
  7680. * @fires Tech#timeupdate
  7681. */
  7682. setCurrentTime(_seconds) {
  7683. // improve the accuracy of manual timeupdates
  7684. if (this.manualTimeUpdates) {
  7685. /**
  7686. * A manual `timeupdate` event.
  7687. *
  7688. * @event Tech#timeupdate
  7689. * @type {Event}
  7690. */
  7691. this.trigger({
  7692. type: 'timeupdate',
  7693. target: this,
  7694. manuallyTriggered: true
  7695. });
  7696. }
  7697. }
  7698. /**
  7699. * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
  7700. * {@link TextTrackList} events.
  7701. *
  7702. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
  7703. *
  7704. * @fires Tech#audiotrackchange
  7705. * @fires Tech#videotrackchange
  7706. * @fires Tech#texttrackchange
  7707. */
  7708. initTrackListeners() {
  7709. /**
  7710. * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
  7711. *
  7712. * @event Tech#audiotrackchange
  7713. * @type {Event}
  7714. */
  7715. /**
  7716. * Triggered when tracks are added or removed on the Tech {@link VideoTrackList}
  7717. *
  7718. * @event Tech#videotrackchange
  7719. * @type {Event}
  7720. */
  7721. /**
  7722. * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
  7723. *
  7724. * @event Tech#texttrackchange
  7725. * @type {Event}
  7726. */
  7727. NORMAL.names.forEach(name => {
  7728. const props = NORMAL[name];
  7729. const trackListChanges = () => {
  7730. this.trigger(`${name}trackchange`);
  7731. };
  7732. const tracks = this[props.getterName]();
  7733. tracks.addEventListener('removetrack', trackListChanges);
  7734. tracks.addEventListener('addtrack', trackListChanges);
  7735. this.on('dispose', () => {
  7736. tracks.removeEventListener('removetrack', trackListChanges);
  7737. tracks.removeEventListener('addtrack', trackListChanges);
  7738. });
  7739. });
  7740. }
  7741. /**
  7742. * Emulate TextTracks using vtt.js if necessary
  7743. *
  7744. * @fires Tech#vttjsloaded
  7745. * @fires Tech#vttjserror
  7746. */
  7747. addWebVttScript_() {
  7748. if (window$1.WebVTT) {
  7749. return;
  7750. }
  7751. // Initially, Tech.el_ is a child of a dummy-div wait until the Component system
  7752. // signals that the Tech is ready at which point Tech.el_ is part of the DOM
  7753. // before inserting the WebVTT script
  7754. if (document.body.contains(this.el())) {
  7755. // load via require if available and vtt.js script location was not passed in
  7756. // as an option. novtt builds will turn the above require call into an empty object
  7757. // which will cause this if check to always fail.
  7758. if (!this.options_['vtt.js'] && isPlain(vtt) && Object.keys(vtt).length > 0) {
  7759. this.trigger('vttjsloaded');
  7760. return;
  7761. }
  7762. // load vtt.js via the script location option or the cdn of no location was
  7763. // passed in
  7764. const script = document.createElement('script');
  7765. script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';
  7766. script.onload = () => {
  7767. /**
  7768. * Fired when vtt.js is loaded.
  7769. *
  7770. * @event Tech#vttjsloaded
  7771. * @type {Event}
  7772. */
  7773. this.trigger('vttjsloaded');
  7774. };
  7775. script.onerror = () => {
  7776. /**
  7777. * Fired when vtt.js was not loaded due to an error
  7778. *
  7779. * @event Tech#vttjsloaded
  7780. * @type {Event}
  7781. */
  7782. this.trigger('vttjserror');
  7783. };
  7784. this.on('dispose', () => {
  7785. script.onload = null;
  7786. script.onerror = null;
  7787. });
  7788. // but have not loaded yet and we set it to true before the inject so that
  7789. // we don't overwrite the injected window.WebVTT if it loads right away
  7790. window$1.WebVTT = true;
  7791. this.el().parentNode.appendChild(script);
  7792. } else {
  7793. this.ready(this.addWebVttScript_);
  7794. }
  7795. }
  7796. /**
  7797. * Emulate texttracks
  7798. *
  7799. */
  7800. emulateTextTracks() {
  7801. const tracks = this.textTracks();
  7802. const remoteTracks = this.remoteTextTracks();
  7803. const handleAddTrack = e => tracks.addTrack(e.track);
  7804. const handleRemoveTrack = e => tracks.removeTrack(e.track);
  7805. remoteTracks.on('addtrack', handleAddTrack);
  7806. remoteTracks.on('removetrack', handleRemoveTrack);
  7807. this.addWebVttScript_();
  7808. const updateDisplay = () => this.trigger('texttrackchange');
  7809. const textTracksChanges = () => {
  7810. updateDisplay();
  7811. for (let i = 0; i < tracks.length; i++) {
  7812. const track = tracks[i];
  7813. track.removeEventListener('cuechange', updateDisplay);
  7814. if (track.mode === 'showing') {
  7815. track.addEventListener('cuechange', updateDisplay);
  7816. }
  7817. }
  7818. };
  7819. textTracksChanges();
  7820. tracks.addEventListener('change', textTracksChanges);
  7821. tracks.addEventListener('addtrack', textTracksChanges);
  7822. tracks.addEventListener('removetrack', textTracksChanges);
  7823. this.on('dispose', function () {
  7824. remoteTracks.off('addtrack', handleAddTrack);
  7825. remoteTracks.off('removetrack', handleRemoveTrack);
  7826. tracks.removeEventListener('change', textTracksChanges);
  7827. tracks.removeEventListener('addtrack', textTracksChanges);
  7828. tracks.removeEventListener('removetrack', textTracksChanges);
  7829. for (let i = 0; i < tracks.length; i++) {
  7830. const track = tracks[i];
  7831. track.removeEventListener('cuechange', updateDisplay);
  7832. }
  7833. });
  7834. }
  7835. /**
  7836. * Create and returns a remote {@link TextTrack} object.
  7837. *
  7838. * @param {string} kind
  7839. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  7840. *
  7841. * @param {string} [label]
  7842. * Label to identify the text track
  7843. *
  7844. * @param {string} [language]
  7845. * Two letter language abbreviation
  7846. *
  7847. * @return {TextTrack}
  7848. * The TextTrack that gets created.
  7849. */
  7850. addTextTrack(kind, label, language) {
  7851. if (!kind) {
  7852. throw new Error('TextTrack kind is required but was not provided');
  7853. }
  7854. return createTrackHelper(this, kind, label, language);
  7855. }
  7856. /**
  7857. * Create an emulated TextTrack for use by addRemoteTextTrack
  7858. *
  7859. * This is intended to be overridden by classes that inherit from
  7860. * Tech in order to create native or custom TextTracks.
  7861. *
  7862. * @param {Object} options
  7863. * The object should contain the options to initialize the TextTrack with.
  7864. *
  7865. * @param {string} [options.kind]
  7866. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  7867. *
  7868. * @param {string} [options.label].
  7869. * Label to identify the text track
  7870. *
  7871. * @param {string} [options.language]
  7872. * Two letter language abbreviation.
  7873. *
  7874. * @return {HTMLTrackElement}
  7875. * The track element that gets created.
  7876. */
  7877. createRemoteTextTrack(options) {
  7878. const track = merge$1(options, {
  7879. tech: this
  7880. });
  7881. return new REMOTE.remoteTextEl.TrackClass(track);
  7882. }
  7883. /**
  7884. * Creates a remote text track object and returns an html track element.
  7885. *
  7886. * > Note: This can be an emulated {@link HTMLTrackElement} or a native one.
  7887. *
  7888. * @param {Object} options
  7889. * See {@link Tech#createRemoteTextTrack} for more detailed properties.
  7890. *
  7891. * @param {boolean} [manualCleanup=false]
  7892. * - When false: the TextTrack will be automatically removed from the video
  7893. * element whenever the source changes
  7894. * - When True: The TextTrack will have to be cleaned up manually
  7895. *
  7896. * @return {HTMLTrackElement}
  7897. * An Html Track Element.
  7898. *
  7899. */
  7900. addRemoteTextTrack(options = {}, manualCleanup) {
  7901. const htmlTrackElement = this.createRemoteTextTrack(options);
  7902. if (typeof manualCleanup !== 'boolean') {
  7903. manualCleanup = false;
  7904. }
  7905. // store HTMLTrackElement and TextTrack to remote list
  7906. this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
  7907. this.remoteTextTracks().addTrack(htmlTrackElement.track);
  7908. if (manualCleanup === false) {
  7909. // create the TextTrackList if it doesn't exist
  7910. this.ready(() => this.autoRemoteTextTracks_.addTrack(htmlTrackElement.track));
  7911. }
  7912. return htmlTrackElement;
  7913. }
  7914. /**
  7915. * Remove a remote text track from the remote `TextTrackList`.
  7916. *
  7917. * @param {TextTrack} track
  7918. * `TextTrack` to remove from the `TextTrackList`
  7919. */
  7920. removeRemoteTextTrack(track) {
  7921. const trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);
  7922. // remove HTMLTrackElement and TextTrack from remote list
  7923. this.remoteTextTrackEls().removeTrackElement_(trackElement);
  7924. this.remoteTextTracks().removeTrack(track);
  7925. this.autoRemoteTextTracks_.removeTrack(track);
  7926. }
  7927. /**
  7928. * Gets available media playback quality metrics as specified by the W3C's Media
  7929. * Playback Quality API.
  7930. *
  7931. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  7932. *
  7933. * @return {Object}
  7934. * An object with supported media playback quality metrics
  7935. *
  7936. * @abstract
  7937. */
  7938. getVideoPlaybackQuality() {
  7939. return {};
  7940. }
  7941. /**
  7942. * Attempt to create a floating video window always on top of other windows
  7943. * so that users may continue consuming media while they interact with other
  7944. * content sites, or applications on their device.
  7945. *
  7946. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  7947. *
  7948. * @return {Promise|undefined}
  7949. * A promise with a Picture-in-Picture window if the browser supports
  7950. * Promises (or one was passed in as an option). It returns undefined
  7951. * otherwise.
  7952. *
  7953. * @abstract
  7954. */
  7955. requestPictureInPicture() {
  7956. return Promise.reject();
  7957. }
  7958. /**
  7959. * A method to check for the value of the 'disablePictureInPicture' <video> property.
  7960. * Defaults to true, as it should be considered disabled if the tech does not support pip
  7961. *
  7962. * @abstract
  7963. */
  7964. disablePictureInPicture() {
  7965. return true;
  7966. }
  7967. /**
  7968. * A method to set or unset the 'disablePictureInPicture' <video> property.
  7969. *
  7970. * @abstract
  7971. */
  7972. setDisablePictureInPicture() {}
  7973. /**
  7974. * A fallback implementation of requestVideoFrameCallback using requestAnimationFrame
  7975. *
  7976. * @param {function} cb
  7977. * @return {number} request id
  7978. */
  7979. requestVideoFrameCallback(cb) {
  7980. const id = newGUID();
  7981. if (!this.isReady_ || this.paused()) {
  7982. this.queuedHanders_.add(id);
  7983. this.one('playing', () => {
  7984. if (this.queuedHanders_.has(id)) {
  7985. this.queuedHanders_.delete(id);
  7986. cb();
  7987. }
  7988. });
  7989. } else {
  7990. this.requestNamedAnimationFrame(id, cb);
  7991. }
  7992. return id;
  7993. }
  7994. /**
  7995. * A fallback implementation of cancelVideoFrameCallback
  7996. *
  7997. * @param {number} id id of callback to be cancelled
  7998. */
  7999. cancelVideoFrameCallback(id) {
  8000. if (this.queuedHanders_.has(id)) {
  8001. this.queuedHanders_.delete(id);
  8002. } else {
  8003. this.cancelNamedAnimationFrame(id);
  8004. }
  8005. }
  8006. /**
  8007. * A method to set a poster from a `Tech`.
  8008. *
  8009. * @abstract
  8010. */
  8011. setPoster() {}
  8012. /**
  8013. * A method to check for the presence of the 'playsinline' <video> attribute.
  8014. *
  8015. * @abstract
  8016. */
  8017. playsinline() {}
  8018. /**
  8019. * A method to set or unset the 'playsinline' <video> attribute.
  8020. *
  8021. * @abstract
  8022. */
  8023. setPlaysinline() {}
  8024. /**
  8025. * Attempt to force override of native audio tracks.
  8026. *
  8027. * @param {boolean} override - If set to true native audio will be overridden,
  8028. * otherwise native audio will potentially be used.
  8029. *
  8030. * @abstract
  8031. */
  8032. overrideNativeAudioTracks(override) {}
  8033. /**
  8034. * Attempt to force override of native video tracks.
  8035. *
  8036. * @param {boolean} override - If set to true native video will be overridden,
  8037. * otherwise native video will potentially be used.
  8038. *
  8039. * @abstract
  8040. */
  8041. overrideNativeVideoTracks(override) {}
  8042. /**
  8043. * Check if the tech can support the given mime-type.
  8044. *
  8045. * The base tech does not support any type, but source handlers might
  8046. * overwrite this.
  8047. *
  8048. * @param {string} _type
  8049. * The mimetype to check for support
  8050. *
  8051. * @return {string}
  8052. * 'probably', 'maybe', or empty string
  8053. *
  8054. * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}
  8055. *
  8056. * @abstract
  8057. */
  8058. canPlayType(_type) {
  8059. return '';
  8060. }
  8061. /**
  8062. * Check if the type is supported by this tech.
  8063. *
  8064. * The base tech does not support any type, but source handlers might
  8065. * overwrite this.
  8066. *
  8067. * @param {string} _type
  8068. * The media type to check
  8069. * @return {string} Returns the native video element's response
  8070. */
  8071. static canPlayType(_type) {
  8072. return '';
  8073. }
  8074. /**
  8075. * Check if the tech can support the given source
  8076. *
  8077. * @param {Object} srcObj
  8078. * The source object
  8079. * @param {Object} options
  8080. * The options passed to the tech
  8081. * @return {string} 'probably', 'maybe', or '' (empty string)
  8082. */
  8083. static canPlaySource(srcObj, options) {
  8084. return Tech.canPlayType(srcObj.type);
  8085. }
  8086. /*
  8087. * Return whether the argument is a Tech or not.
  8088. * Can be passed either a Class like `Html5` or a instance like `player.tech_`
  8089. *
  8090. * @param {Object} component
  8091. * The item to check
  8092. *
  8093. * @return {boolean}
  8094. * Whether it is a tech or not
  8095. * - True if it is a tech
  8096. * - False if it is not
  8097. */
  8098. static isTech(component) {
  8099. return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
  8100. }
  8101. /**
  8102. * Registers a `Tech` into a shared list for videojs.
  8103. *
  8104. * @param {string} name
  8105. * Name of the `Tech` to register.
  8106. *
  8107. * @param {Object} tech
  8108. * The `Tech` class to register.
  8109. */
  8110. static registerTech(name, tech) {
  8111. if (!Tech.techs_) {
  8112. Tech.techs_ = {};
  8113. }
  8114. if (!Tech.isTech(tech)) {
  8115. throw new Error(`Tech ${name} must be a Tech`);
  8116. }
  8117. if (!Tech.canPlayType) {
  8118. throw new Error('Techs must have a static canPlayType method on them');
  8119. }
  8120. if (!Tech.canPlaySource) {
  8121. throw new Error('Techs must have a static canPlaySource method on them');
  8122. }
  8123. name = toTitleCase$1(name);
  8124. Tech.techs_[name] = tech;
  8125. Tech.techs_[toLowerCase(name)] = tech;
  8126. if (name !== 'Tech') {
  8127. // camel case the techName for use in techOrder
  8128. Tech.defaultTechOrder_.push(name);
  8129. }
  8130. return tech;
  8131. }
  8132. /**
  8133. * Get a `Tech` from the shared list by name.
  8134. *
  8135. * @param {string} name
  8136. * `camelCase` or `TitleCase` name of the Tech to get
  8137. *
  8138. * @return {Tech|undefined}
  8139. * The `Tech` or undefined if there was no tech with the name requested.
  8140. */
  8141. static getTech(name) {
  8142. if (!name) {
  8143. return;
  8144. }
  8145. if (Tech.techs_ && Tech.techs_[name]) {
  8146. return Tech.techs_[name];
  8147. }
  8148. name = toTitleCase$1(name);
  8149. if (window$1 && window$1.videojs && window$1.videojs[name]) {
  8150. log$1.warn(`The ${name} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`);
  8151. return window$1.videojs[name];
  8152. }
  8153. }
  8154. }
  8155. /**
  8156. * Get the {@link VideoTrackList}
  8157. *
  8158. * @returns {VideoTrackList}
  8159. * @method Tech.prototype.videoTracks
  8160. */
  8161. /**
  8162. * Get the {@link AudioTrackList}
  8163. *
  8164. * @returns {AudioTrackList}
  8165. * @method Tech.prototype.audioTracks
  8166. */
  8167. /**
  8168. * Get the {@link TextTrackList}
  8169. *
  8170. * @returns {TextTrackList}
  8171. * @method Tech.prototype.textTracks
  8172. */
  8173. /**
  8174. * Get the remote element {@link TextTrackList}
  8175. *
  8176. * @returns {TextTrackList}
  8177. * @method Tech.prototype.remoteTextTracks
  8178. */
  8179. /**
  8180. * Get the remote element {@link HtmlTrackElementList}
  8181. *
  8182. * @returns {HtmlTrackElementList}
  8183. * @method Tech.prototype.remoteTextTrackEls
  8184. */
  8185. ALL.names.forEach(function (name) {
  8186. const props = ALL[name];
  8187. Tech.prototype[props.getterName] = function () {
  8188. this[props.privateName] = this[props.privateName] || new props.ListClass();
  8189. return this[props.privateName];
  8190. };
  8191. });
  8192. /**
  8193. * List of associated text tracks
  8194. *
  8195. * @type {TextTrackList}
  8196. * @private
  8197. * @property Tech#textTracks_
  8198. */
  8199. /**
  8200. * List of associated audio tracks.
  8201. *
  8202. * @type {AudioTrackList}
  8203. * @private
  8204. * @property Tech#audioTracks_
  8205. */
  8206. /**
  8207. * List of associated video tracks.
  8208. *
  8209. * @type {VideoTrackList}
  8210. * @private
  8211. * @property Tech#videoTracks_
  8212. */
  8213. /**
  8214. * Boolean indicating whether the `Tech` supports volume control.
  8215. *
  8216. * @type {boolean}
  8217. * @default
  8218. */
  8219. Tech.prototype.featuresVolumeControl = true;
  8220. /**
  8221. * Boolean indicating whether the `Tech` supports muting volume.
  8222. *
  8223. * @type {boolean}
  8224. * @default
  8225. */
  8226. Tech.prototype.featuresMuteControl = true;
  8227. /**
  8228. * Boolean indicating whether the `Tech` supports fullscreen resize control.
  8229. * Resizing plugins using request fullscreen reloads the plugin
  8230. *
  8231. * @type {boolean}
  8232. * @default
  8233. */
  8234. Tech.prototype.featuresFullscreenResize = false;
  8235. /**
  8236. * Boolean indicating whether the `Tech` supports changing the speed at which the video
  8237. * plays. Examples:
  8238. * - Set player to play 2x (twice) as fast
  8239. * - Set player to play 0.5x (half) as fast
  8240. *
  8241. * @type {boolean}
  8242. * @default
  8243. */
  8244. Tech.prototype.featuresPlaybackRate = false;
  8245. /**
  8246. * Boolean indicating whether the `Tech` supports the `progress` event.
  8247. * This will be used to determine if {@link Tech#manualProgressOn} should be called.
  8248. *
  8249. * @type {boolean}
  8250. * @default
  8251. */
  8252. Tech.prototype.featuresProgressEvents = false;
  8253. /**
  8254. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  8255. *
  8256. * A tech should set this to `true` and then use {@link Tech#triggerSourceset}
  8257. * to trigger a {@link Tech#event:sourceset} at the earliest time after getting
  8258. * a new source.
  8259. *
  8260. * @type {boolean}
  8261. * @default
  8262. */
  8263. Tech.prototype.featuresSourceset = false;
  8264. /**
  8265. * Boolean indicating whether the `Tech` supports the `timeupdate` event.
  8266. * This will be used to determine if {@link Tech#manualTimeUpdates} should be called.
  8267. *
  8268. * @type {boolean}
  8269. * @default
  8270. */
  8271. Tech.prototype.featuresTimeupdateEvents = false;
  8272. /**
  8273. * Boolean indicating whether the `Tech` supports the native `TextTrack`s.
  8274. * This will help us integrate with native `TextTrack`s if the browser supports them.
  8275. *
  8276. * @type {boolean}
  8277. * @default
  8278. */
  8279. Tech.prototype.featuresNativeTextTracks = false;
  8280. /**
  8281. * Boolean indicating whether the `Tech` supports `requestVideoFrameCallback`.
  8282. *
  8283. * @type {boolean}
  8284. * @default
  8285. */
  8286. Tech.prototype.featuresVideoFrameCallback = false;
  8287. /**
  8288. * A functional mixin for techs that want to use the Source Handler pattern.
  8289. * Source handlers are scripts for handling specific formats.
  8290. * The source handler pattern is used for adaptive formats (HLS, DASH) that
  8291. * manually load video data and feed it into a Source Buffer (Media Source Extensions)
  8292. * Example: `Tech.withSourceHandlers.call(MyTech);`
  8293. *
  8294. * @param {Tech} _Tech
  8295. * The tech to add source handler functions to.
  8296. *
  8297. * @mixes Tech~SourceHandlerAdditions
  8298. */
  8299. Tech.withSourceHandlers = function (_Tech) {
  8300. /**
  8301. * Register a source handler
  8302. *
  8303. * @param {Function} handler
  8304. * The source handler class
  8305. *
  8306. * @param {number} [index]
  8307. * Register it at the following index
  8308. */
  8309. _Tech.registerSourceHandler = function (handler, index) {
  8310. let handlers = _Tech.sourceHandlers;
  8311. if (!handlers) {
  8312. handlers = _Tech.sourceHandlers = [];
  8313. }
  8314. if (index === undefined) {
  8315. // add to the end of the list
  8316. index = handlers.length;
  8317. }
  8318. handlers.splice(index, 0, handler);
  8319. };
  8320. /**
  8321. * Check if the tech can support the given type. Also checks the
  8322. * Techs sourceHandlers.
  8323. *
  8324. * @param {string} type
  8325. * The mimetype to check.
  8326. *
  8327. * @return {string}
  8328. * 'probably', 'maybe', or '' (empty string)
  8329. */
  8330. _Tech.canPlayType = function (type) {
  8331. const handlers = _Tech.sourceHandlers || [];
  8332. let can;
  8333. for (let i = 0; i < handlers.length; i++) {
  8334. can = handlers[i].canPlayType(type);
  8335. if (can) {
  8336. return can;
  8337. }
  8338. }
  8339. return '';
  8340. };
  8341. /**
  8342. * Returns the first source handler that supports the source.
  8343. *
  8344. * TODO: Answer question: should 'probably' be prioritized over 'maybe'
  8345. *
  8346. * @param {Tech~SourceObject} source
  8347. * The source object
  8348. *
  8349. * @param {Object} options
  8350. * The options passed to the tech
  8351. *
  8352. * @return {SourceHandler|null}
  8353. * The first source handler that supports the source or null if
  8354. * no SourceHandler supports the source
  8355. */
  8356. _Tech.selectSourceHandler = function (source, options) {
  8357. const handlers = _Tech.sourceHandlers || [];
  8358. let can;
  8359. for (let i = 0; i < handlers.length; i++) {
  8360. can = handlers[i].canHandleSource(source, options);
  8361. if (can) {
  8362. return handlers[i];
  8363. }
  8364. }
  8365. return null;
  8366. };
  8367. /**
  8368. * Check if the tech can support the given source.
  8369. *
  8370. * @param {Tech~SourceObject} srcObj
  8371. * The source object
  8372. *
  8373. * @param {Object} options
  8374. * The options passed to the tech
  8375. *
  8376. * @return {string}
  8377. * 'probably', 'maybe', or '' (empty string)
  8378. */
  8379. _Tech.canPlaySource = function (srcObj, options) {
  8380. const sh = _Tech.selectSourceHandler(srcObj, options);
  8381. if (sh) {
  8382. return sh.canHandleSource(srcObj, options);
  8383. }
  8384. return '';
  8385. };
  8386. /**
  8387. * When using a source handler, prefer its implementation of
  8388. * any function normally provided by the tech.
  8389. */
  8390. const deferrable = ['seekable', 'seeking', 'duration'];
  8391. /**
  8392. * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable
  8393. * function if it exists, with a fallback to the Techs seekable function.
  8394. *
  8395. * @method _Tech.seekable
  8396. */
  8397. /**
  8398. * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration
  8399. * function if it exists, otherwise it will fallback to the techs duration function.
  8400. *
  8401. * @method _Tech.duration
  8402. */
  8403. deferrable.forEach(function (fnName) {
  8404. const originalFn = this[fnName];
  8405. if (typeof originalFn !== 'function') {
  8406. return;
  8407. }
  8408. this[fnName] = function () {
  8409. if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
  8410. return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
  8411. }
  8412. return originalFn.apply(this, arguments);
  8413. };
  8414. }, _Tech.prototype);
  8415. /**
  8416. * Create a function for setting the source using a source object
  8417. * and source handlers.
  8418. * Should never be called unless a source handler was found.
  8419. *
  8420. * @param {Tech~SourceObject} source
  8421. * A source object with src and type keys
  8422. */
  8423. _Tech.prototype.setSource = function (source) {
  8424. let sh = _Tech.selectSourceHandler(source, this.options_);
  8425. if (!sh) {
  8426. // Fall back to a native source handler when unsupported sources are
  8427. // deliberately set
  8428. if (_Tech.nativeSourceHandler) {
  8429. sh = _Tech.nativeSourceHandler;
  8430. } else {
  8431. log$1.error('No source handler found for the current source.');
  8432. }
  8433. }
  8434. // Dispose any existing source handler
  8435. this.disposeSourceHandler();
  8436. this.off('dispose', this.disposeSourceHandler_);
  8437. if (sh !== _Tech.nativeSourceHandler) {
  8438. this.currentSource_ = source;
  8439. }
  8440. this.sourceHandler_ = sh.handleSource(source, this, this.options_);
  8441. this.one('dispose', this.disposeSourceHandler_);
  8442. };
  8443. /**
  8444. * Clean up any existing SourceHandlers and listeners when the Tech is disposed.
  8445. *
  8446. * @listens Tech#dispose
  8447. */
  8448. _Tech.prototype.disposeSourceHandler = function () {
  8449. // if we have a source and get another one
  8450. // then we are loading something new
  8451. // than clear all of our current tracks
  8452. if (this.currentSource_) {
  8453. this.clearTracks(['audio', 'video']);
  8454. this.currentSource_ = null;
  8455. }
  8456. // always clean up auto-text tracks
  8457. this.cleanupAutoTextTracks();
  8458. if (this.sourceHandler_) {
  8459. if (this.sourceHandler_.dispose) {
  8460. this.sourceHandler_.dispose();
  8461. }
  8462. this.sourceHandler_ = null;
  8463. }
  8464. };
  8465. };
  8466. // The base Tech class needs to be registered as a Component. It is the only
  8467. // Tech that can be registered as a Component.
  8468. Component$1.registerComponent('Tech', Tech);
  8469. Tech.registerTech('Tech', Tech);
  8470. /**
  8471. * A list of techs that should be added to techOrder on Players
  8472. *
  8473. * @private
  8474. */
  8475. Tech.defaultTechOrder_ = [];
  8476. /**
  8477. * @file middleware.js
  8478. * @module middleware
  8479. */
  8480. const middlewares = {};
  8481. const middlewareInstances = {};
  8482. const TERMINATOR = {};
  8483. /**
  8484. * A middleware object is a plain JavaScript object that has methods that
  8485. * match the {@link Tech} methods found in the lists of allowed
  8486. * {@link module:middleware.allowedGetters|getters},
  8487. * {@link module:middleware.allowedSetters|setters}, and
  8488. * {@link module:middleware.allowedMediators|mediators}.
  8489. *
  8490. * @typedef {Object} MiddlewareObject
  8491. */
  8492. /**
  8493. * A middleware factory function that should return a
  8494. * {@link module:middleware~MiddlewareObject|MiddlewareObject}.
  8495. *
  8496. * This factory will be called for each player when needed, with the player
  8497. * passed in as an argument.
  8498. *
  8499. * @callback MiddlewareFactory
  8500. * @param { import('../player').default } player
  8501. * A Video.js player.
  8502. */
  8503. /**
  8504. * Define a middleware that the player should use by way of a factory function
  8505. * that returns a middleware object.
  8506. *
  8507. * @param {string} type
  8508. * The MIME type to match or `"*"` for all MIME types.
  8509. *
  8510. * @param {MiddlewareFactory} middleware
  8511. * A middleware factory function that will be executed for
  8512. * matching types.
  8513. */
  8514. function use(type, middleware) {
  8515. middlewares[type] = middlewares[type] || [];
  8516. middlewares[type].push(middleware);
  8517. }
  8518. /**
  8519. * Asynchronously sets a source using middleware by recursing through any
  8520. * matching middlewares and calling `setSource` on each, passing along the
  8521. * previous returned value each time.
  8522. *
  8523. * @param { import('../player').default } player
  8524. * A {@link Player} instance.
  8525. *
  8526. * @param {Tech~SourceObject} src
  8527. * A source object.
  8528. *
  8529. * @param {Function}
  8530. * The next middleware to run.
  8531. */
  8532. function setSource(player, src, next) {
  8533. player.setTimeout(() => setSourceHelper(src, middlewares[src.type], next, player), 1);
  8534. }
  8535. /**
  8536. * When the tech is set, passes the tech to each middleware's `setTech` method.
  8537. *
  8538. * @param {Object[]} middleware
  8539. * An array of middleware instances.
  8540. *
  8541. * @param { import('../tech/tech').default } tech
  8542. * A Video.js tech.
  8543. */
  8544. function setTech(middleware, tech) {
  8545. middleware.forEach(mw => mw.setTech && mw.setTech(tech));
  8546. }
  8547. /**
  8548. * Calls a getter on the tech first, through each middleware
  8549. * from right to left to the player.
  8550. *
  8551. * @param {Object[]} middleware
  8552. * An array of middleware instances.
  8553. *
  8554. * @param { import('../tech/tech').default } tech
  8555. * The current tech.
  8556. *
  8557. * @param {string} method
  8558. * A method name.
  8559. *
  8560. * @return {*}
  8561. * The final value from the tech after middleware has intercepted it.
  8562. */
  8563. function get(middleware, tech, method) {
  8564. return middleware.reduceRight(middlewareIterator(method), tech[method]());
  8565. }
  8566. /**
  8567. * Takes the argument given to the player and calls the setter method on each
  8568. * middleware from left to right to the tech.
  8569. *
  8570. * @param {Object[]} middleware
  8571. * An array of middleware instances.
  8572. *
  8573. * @param { import('../tech/tech').default } tech
  8574. * The current tech.
  8575. *
  8576. * @param {string} method
  8577. * A method name.
  8578. *
  8579. * @param {*} arg
  8580. * The value to set on the tech.
  8581. *
  8582. * @return {*}
  8583. * The return value of the `method` of the `tech`.
  8584. */
  8585. function set(middleware, tech, method, arg) {
  8586. return tech[method](middleware.reduce(middlewareIterator(method), arg));
  8587. }
  8588. /**
  8589. * Takes the argument given to the player and calls the `call` version of the
  8590. * method on each middleware from left to right.
  8591. *
  8592. * Then, call the passed in method on the tech and return the result unchanged
  8593. * back to the player, through middleware, this time from right to left.
  8594. *
  8595. * @param {Object[]} middleware
  8596. * An array of middleware instances.
  8597. *
  8598. * @param { import('../tech/tech').default } tech
  8599. * The current tech.
  8600. *
  8601. * @param {string} method
  8602. * A method name.
  8603. *
  8604. * @param {*} arg
  8605. * The value to set on the tech.
  8606. *
  8607. * @return {*}
  8608. * The return value of the `method` of the `tech`, regardless of the
  8609. * return values of middlewares.
  8610. */
  8611. function mediate(middleware, tech, method, arg = null) {
  8612. const callMethod = 'call' + toTitleCase$1(method);
  8613. const middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
  8614. const terminated = middlewareValue === TERMINATOR;
  8615. // deprecated. The `null` return value should instead return TERMINATOR to
  8616. // prevent confusion if a techs method actually returns null.
  8617. const returnValue = terminated ? null : tech[method](middlewareValue);
  8618. executeRight(middleware, method, returnValue, terminated);
  8619. return returnValue;
  8620. }
  8621. /**
  8622. * Enumeration of allowed getters where the keys are method names.
  8623. *
  8624. * @type {Object}
  8625. */
  8626. const allowedGetters = {
  8627. buffered: 1,
  8628. currentTime: 1,
  8629. duration: 1,
  8630. muted: 1,
  8631. played: 1,
  8632. paused: 1,
  8633. seekable: 1,
  8634. volume: 1,
  8635. ended: 1
  8636. };
  8637. /**
  8638. * Enumeration of allowed setters where the keys are method names.
  8639. *
  8640. * @type {Object}
  8641. */
  8642. const allowedSetters = {
  8643. setCurrentTime: 1,
  8644. setMuted: 1,
  8645. setVolume: 1
  8646. };
  8647. /**
  8648. * Enumeration of allowed mediators where the keys are method names.
  8649. *
  8650. * @type {Object}
  8651. */
  8652. const allowedMediators = {
  8653. play: 1,
  8654. pause: 1
  8655. };
  8656. function middlewareIterator(method) {
  8657. return (value, mw) => {
  8658. // if the previous middleware terminated, pass along the termination
  8659. if (value === TERMINATOR) {
  8660. return TERMINATOR;
  8661. }
  8662. if (mw[method]) {
  8663. return mw[method](value);
  8664. }
  8665. return value;
  8666. };
  8667. }
  8668. function executeRight(mws, method, value, terminated) {
  8669. for (let i = mws.length - 1; i >= 0; i--) {
  8670. const mw = mws[i];
  8671. if (mw[method]) {
  8672. mw[method](terminated, value);
  8673. }
  8674. }
  8675. }
  8676. /**
  8677. * Clear the middleware cache for a player.
  8678. *
  8679. * @param { import('../player').default } player
  8680. * A {@link Player} instance.
  8681. */
  8682. function clearCacheForPlayer(player) {
  8683. middlewareInstances[player.id()] = null;
  8684. }
  8685. /**
  8686. * {
  8687. * [playerId]: [[mwFactory, mwInstance], ...]
  8688. * }
  8689. *
  8690. * @private
  8691. */
  8692. function getOrCreateFactory(player, mwFactory) {
  8693. const mws = middlewareInstances[player.id()];
  8694. let mw = null;
  8695. if (mws === undefined || mws === null) {
  8696. mw = mwFactory(player);
  8697. middlewareInstances[player.id()] = [[mwFactory, mw]];
  8698. return mw;
  8699. }
  8700. for (let i = 0; i < mws.length; i++) {
  8701. const [mwf, mwi] = mws[i];
  8702. if (mwf !== mwFactory) {
  8703. continue;
  8704. }
  8705. mw = mwi;
  8706. }
  8707. if (mw === null) {
  8708. mw = mwFactory(player);
  8709. mws.push([mwFactory, mw]);
  8710. }
  8711. return mw;
  8712. }
  8713. function setSourceHelper(src = {}, middleware = [], next, player, acc = [], lastRun = false) {
  8714. const [mwFactory, ...mwrest] = middleware;
  8715. // if mwFactory is a string, then we're at a fork in the road
  8716. if (typeof mwFactory === 'string') {
  8717. setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun);
  8718. // if we have an mwFactory, call it with the player to get the mw,
  8719. // then call the mw's setSource method
  8720. } else if (mwFactory) {
  8721. const mw = getOrCreateFactory(player, mwFactory);
  8722. // if setSource isn't present, implicitly select this middleware
  8723. if (!mw.setSource) {
  8724. acc.push(mw);
  8725. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  8726. }
  8727. mw.setSource(Object.assign({}, src), function (err, _src) {
  8728. // something happened, try the next middleware on the current level
  8729. // make sure to use the old src
  8730. if (err) {
  8731. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  8732. }
  8733. // we've succeeded, now we need to go deeper
  8734. acc.push(mw);
  8735. // if it's the same type, continue down the current chain
  8736. // otherwise, we want to go down the new chain
  8737. setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
  8738. });
  8739. } else if (mwrest.length) {
  8740. setSourceHelper(src, mwrest, next, player, acc, lastRun);
  8741. } else if (lastRun) {
  8742. next(src, acc);
  8743. } else {
  8744. setSourceHelper(src, middlewares['*'], next, player, acc, true);
  8745. }
  8746. }
  8747. /**
  8748. * Mimetypes
  8749. *
  8750. * @see https://www.iana.org/assignments/media-types/media-types.xhtml
  8751. * @typedef Mimetypes~Kind
  8752. * @enum
  8753. */
  8754. const MimetypesKind = {
  8755. opus: 'video/ogg',
  8756. ogv: 'video/ogg',
  8757. mp4: 'video/mp4',
  8758. mov: 'video/mp4',
  8759. m4v: 'video/mp4',
  8760. mkv: 'video/x-matroska',
  8761. m4a: 'audio/mp4',
  8762. mp3: 'audio/mpeg',
  8763. aac: 'audio/aac',
  8764. caf: 'audio/x-caf',
  8765. flac: 'audio/flac',
  8766. oga: 'audio/ogg',
  8767. wav: 'audio/wav',
  8768. m3u8: 'application/x-mpegURL',
  8769. mpd: 'application/dash+xml',
  8770. jpg: 'image/jpeg',
  8771. jpeg: 'image/jpeg',
  8772. gif: 'image/gif',
  8773. png: 'image/png',
  8774. svg: 'image/svg+xml',
  8775. webp: 'image/webp'
  8776. };
  8777. /**
  8778. * Get the mimetype of a given src url if possible
  8779. *
  8780. * @param {string} src
  8781. * The url to the src
  8782. *
  8783. * @return {string}
  8784. * return the mimetype if it was known or empty string otherwise
  8785. */
  8786. const getMimetype = function (src = '') {
  8787. const ext = getFileExtension(src);
  8788. const mimetype = MimetypesKind[ext.toLowerCase()];
  8789. return mimetype || '';
  8790. };
  8791. /**
  8792. * Find the mime type of a given source string if possible. Uses the player
  8793. * source cache.
  8794. *
  8795. * @param { import('../player').default } player
  8796. * The player object
  8797. *
  8798. * @param {string} src
  8799. * The source string
  8800. *
  8801. * @return {string}
  8802. * The type that was found
  8803. */
  8804. const findMimetype = (player, src) => {
  8805. if (!src) {
  8806. return '';
  8807. }
  8808. // 1. check for the type in the `source` cache
  8809. if (player.cache_.source.src === src && player.cache_.source.type) {
  8810. return player.cache_.source.type;
  8811. }
  8812. // 2. see if we have this source in our `currentSources` cache
  8813. const matchingSources = player.cache_.sources.filter(s => s.src === src);
  8814. if (matchingSources.length) {
  8815. return matchingSources[0].type;
  8816. }
  8817. // 3. look for the src url in source elements and use the type there
  8818. const sources = player.$$('source');
  8819. for (let i = 0; i < sources.length; i++) {
  8820. const s = sources[i];
  8821. if (s.type && s.src && s.src === src) {
  8822. return s.type;
  8823. }
  8824. }
  8825. // 4. finally fallback to our list of mime types based on src url extension
  8826. return getMimetype(src);
  8827. };
  8828. /**
  8829. * @module filter-source
  8830. */
  8831. /**
  8832. * Filter out single bad source objects or multiple source objects in an
  8833. * array. Also flattens nested source object arrays into a 1 dimensional
  8834. * array of source objects.
  8835. *
  8836. * @param {Tech~SourceObject|Tech~SourceObject[]} src
  8837. * The src object to filter
  8838. *
  8839. * @return {Tech~SourceObject[]}
  8840. * An array of sourceobjects containing only valid sources
  8841. *
  8842. * @private
  8843. */
  8844. const filterSource = function (src) {
  8845. // traverse array
  8846. if (Array.isArray(src)) {
  8847. let newsrc = [];
  8848. src.forEach(function (srcobj) {
  8849. srcobj = filterSource(srcobj);
  8850. if (Array.isArray(srcobj)) {
  8851. newsrc = newsrc.concat(srcobj);
  8852. } else if (isObject(srcobj)) {
  8853. newsrc.push(srcobj);
  8854. }
  8855. });
  8856. src = newsrc;
  8857. } else if (typeof src === 'string' && src.trim()) {
  8858. // convert string into object
  8859. src = [fixSource({
  8860. src
  8861. })];
  8862. } else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
  8863. // src is already valid
  8864. src = [fixSource(src)];
  8865. } else {
  8866. // invalid source, turn it into an empty array
  8867. src = [];
  8868. }
  8869. return src;
  8870. };
  8871. /**
  8872. * Checks src mimetype, adding it when possible
  8873. *
  8874. * @param {Tech~SourceObject} src
  8875. * The src object to check
  8876. * @return {Tech~SourceObject}
  8877. * src Object with known type
  8878. */
  8879. function fixSource(src) {
  8880. if (!src.type) {
  8881. const mimetype = getMimetype(src.src);
  8882. if (mimetype) {
  8883. src.type = mimetype;
  8884. }
  8885. }
  8886. return src;
  8887. }
  8888. /**
  8889. * @file loader.js
  8890. */
  8891. /**
  8892. * The `MediaLoader` is the `Component` that decides which playback technology to load
  8893. * when a player is initialized.
  8894. *
  8895. * @extends Component
  8896. */
  8897. class MediaLoader extends Component$1 {
  8898. /**
  8899. * Create an instance of this class.
  8900. *
  8901. * @param { import('../player').default } player
  8902. * The `Player` that this class should attach to.
  8903. *
  8904. * @param {Object} [options]
  8905. * The key/value store of player options.
  8906. *
  8907. * @param {Function} [ready]
  8908. * The function that is run when this component is ready.
  8909. */
  8910. constructor(player, options, ready) {
  8911. // MediaLoader has no element
  8912. const options_ = merge$1({
  8913. createEl: false
  8914. }, options);
  8915. super(player, options_, ready);
  8916. // If there are no sources when the player is initialized,
  8917. // load the first supported playback technology.
  8918. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
  8919. for (let i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
  8920. const techName = toTitleCase$1(j[i]);
  8921. let tech = Tech.getTech(techName);
  8922. // Support old behavior of techs being registered as components.
  8923. // Remove once that deprecated behavior is removed.
  8924. if (!techName) {
  8925. tech = Component$1.getComponent(techName);
  8926. }
  8927. // Check if the browser supports this technology
  8928. if (tech && tech.isSupported()) {
  8929. player.loadTech_(techName);
  8930. break;
  8931. }
  8932. }
  8933. } else {
  8934. // Loop through playback technologies (e.g. HTML5) and check for support.
  8935. // Then load the best source.
  8936. // A few assumptions here:
  8937. // All playback technologies respect preload false.
  8938. player.src(options.playerOptions.sources);
  8939. }
  8940. }
  8941. }
  8942. Component$1.registerComponent('MediaLoader', MediaLoader);
  8943. /**
  8944. * @file clickable-component.js
  8945. */
  8946. /**
  8947. * Component which is clickable or keyboard actionable, but is not a
  8948. * native HTML button.
  8949. *
  8950. * @extends Component
  8951. */
  8952. class ClickableComponent extends Component$1 {
  8953. /**
  8954. * Creates an instance of this class.
  8955. *
  8956. * @param { import('./player').default } player
  8957. * The `Player` that this class should be attached to.
  8958. *
  8959. * @param {Object} [options]
  8960. * The key/value store of component options.
  8961. *
  8962. * @param {function} [options.clickHandler]
  8963. * The function to call when the button is clicked / activated
  8964. *
  8965. * @param {string} [options.controlText]
  8966. * The text to set on the button
  8967. *
  8968. * @param {string} [options.className]
  8969. * A class or space separated list of classes to add the component
  8970. *
  8971. */
  8972. constructor(player, options) {
  8973. super(player, options);
  8974. if (this.options_.controlText) {
  8975. this.controlText(this.options_.controlText);
  8976. }
  8977. this.handleMouseOver_ = e => this.handleMouseOver(e);
  8978. this.handleMouseOut_ = e => this.handleMouseOut(e);
  8979. this.handleClick_ = e => this.handleClick(e);
  8980. this.handleKeyDown_ = e => this.handleKeyDown(e);
  8981. this.emitTapEvents();
  8982. this.enable();
  8983. }
  8984. /**
  8985. * Create the `ClickableComponent`s DOM element.
  8986. *
  8987. * @param {string} [tag=div]
  8988. * The element's node type.
  8989. *
  8990. * @param {Object} [props={}]
  8991. * An object of properties that should be set on the element.
  8992. *
  8993. * @param {Object} [attributes={}]
  8994. * An object of attributes that should be set on the element.
  8995. *
  8996. * @return {Element}
  8997. * The element that gets created.
  8998. */
  8999. createEl(tag = 'div', props = {}, attributes = {}) {
  9000. props = Object.assign({
  9001. className: this.buildCSSClass(),
  9002. tabIndex: 0
  9003. }, props);
  9004. if (tag === 'button') {
  9005. log$1.error(`Creating a ClickableComponent with an HTML element of ${tag} is not supported; use a Button instead.`);
  9006. }
  9007. // Add ARIA attributes for clickable element which is not a native HTML button
  9008. attributes = Object.assign({
  9009. role: 'button'
  9010. }, attributes);
  9011. this.tabIndex_ = props.tabIndex;
  9012. const el = createEl(tag, props, attributes);
  9013. el.appendChild(createEl('span', {
  9014. className: 'vjs-icon-placeholder'
  9015. }, {
  9016. 'aria-hidden': true
  9017. }));
  9018. this.createControlTextEl(el);
  9019. return el;
  9020. }
  9021. dispose() {
  9022. // remove controlTextEl_ on dispose
  9023. this.controlTextEl_ = null;
  9024. super.dispose();
  9025. }
  9026. /**
  9027. * Create a control text element on this `ClickableComponent`
  9028. *
  9029. * @param {Element} [el]
  9030. * Parent element for the control text.
  9031. *
  9032. * @return {Element}
  9033. * The control text element that gets created.
  9034. */
  9035. createControlTextEl(el) {
  9036. this.controlTextEl_ = createEl('span', {
  9037. className: 'vjs-control-text'
  9038. }, {
  9039. // let the screen reader user know that the text of the element may change
  9040. 'aria-live': 'polite'
  9041. });
  9042. if (el) {
  9043. el.appendChild(this.controlTextEl_);
  9044. }
  9045. this.controlText(this.controlText_, el);
  9046. return this.controlTextEl_;
  9047. }
  9048. /**
  9049. * Get or set the localize text to use for the controls on the `ClickableComponent`.
  9050. *
  9051. * @param {string} [text]
  9052. * Control text for element.
  9053. *
  9054. * @param {Element} [el=this.el()]
  9055. * Element to set the title on.
  9056. *
  9057. * @return {string}
  9058. * - The control text when getting
  9059. */
  9060. controlText(text, el = this.el()) {
  9061. if (text === undefined) {
  9062. return this.controlText_ || 'Need Text';
  9063. }
  9064. const localizedText = this.localize(text);
  9065. /** @protected */
  9066. this.controlText_ = text;
  9067. textContent(this.controlTextEl_, localizedText);
  9068. if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {
  9069. // Set title attribute if only an icon is shown
  9070. el.setAttribute('title', localizedText);
  9071. }
  9072. }
  9073. /**
  9074. * Builds the default DOM `className`.
  9075. *
  9076. * @return {string}
  9077. * The DOM `className` for this object.
  9078. */
  9079. buildCSSClass() {
  9080. return `vjs-control vjs-button ${super.buildCSSClass()}`;
  9081. }
  9082. /**
  9083. * Enable this `ClickableComponent`
  9084. */
  9085. enable() {
  9086. if (!this.enabled_) {
  9087. this.enabled_ = true;
  9088. this.removeClass('vjs-disabled');
  9089. this.el_.setAttribute('aria-disabled', 'false');
  9090. if (typeof this.tabIndex_ !== 'undefined') {
  9091. this.el_.setAttribute('tabIndex', this.tabIndex_);
  9092. }
  9093. this.on(['tap', 'click'], this.handleClick_);
  9094. this.on('keydown', this.handleKeyDown_);
  9095. }
  9096. }
  9097. /**
  9098. * Disable this `ClickableComponent`
  9099. */
  9100. disable() {
  9101. this.enabled_ = false;
  9102. this.addClass('vjs-disabled');
  9103. this.el_.setAttribute('aria-disabled', 'true');
  9104. if (typeof this.tabIndex_ !== 'undefined') {
  9105. this.el_.removeAttribute('tabIndex');
  9106. }
  9107. this.off('mouseover', this.handleMouseOver_);
  9108. this.off('mouseout', this.handleMouseOut_);
  9109. this.off(['tap', 'click'], this.handleClick_);
  9110. this.off('keydown', this.handleKeyDown_);
  9111. }
  9112. /**
  9113. * Handles language change in ClickableComponent for the player in components
  9114. *
  9115. *
  9116. */
  9117. handleLanguagechange() {
  9118. this.controlText(this.controlText_);
  9119. }
  9120. /**
  9121. * Event handler that is called when a `ClickableComponent` receives a
  9122. * `click` or `tap` event.
  9123. *
  9124. * @param {Event} event
  9125. * The `tap` or `click` event that caused this function to be called.
  9126. *
  9127. * @listens tap
  9128. * @listens click
  9129. * @abstract
  9130. */
  9131. handleClick(event) {
  9132. if (this.options_.clickHandler) {
  9133. this.options_.clickHandler.call(this, arguments);
  9134. }
  9135. }
  9136. /**
  9137. * Event handler that is called when a `ClickableComponent` receives a
  9138. * `keydown` event.
  9139. *
  9140. * By default, if the key is Space or Enter, it will trigger a `click` event.
  9141. *
  9142. * @param {Event} event
  9143. * The `keydown` event that caused this function to be called.
  9144. *
  9145. * @listens keydown
  9146. */
  9147. handleKeyDown(event) {
  9148. // Support Space or Enter key operation to fire a click event. Also,
  9149. // prevent the event from propagating through the DOM and triggering
  9150. // Player hotkeys.
  9151. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  9152. event.preventDefault();
  9153. event.stopPropagation();
  9154. this.trigger('click');
  9155. } else {
  9156. // Pass keypress handling up for unsupported keys
  9157. super.handleKeyDown(event);
  9158. }
  9159. }
  9160. }
  9161. Component$1.registerComponent('ClickableComponent', ClickableComponent);
  9162. /**
  9163. * @file poster-image.js
  9164. */
  9165. /**
  9166. * A `ClickableComponent` that handles showing the poster image for the player.
  9167. *
  9168. * @extends ClickableComponent
  9169. */
  9170. class PosterImage extends ClickableComponent {
  9171. /**
  9172. * Create an instance of this class.
  9173. *
  9174. * @param { import('./player').default } player
  9175. * The `Player` that this class should attach to.
  9176. *
  9177. * @param {Object} [options]
  9178. * The key/value store of player options.
  9179. */
  9180. constructor(player, options) {
  9181. super(player, options);
  9182. this.update();
  9183. this.update_ = e => this.update(e);
  9184. player.on('posterchange', this.update_);
  9185. }
  9186. /**
  9187. * Clean up and dispose of the `PosterImage`.
  9188. */
  9189. dispose() {
  9190. this.player().off('posterchange', this.update_);
  9191. super.dispose();
  9192. }
  9193. /**
  9194. * Create the `PosterImage`s DOM element.
  9195. *
  9196. * @return {Element}
  9197. * The element that gets created.
  9198. */
  9199. createEl() {
  9200. // The el is an empty div to keep position in the DOM
  9201. // A picture and img el will be inserted when a source is set
  9202. return createEl('div', {
  9203. className: 'vjs-poster'
  9204. });
  9205. }
  9206. /**
  9207. * Get or set the `PosterImage`'s crossOrigin option.
  9208. *
  9209. * @param {string|null} [value]
  9210. * The value to set the crossOrigin to. If an argument is
  9211. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  9212. *
  9213. * @return {string|null}
  9214. * - The current crossOrigin value of the `Player` when getting.
  9215. * - undefined when setting
  9216. */
  9217. crossOrigin(value) {
  9218. // `null` can be set to unset a value
  9219. if (typeof value === 'undefined') {
  9220. if (this.$('img')) {
  9221. // If the poster's element exists, give its value
  9222. return this.$('img').crossOrigin;
  9223. } else if (this.player_.tech_ && this.player_.tech_.isReady_) {
  9224. // If not but the tech is ready, query the tech
  9225. return this.player_.crossOrigin();
  9226. }
  9227. // Otherwise check options as the poster is usually set before the state of crossorigin
  9228. // can be retrieved by the getter
  9229. return this.player_.options_.crossOrigin || this.player_.options_.crossorigin || null;
  9230. }
  9231. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  9232. this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  9233. return;
  9234. }
  9235. if (this.$('img')) {
  9236. this.$('img').crossOrigin = value;
  9237. }
  9238. return;
  9239. }
  9240. /**
  9241. * An {@link EventTarget~EventListener} for {@link Player#posterchange} events.
  9242. *
  9243. * @listens Player#posterchange
  9244. *
  9245. * @param {Event} [event]
  9246. * The `Player#posterchange` event that triggered this function.
  9247. */
  9248. update(event) {
  9249. const url = this.player().poster();
  9250. this.setSrc(url);
  9251. // If there's no poster source we should display:none on this component
  9252. // so it's not still clickable or right-clickable
  9253. if (url) {
  9254. this.show();
  9255. } else {
  9256. this.hide();
  9257. }
  9258. }
  9259. /**
  9260. * Set the source of the `PosterImage` depending on the display method. (Re)creates
  9261. * the inner picture and img elementss when needed.
  9262. *
  9263. * @param {string} [url]
  9264. * The URL to the source for the `PosterImage`. If not specified or falsy,
  9265. * any source and ant inner picture/img are removed.
  9266. */
  9267. setSrc(url) {
  9268. if (!url) {
  9269. this.el_.textContent = '';
  9270. return;
  9271. }
  9272. if (!this.$('img')) {
  9273. this.el_.appendChild(createEl('picture', {
  9274. className: 'vjs-poster',
  9275. // Don't want poster to be tabbable.
  9276. tabIndex: -1
  9277. }, {}, createEl('img', {
  9278. loading: 'lazy',
  9279. crossOrigin: this.crossOrigin()
  9280. }, {
  9281. alt: ''
  9282. })));
  9283. }
  9284. this.$('img').src = url;
  9285. }
  9286. /**
  9287. * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See
  9288. * {@link ClickableComponent#handleClick} for instances where this will be triggered.
  9289. *
  9290. * @listens tap
  9291. * @listens click
  9292. * @listens keydown
  9293. *
  9294. * @param {Event} event
  9295. + The `click`, `tap` or `keydown` event that caused this function to be called.
  9296. */
  9297. handleClick(event) {
  9298. // We don't want a click to trigger playback when controls are disabled
  9299. if (!this.player_.controls()) {
  9300. return;
  9301. }
  9302. if (this.player_.tech(true)) {
  9303. this.player_.tech(true).focus();
  9304. }
  9305. if (this.player_.paused()) {
  9306. silencePromise(this.player_.play());
  9307. } else {
  9308. this.player_.pause();
  9309. }
  9310. }
  9311. }
  9312. /**
  9313. * Get or set the `PosterImage`'s crossorigin option. For the HTML5 player, this
  9314. * sets the `crossOrigin` property on the `<img>` tag to control the CORS
  9315. * behavior.
  9316. *
  9317. * @param {string|null} [value]
  9318. * The value to set the `PosterImages`'s crossorigin to. If an argument is
  9319. * given, must be one of `anonymous` or `use-credentials`.
  9320. *
  9321. * @return {string|null|undefined}
  9322. * - The current crossorigin value of the `Player` when getting.
  9323. * - undefined when setting
  9324. */
  9325. PosterImage.prototype.crossorigin = PosterImage.prototype.crossOrigin;
  9326. Component$1.registerComponent('PosterImage', PosterImage);
  9327. /**
  9328. * @file text-track-display.js
  9329. */
  9330. const darkGray = '#222';
  9331. const lightGray = '#ccc';
  9332. const fontMap = {
  9333. monospace: 'monospace',
  9334. sansSerif: 'sans-serif',
  9335. serif: 'serif',
  9336. monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
  9337. monospaceSerif: '"Courier New", monospace',
  9338. proportionalSansSerif: 'sans-serif',
  9339. proportionalSerif: 'serif',
  9340. casual: '"Comic Sans MS", Impact, fantasy',
  9341. script: '"Monotype Corsiva", cursive',
  9342. smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
  9343. };
  9344. /**
  9345. * Construct an rgba color from a given hex color code.
  9346. *
  9347. * @param {number} color
  9348. * Hex number for color, like #f0e or #f604e2.
  9349. *
  9350. * @param {number} opacity
  9351. * Value for opacity, 0.0 - 1.0.
  9352. *
  9353. * @return {string}
  9354. * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
  9355. */
  9356. function constructColor(color, opacity) {
  9357. let hex;
  9358. if (color.length === 4) {
  9359. // color looks like "#f0e"
  9360. hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
  9361. } else if (color.length === 7) {
  9362. // color looks like "#f604e2"
  9363. hex = color.slice(1);
  9364. } else {
  9365. throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
  9366. }
  9367. return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';
  9368. }
  9369. /**
  9370. * Try to update the style of a DOM element. Some style changes will throw an error,
  9371. * particularly in IE8. Those should be noops.
  9372. *
  9373. * @param {Element} el
  9374. * The DOM element to be styled.
  9375. *
  9376. * @param {string} style
  9377. * The CSS property on the element that should be styled.
  9378. *
  9379. * @param {string} rule
  9380. * The style rule that should be applied to the property.
  9381. *
  9382. * @private
  9383. */
  9384. function tryUpdateStyle(el, style, rule) {
  9385. try {
  9386. el.style[style] = rule;
  9387. } catch (e) {
  9388. // Satisfies linter.
  9389. return;
  9390. }
  9391. }
  9392. /**
  9393. * The component for displaying text track cues.
  9394. *
  9395. * @extends Component
  9396. */
  9397. class TextTrackDisplay extends Component$1 {
  9398. /**
  9399. * Creates an instance of this class.
  9400. *
  9401. * @param { import('../player').default } player
  9402. * The `Player` that this class should be attached to.
  9403. *
  9404. * @param {Object} [options]
  9405. * The key/value store of player options.
  9406. *
  9407. * @param {Function} [ready]
  9408. * The function to call when `TextTrackDisplay` is ready.
  9409. */
  9410. constructor(player, options, ready) {
  9411. super(player, options, ready);
  9412. const updateDisplayHandler = e => this.updateDisplay(e);
  9413. player.on('loadstart', e => this.toggleDisplay(e));
  9414. player.on('texttrackchange', updateDisplayHandler);
  9415. player.on('loadedmetadata', e => this.preselectTrack(e));
  9416. // This used to be called during player init, but was causing an error
  9417. // if a track should show by default and the display hadn't loaded yet.
  9418. // Should probably be moved to an external track loader when we support
  9419. // tracks that don't need a display.
  9420. player.ready(bind_(this, function () {
  9421. if (player.tech_ && player.tech_.featuresNativeTextTracks) {
  9422. this.hide();
  9423. return;
  9424. }
  9425. player.on('fullscreenchange', updateDisplayHandler);
  9426. player.on('playerresize', updateDisplayHandler);
  9427. const screenOrientation = window$1.screen.orientation || window$1;
  9428. const changeOrientationEvent = window$1.screen.orientation ? 'change' : 'orientationchange';
  9429. screenOrientation.addEventListener(changeOrientationEvent, updateDisplayHandler);
  9430. player.on('dispose', () => screenOrientation.removeEventListener(changeOrientationEvent, updateDisplayHandler));
  9431. const tracks = this.options_.playerOptions.tracks || [];
  9432. for (let i = 0; i < tracks.length; i++) {
  9433. this.player_.addRemoteTextTrack(tracks[i], true);
  9434. }
  9435. this.preselectTrack();
  9436. }));
  9437. }
  9438. /**
  9439. * Preselect a track following this precedence:
  9440. * - matches the previously selected {@link TextTrack}'s language and kind
  9441. * - matches the previously selected {@link TextTrack}'s language only
  9442. * - is the first default captions track
  9443. * - is the first default descriptions track
  9444. *
  9445. * @listens Player#loadstart
  9446. */
  9447. preselectTrack() {
  9448. const modes = {
  9449. captions: 1,
  9450. subtitles: 1
  9451. };
  9452. const trackList = this.player_.textTracks();
  9453. const userPref = this.player_.cache_.selectedLanguage;
  9454. let firstDesc;
  9455. let firstCaptions;
  9456. let preferredTrack;
  9457. for (let i = 0; i < trackList.length; i++) {
  9458. const track = trackList[i];
  9459. if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {
  9460. // Always choose the track that matches both language and kind
  9461. if (track.kind === userPref.kind) {
  9462. preferredTrack = track;
  9463. // or choose the first track that matches language
  9464. } else if (!preferredTrack) {
  9465. preferredTrack = track;
  9466. }
  9467. // clear everything if offTextTrackMenuItem was clicked
  9468. } else if (userPref && !userPref.enabled) {
  9469. preferredTrack = null;
  9470. firstDesc = null;
  9471. firstCaptions = null;
  9472. } else if (track.default) {
  9473. if (track.kind === 'descriptions' && !firstDesc) {
  9474. firstDesc = track;
  9475. } else if (track.kind in modes && !firstCaptions) {
  9476. firstCaptions = track;
  9477. }
  9478. }
  9479. }
  9480. // The preferredTrack matches the user preference and takes
  9481. // precedence over all the other tracks.
  9482. // So, display the preferredTrack before the first default track
  9483. // and the subtitles/captions track before the descriptions track
  9484. if (preferredTrack) {
  9485. preferredTrack.mode = 'showing';
  9486. } else if (firstCaptions) {
  9487. firstCaptions.mode = 'showing';
  9488. } else if (firstDesc) {
  9489. firstDesc.mode = 'showing';
  9490. }
  9491. }
  9492. /**
  9493. * Turn display of {@link TextTrack}'s from the current state into the other state.
  9494. * There are only two states:
  9495. * - 'shown'
  9496. * - 'hidden'
  9497. *
  9498. * @listens Player#loadstart
  9499. */
  9500. toggleDisplay() {
  9501. if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
  9502. this.hide();
  9503. } else {
  9504. this.show();
  9505. }
  9506. }
  9507. /**
  9508. * Create the {@link Component}'s DOM element.
  9509. *
  9510. * @return {Element}
  9511. * The element that was created.
  9512. */
  9513. createEl() {
  9514. return super.createEl('div', {
  9515. className: 'vjs-text-track-display'
  9516. }, {
  9517. 'translate': 'yes',
  9518. 'aria-live': 'off',
  9519. 'aria-atomic': 'true'
  9520. });
  9521. }
  9522. /**
  9523. * Clear all displayed {@link TextTrack}s.
  9524. */
  9525. clearDisplay() {
  9526. if (typeof window$1.WebVTT === 'function') {
  9527. window$1.WebVTT.processCues(window$1, [], this.el_);
  9528. }
  9529. }
  9530. /**
  9531. * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or
  9532. * a {@link Player#fullscreenchange} is fired.
  9533. *
  9534. * @listens Player#texttrackchange
  9535. * @listens Player#fullscreenchange
  9536. */
  9537. updateDisplay() {
  9538. const tracks = this.player_.textTracks();
  9539. const allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;
  9540. this.clearDisplay();
  9541. if (allowMultipleShowingTracks) {
  9542. const showingTracks = [];
  9543. for (let i = 0; i < tracks.length; ++i) {
  9544. const track = tracks[i];
  9545. if (track.mode !== 'showing') {
  9546. continue;
  9547. }
  9548. showingTracks.push(track);
  9549. }
  9550. this.updateForTrack(showingTracks);
  9551. return;
  9552. }
  9553. // Track display prioritization model: if multiple tracks are 'showing',
  9554. // display the first 'subtitles' or 'captions' track which is 'showing',
  9555. // otherwise display the first 'descriptions' track which is 'showing'
  9556. let descriptionsTrack = null;
  9557. let captionsSubtitlesTrack = null;
  9558. let i = tracks.length;
  9559. while (i--) {
  9560. const track = tracks[i];
  9561. if (track.mode === 'showing') {
  9562. if (track.kind === 'descriptions') {
  9563. descriptionsTrack = track;
  9564. } else {
  9565. captionsSubtitlesTrack = track;
  9566. }
  9567. }
  9568. }
  9569. if (captionsSubtitlesTrack) {
  9570. if (this.getAttribute('aria-live') !== 'off') {
  9571. this.setAttribute('aria-live', 'off');
  9572. }
  9573. this.updateForTrack(captionsSubtitlesTrack);
  9574. } else if (descriptionsTrack) {
  9575. if (this.getAttribute('aria-live') !== 'assertive') {
  9576. this.setAttribute('aria-live', 'assertive');
  9577. }
  9578. this.updateForTrack(descriptionsTrack);
  9579. }
  9580. }
  9581. /**
  9582. * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}.
  9583. *
  9584. * @param {TextTrack} track
  9585. * Text track object containing active cues to style.
  9586. */
  9587. updateDisplayState(track) {
  9588. const overrides = this.player_.textTrackSettings.getValues();
  9589. const cues = track.activeCues;
  9590. let i = cues.length;
  9591. while (i--) {
  9592. const cue = cues[i];
  9593. if (!cue) {
  9594. continue;
  9595. }
  9596. const cueDiv = cue.displayState;
  9597. if (overrides.color) {
  9598. cueDiv.firstChild.style.color = overrides.color;
  9599. }
  9600. if (overrides.textOpacity) {
  9601. tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
  9602. }
  9603. if (overrides.backgroundColor) {
  9604. cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
  9605. }
  9606. if (overrides.backgroundOpacity) {
  9607. tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
  9608. }
  9609. if (overrides.windowColor) {
  9610. if (overrides.windowOpacity) {
  9611. tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
  9612. } else {
  9613. cueDiv.style.backgroundColor = overrides.windowColor;
  9614. }
  9615. }
  9616. if (overrides.edgeStyle) {
  9617. if (overrides.edgeStyle === 'dropshadow') {
  9618. cueDiv.firstChild.style.textShadow = `2px 2px 3px ${darkGray}, 2px 2px 4px ${darkGray}, 2px 2px 5px ${darkGray}`;
  9619. } else if (overrides.edgeStyle === 'raised') {
  9620. cueDiv.firstChild.style.textShadow = `1px 1px ${darkGray}, 2px 2px ${darkGray}, 3px 3px ${darkGray}`;
  9621. } else if (overrides.edgeStyle === 'depressed') {
  9622. cueDiv.firstChild.style.textShadow = `1px 1px ${lightGray}, 0 1px ${lightGray}, -1px -1px ${darkGray}, 0 -1px ${darkGray}`;
  9623. } else if (overrides.edgeStyle === 'uniform') {
  9624. cueDiv.firstChild.style.textShadow = `0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}`;
  9625. }
  9626. }
  9627. if (overrides.fontPercent && overrides.fontPercent !== 1) {
  9628. const fontSize = window$1.parseFloat(cueDiv.style.fontSize);
  9629. cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
  9630. cueDiv.style.height = 'auto';
  9631. cueDiv.style.top = 'auto';
  9632. }
  9633. if (overrides.fontFamily && overrides.fontFamily !== 'default') {
  9634. if (overrides.fontFamily === 'small-caps') {
  9635. cueDiv.firstChild.style.fontVariant = 'small-caps';
  9636. } else {
  9637. cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
  9638. }
  9639. }
  9640. }
  9641. }
  9642. /**
  9643. * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}.
  9644. *
  9645. * @param {TextTrack|TextTrack[]} tracks
  9646. * Text track object or text track array to be added to the list.
  9647. */
  9648. updateForTrack(tracks) {
  9649. if (!Array.isArray(tracks)) {
  9650. tracks = [tracks];
  9651. }
  9652. if (typeof window$1.WebVTT !== 'function' || tracks.every(track => {
  9653. return !track.activeCues;
  9654. })) {
  9655. return;
  9656. }
  9657. const cues = [];
  9658. // push all active track cues
  9659. for (let i = 0; i < tracks.length; ++i) {
  9660. const track = tracks[i];
  9661. for (let j = 0; j < track.activeCues.length; ++j) {
  9662. cues.push(track.activeCues[j]);
  9663. }
  9664. }
  9665. // removes all cues before it processes new ones
  9666. window$1.WebVTT.processCues(window$1, cues, this.el_);
  9667. // add unique class to each language text track & add settings styling if necessary
  9668. for (let i = 0; i < tracks.length; ++i) {
  9669. const track = tracks[i];
  9670. for (let j = 0; j < track.activeCues.length; ++j) {
  9671. const cueEl = track.activeCues[j].displayState;
  9672. addClass(cueEl, 'vjs-text-track-cue', 'vjs-text-track-cue-' + (track.language ? track.language : i));
  9673. if (track.language) {
  9674. setAttribute(cueEl, 'lang', track.language);
  9675. }
  9676. }
  9677. if (this.player_.textTrackSettings) {
  9678. this.updateDisplayState(track);
  9679. }
  9680. }
  9681. }
  9682. }
  9683. Component$1.registerComponent('TextTrackDisplay', TextTrackDisplay);
  9684. /**
  9685. * @file loading-spinner.js
  9686. */
  9687. /**
  9688. * A loading spinner for use during waiting/loading events.
  9689. *
  9690. * @extends Component
  9691. */
  9692. class LoadingSpinner extends Component$1 {
  9693. /**
  9694. * Create the `LoadingSpinner`s DOM element.
  9695. *
  9696. * @return {Element}
  9697. * The dom element that gets created.
  9698. */
  9699. createEl() {
  9700. const isAudio = this.player_.isAudio();
  9701. const playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
  9702. const controlText = createEl('span', {
  9703. className: 'vjs-control-text',
  9704. textContent: this.localize('{1} is loading.', [playerType])
  9705. });
  9706. const el = super.createEl('div', {
  9707. className: 'vjs-loading-spinner',
  9708. dir: 'ltr'
  9709. });
  9710. el.appendChild(controlText);
  9711. return el;
  9712. }
  9713. /**
  9714. * Update control text on languagechange
  9715. */
  9716. handleLanguagechange() {
  9717. this.$('.vjs-control-text').textContent = this.localize('{1} is loading.', [this.player_.isAudio() ? 'Audio Player' : 'Video Player']);
  9718. }
  9719. }
  9720. Component$1.registerComponent('LoadingSpinner', LoadingSpinner);
  9721. /**
  9722. * @file button.js
  9723. */
  9724. /**
  9725. * Base class for all buttons.
  9726. *
  9727. * @extends ClickableComponent
  9728. */
  9729. class Button extends ClickableComponent {
  9730. /**
  9731. * Create the `Button`s DOM element.
  9732. *
  9733. * @param {string} [tag="button"]
  9734. * The element's node type. This argument is IGNORED: no matter what
  9735. * is passed, it will always create a `button` element.
  9736. *
  9737. * @param {Object} [props={}]
  9738. * An object of properties that should be set on the element.
  9739. *
  9740. * @param {Object} [attributes={}]
  9741. * An object of attributes that should be set on the element.
  9742. *
  9743. * @return {Element}
  9744. * The element that gets created.
  9745. */
  9746. createEl(tag, props = {}, attributes = {}) {
  9747. tag = 'button';
  9748. props = Object.assign({
  9749. className: this.buildCSSClass()
  9750. }, props);
  9751. // Add attributes for button element
  9752. attributes = Object.assign({
  9753. // Necessary since the default button type is "submit"
  9754. type: 'button'
  9755. }, attributes);
  9756. const el = createEl(tag, props, attributes);
  9757. el.appendChild(createEl('span', {
  9758. className: 'vjs-icon-placeholder'
  9759. }, {
  9760. 'aria-hidden': true
  9761. }));
  9762. this.createControlTextEl(el);
  9763. return el;
  9764. }
  9765. /**
  9766. * Add a child `Component` inside of this `Button`.
  9767. *
  9768. * @param {string|Component} child
  9769. * The name or instance of a child to add.
  9770. *
  9771. * @param {Object} [options={}]
  9772. * The key/value store of options that will get passed to children of
  9773. * the child.
  9774. *
  9775. * @return {Component}
  9776. * The `Component` that gets added as a child. When using a string the
  9777. * `Component` will get created by this process.
  9778. *
  9779. * @deprecated since version 5
  9780. */
  9781. addChild(child, options = {}) {
  9782. const className = this.constructor.name;
  9783. log$1.warn(`Adding an actionable (user controllable) child to a Button (${className}) is not supported; use a ClickableComponent instead.`);
  9784. // Avoid the error message generated by ClickableComponent's addChild method
  9785. return Component$1.prototype.addChild.call(this, child, options);
  9786. }
  9787. /**
  9788. * Enable the `Button` element so that it can be activated or clicked. Use this with
  9789. * {@link Button#disable}.
  9790. */
  9791. enable() {
  9792. super.enable();
  9793. this.el_.removeAttribute('disabled');
  9794. }
  9795. /**
  9796. * Disable the `Button` element so that it cannot be activated or clicked. Use this with
  9797. * {@link Button#enable}.
  9798. */
  9799. disable() {
  9800. super.disable();
  9801. this.el_.setAttribute('disabled', 'disabled');
  9802. }
  9803. /**
  9804. * This gets called when a `Button` has focus and `keydown` is triggered via a key
  9805. * press.
  9806. *
  9807. * @param {Event} event
  9808. * The event that caused this function to get called.
  9809. *
  9810. * @listens keydown
  9811. */
  9812. handleKeyDown(event) {
  9813. // Ignore Space or Enter key operation, which is handled by the browser for
  9814. // a button - though not for its super class, ClickableComponent. Also,
  9815. // prevent the event from propagating through the DOM and triggering Player
  9816. // hotkeys. We do not preventDefault here because we _want_ the browser to
  9817. // handle it.
  9818. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  9819. event.stopPropagation();
  9820. return;
  9821. }
  9822. // Pass keypress handling up for unsupported keys
  9823. super.handleKeyDown(event);
  9824. }
  9825. }
  9826. Component$1.registerComponent('Button', Button);
  9827. /**
  9828. * @file big-play-button.js
  9829. */
  9830. /**
  9831. * The initial play button that shows before the video has played. The hiding of the
  9832. * `BigPlayButton` get done via CSS and `Player` states.
  9833. *
  9834. * @extends Button
  9835. */
  9836. class BigPlayButton extends Button {
  9837. constructor(player, options) {
  9838. super(player, options);
  9839. this.mouseused_ = false;
  9840. this.on('mousedown', e => this.handleMouseDown(e));
  9841. }
  9842. /**
  9843. * Builds the default DOM `className`.
  9844. *
  9845. * @return {string}
  9846. * The DOM `className` for this object. Always returns 'vjs-big-play-button'.
  9847. */
  9848. buildCSSClass() {
  9849. return 'vjs-big-play-button';
  9850. }
  9851. /**
  9852. * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent}
  9853. * for more detailed information on what a click can be.
  9854. *
  9855. * @param {KeyboardEvent} event
  9856. * The `keydown`, `tap`, or `click` event that caused this function to be
  9857. * called.
  9858. *
  9859. * @listens tap
  9860. * @listens click
  9861. */
  9862. handleClick(event) {
  9863. const playPromise = this.player_.play();
  9864. // exit early if clicked via the mouse
  9865. if (this.mouseused_ && event.clientX && event.clientY) {
  9866. silencePromise(playPromise);
  9867. if (this.player_.tech(true)) {
  9868. this.player_.tech(true).focus();
  9869. }
  9870. return;
  9871. }
  9872. const cb = this.player_.getChild('controlBar');
  9873. const playToggle = cb && cb.getChild('playToggle');
  9874. if (!playToggle) {
  9875. this.player_.tech(true).focus();
  9876. return;
  9877. }
  9878. const playFocus = () => playToggle.focus();
  9879. if (isPromise(playPromise)) {
  9880. playPromise.then(playFocus, () => {});
  9881. } else {
  9882. this.setTimeout(playFocus, 1);
  9883. }
  9884. }
  9885. handleKeyDown(event) {
  9886. this.mouseused_ = false;
  9887. super.handleKeyDown(event);
  9888. }
  9889. handleMouseDown(event) {
  9890. this.mouseused_ = true;
  9891. }
  9892. }
  9893. /**
  9894. * The text that should display over the `BigPlayButton`s controls. Added to for localization.
  9895. *
  9896. * @type {string}
  9897. * @protected
  9898. */
  9899. BigPlayButton.prototype.controlText_ = 'Play Video';
  9900. Component$1.registerComponent('BigPlayButton', BigPlayButton);
  9901. /**
  9902. * @file close-button.js
  9903. */
  9904. /**
  9905. * The `CloseButton` is a `{@link Button}` that fires a `close` event when
  9906. * it gets clicked.
  9907. *
  9908. * @extends Button
  9909. */
  9910. class CloseButton extends Button {
  9911. /**
  9912. * Creates an instance of the this class.
  9913. *
  9914. * @param { import('./player').default } player
  9915. * The `Player` that this class should be attached to.
  9916. *
  9917. * @param {Object} [options]
  9918. * The key/value store of player options.
  9919. */
  9920. constructor(player, options) {
  9921. super(player, options);
  9922. this.controlText(options && options.controlText || this.localize('Close'));
  9923. }
  9924. /**
  9925. * Builds the default DOM `className`.
  9926. *
  9927. * @return {string}
  9928. * The DOM `className` for this object.
  9929. */
  9930. buildCSSClass() {
  9931. return `vjs-close-button ${super.buildCSSClass()}`;
  9932. }
  9933. /**
  9934. * This gets called when a `CloseButton` gets clicked. See
  9935. * {@link ClickableComponent#handleClick} for more information on when
  9936. * this will be triggered
  9937. *
  9938. * @param {Event} event
  9939. * The `keydown`, `tap`, or `click` event that caused this function to be
  9940. * called.
  9941. *
  9942. * @listens tap
  9943. * @listens click
  9944. * @fires CloseButton#close
  9945. */
  9946. handleClick(event) {
  9947. /**
  9948. * Triggered when the a `CloseButton` is clicked.
  9949. *
  9950. * @event CloseButton#close
  9951. * @type {Event}
  9952. *
  9953. * @property {boolean} [bubbles=false]
  9954. * set to false so that the close event does not
  9955. * bubble up to parents if there is no listener
  9956. */
  9957. this.trigger({
  9958. type: 'close',
  9959. bubbles: false
  9960. });
  9961. }
  9962. /**
  9963. * Event handler that is called when a `CloseButton` receives a
  9964. * `keydown` event.
  9965. *
  9966. * By default, if the key is Esc, it will trigger a `click` event.
  9967. *
  9968. * @param {Event} event
  9969. * The `keydown` event that caused this function to be called.
  9970. *
  9971. * @listens keydown
  9972. */
  9973. handleKeyDown(event) {
  9974. // Esc button will trigger `click` event
  9975. if (keycode.isEventKey(event, 'Esc')) {
  9976. event.preventDefault();
  9977. event.stopPropagation();
  9978. this.trigger('click');
  9979. } else {
  9980. // Pass keypress handling up for unsupported keys
  9981. super.handleKeyDown(event);
  9982. }
  9983. }
  9984. }
  9985. Component$1.registerComponent('CloseButton', CloseButton);
  9986. /**
  9987. * @file play-toggle.js
  9988. */
  9989. /**
  9990. * Button to toggle between play and pause.
  9991. *
  9992. * @extends Button
  9993. */
  9994. class PlayToggle extends Button {
  9995. /**
  9996. * Creates an instance of this class.
  9997. *
  9998. * @param { import('./player').default } player
  9999. * The `Player` that this class should be attached to.
  10000. *
  10001. * @param {Object} [options={}]
  10002. * The key/value store of player options.
  10003. */
  10004. constructor(player, options = {}) {
  10005. super(player, options);
  10006. // show or hide replay icon
  10007. options.replay = options.replay === undefined || options.replay;
  10008. this.on(player, 'play', e => this.handlePlay(e));
  10009. this.on(player, 'pause', e => this.handlePause(e));
  10010. if (options.replay) {
  10011. this.on(player, 'ended', e => this.handleEnded(e));
  10012. }
  10013. }
  10014. /**
  10015. * Builds the default DOM `className`.
  10016. *
  10017. * @return {string}
  10018. * The DOM `className` for this object.
  10019. */
  10020. buildCSSClass() {
  10021. return `vjs-play-control ${super.buildCSSClass()}`;
  10022. }
  10023. /**
  10024. * This gets called when an `PlayToggle` is "clicked". See
  10025. * {@link ClickableComponent} for more detailed information on what a click can be.
  10026. *
  10027. * @param {Event} [event]
  10028. * The `keydown`, `tap`, or `click` event that caused this function to be
  10029. * called.
  10030. *
  10031. * @listens tap
  10032. * @listens click
  10033. */
  10034. handleClick(event) {
  10035. if (this.player_.paused()) {
  10036. silencePromise(this.player_.play());
  10037. } else {
  10038. this.player_.pause();
  10039. }
  10040. }
  10041. /**
  10042. * This gets called once after the video has ended and the user seeks so that
  10043. * we can change the replay button back to a play button.
  10044. *
  10045. * @param {Event} [event]
  10046. * The event that caused this function to run.
  10047. *
  10048. * @listens Player#seeked
  10049. */
  10050. handleSeeked(event) {
  10051. this.removeClass('vjs-ended');
  10052. if (this.player_.paused()) {
  10053. this.handlePause(event);
  10054. } else {
  10055. this.handlePlay(event);
  10056. }
  10057. }
  10058. /**
  10059. * Add the vjs-playing class to the element so it can change appearance.
  10060. *
  10061. * @param {Event} [event]
  10062. * The event that caused this function to run.
  10063. *
  10064. * @listens Player#play
  10065. */
  10066. handlePlay(event) {
  10067. this.removeClass('vjs-ended', 'vjs-paused');
  10068. this.addClass('vjs-playing');
  10069. // change the button text to "Pause"
  10070. this.controlText('Pause');
  10071. }
  10072. /**
  10073. * Add the vjs-paused class to the element so it can change appearance.
  10074. *
  10075. * @param {Event} [event]
  10076. * The event that caused this function to run.
  10077. *
  10078. * @listens Player#pause
  10079. */
  10080. handlePause(event) {
  10081. this.removeClass('vjs-playing');
  10082. this.addClass('vjs-paused');
  10083. // change the button text to "Play"
  10084. this.controlText('Play');
  10085. }
  10086. /**
  10087. * Add the vjs-ended class to the element so it can change appearance
  10088. *
  10089. * @param {Event} [event]
  10090. * The event that caused this function to run.
  10091. *
  10092. * @listens Player#ended
  10093. */
  10094. handleEnded(event) {
  10095. this.removeClass('vjs-playing');
  10096. this.addClass('vjs-ended');
  10097. // change the button text to "Replay"
  10098. this.controlText('Replay');
  10099. // on the next seek remove the replay button
  10100. this.one(this.player_, 'seeked', e => this.handleSeeked(e));
  10101. }
  10102. }
  10103. /**
  10104. * The text that should display over the `PlayToggle`s controls. Added for localization.
  10105. *
  10106. * @type {string}
  10107. * @protected
  10108. */
  10109. PlayToggle.prototype.controlText_ = 'Play';
  10110. Component$1.registerComponent('PlayToggle', PlayToggle);
  10111. /**
  10112. * @file time-display.js
  10113. */
  10114. /**
  10115. * Displays time information about the video
  10116. *
  10117. * @extends Component
  10118. */
  10119. class TimeDisplay extends Component$1 {
  10120. /**
  10121. * Creates an instance of this class.
  10122. *
  10123. * @param { import('../../player').default } player
  10124. * The `Player` that this class should be attached to.
  10125. *
  10126. * @param {Object} [options]
  10127. * The key/value store of player options.
  10128. */
  10129. constructor(player, options) {
  10130. super(player, options);
  10131. this.on(player, ['timeupdate', 'ended'], e => this.updateContent(e));
  10132. this.updateTextNode_();
  10133. }
  10134. /**
  10135. * Create the `Component`'s DOM element
  10136. *
  10137. * @return {Element}
  10138. * The element that was created.
  10139. */
  10140. createEl() {
  10141. const className = this.buildCSSClass();
  10142. const el = super.createEl('div', {
  10143. className: `${className} vjs-time-control vjs-control`
  10144. });
  10145. const span = createEl('span', {
  10146. className: 'vjs-control-text',
  10147. textContent: `${this.localize(this.labelText_)}\u00a0`
  10148. }, {
  10149. role: 'presentation'
  10150. });
  10151. el.appendChild(span);
  10152. this.contentEl_ = createEl('span', {
  10153. className: `${className}-display`
  10154. }, {
  10155. // span elements have no implicit role, but some screen readers (notably VoiceOver)
  10156. // treat them as a break between items in the DOM when using arrow keys
  10157. // (or left-to-right swipes on iOS) to read contents of a page. Using
  10158. // role='presentation' causes VoiceOver to NOT treat this span as a break.
  10159. role: 'presentation'
  10160. });
  10161. el.appendChild(this.contentEl_);
  10162. return el;
  10163. }
  10164. dispose() {
  10165. this.contentEl_ = null;
  10166. this.textNode_ = null;
  10167. super.dispose();
  10168. }
  10169. /**
  10170. * Updates the time display text node with a new time
  10171. *
  10172. * @param {number} [time=0] the time to update to
  10173. *
  10174. * @private
  10175. */
  10176. updateTextNode_(time = 0) {
  10177. time = formatTime(time);
  10178. if (this.formattedTime_ === time) {
  10179. return;
  10180. }
  10181. this.formattedTime_ = time;
  10182. this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_', () => {
  10183. if (!this.contentEl_) {
  10184. return;
  10185. }
  10186. let oldNode = this.textNode_;
  10187. if (oldNode && this.contentEl_.firstChild !== oldNode) {
  10188. oldNode = null;
  10189. 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.');
  10190. }
  10191. this.textNode_ = document.createTextNode(this.formattedTime_);
  10192. if (!this.textNode_) {
  10193. return;
  10194. }
  10195. if (oldNode) {
  10196. this.contentEl_.replaceChild(this.textNode_, oldNode);
  10197. } else {
  10198. this.contentEl_.appendChild(this.textNode_);
  10199. }
  10200. });
  10201. }
  10202. /**
  10203. * To be filled out in the child class, should update the displayed time
  10204. * in accordance with the fact that the current time has changed.
  10205. *
  10206. * @param {Event} [event]
  10207. * The `timeupdate` event that caused this to run.
  10208. *
  10209. * @listens Player#timeupdate
  10210. */
  10211. updateContent(event) {}
  10212. }
  10213. /**
  10214. * The text that is added to the `TimeDisplay` for screen reader users.
  10215. *
  10216. * @type {string}
  10217. * @private
  10218. */
  10219. TimeDisplay.prototype.labelText_ = 'Time';
  10220. /**
  10221. * The text that should display over the `TimeDisplay`s controls. Added to for localization.
  10222. *
  10223. * @type {string}
  10224. * @protected
  10225. *
  10226. * @deprecated in v7; controlText_ is not used in non-active display Components
  10227. */
  10228. TimeDisplay.prototype.controlText_ = 'Time';
  10229. Component$1.registerComponent('TimeDisplay', TimeDisplay);
  10230. /**
  10231. * @file current-time-display.js
  10232. */
  10233. /**
  10234. * Displays the current time
  10235. *
  10236. * @extends Component
  10237. */
  10238. class CurrentTimeDisplay extends TimeDisplay {
  10239. /**
  10240. * Builds the default DOM `className`.
  10241. *
  10242. * @return {string}
  10243. * The DOM `className` for this object.
  10244. */
  10245. buildCSSClass() {
  10246. return 'vjs-current-time';
  10247. }
  10248. /**
  10249. * Update current time display
  10250. *
  10251. * @param {Event} [event]
  10252. * The `timeupdate` event that caused this function to run.
  10253. *
  10254. * @listens Player#timeupdate
  10255. */
  10256. updateContent(event) {
  10257. // Allows for smooth scrubbing, when player can't keep up.
  10258. let time;
  10259. if (this.player_.ended()) {
  10260. time = this.player_.duration();
  10261. } else {
  10262. time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  10263. }
  10264. this.updateTextNode_(time);
  10265. }
  10266. }
  10267. /**
  10268. * The text that is added to the `CurrentTimeDisplay` for screen reader users.
  10269. *
  10270. * @type {string}
  10271. * @private
  10272. */
  10273. CurrentTimeDisplay.prototype.labelText_ = 'Current Time';
  10274. /**
  10275. * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
  10276. *
  10277. * @type {string}
  10278. * @protected
  10279. *
  10280. * @deprecated in v7; controlText_ is not used in non-active display Components
  10281. */
  10282. CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
  10283. Component$1.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
  10284. /**
  10285. * @file duration-display.js
  10286. */
  10287. /**
  10288. * Displays the duration
  10289. *
  10290. * @extends Component
  10291. */
  10292. class DurationDisplay extends TimeDisplay {
  10293. /**
  10294. * Creates an instance of this class.
  10295. *
  10296. * @param { import('../../player').default } player
  10297. * The `Player` that this class should be attached to.
  10298. *
  10299. * @param {Object} [options]
  10300. * The key/value store of player options.
  10301. */
  10302. constructor(player, options) {
  10303. super(player, options);
  10304. const updateContent = e => this.updateContent(e);
  10305. // we do not want to/need to throttle duration changes,
  10306. // as they should always display the changed duration as
  10307. // it has changed
  10308. this.on(player, 'durationchange', updateContent);
  10309. // Listen to loadstart because the player duration is reset when a new media element is loaded,
  10310. // but the durationchange on the user agent will not fire.
  10311. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  10312. this.on(player, 'loadstart', updateContent);
  10313. // Also listen for timeupdate (in the parent) and loadedmetadata because removing those
  10314. // listeners could have broken dependent applications/libraries. These
  10315. // can likely be removed for 7.0.
  10316. this.on(player, 'loadedmetadata', updateContent);
  10317. }
  10318. /**
  10319. * Builds the default DOM `className`.
  10320. *
  10321. * @return {string}
  10322. * The DOM `className` for this object.
  10323. */
  10324. buildCSSClass() {
  10325. return 'vjs-duration';
  10326. }
  10327. /**
  10328. * Update duration time display.
  10329. *
  10330. * @param {Event} [event]
  10331. * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
  10332. * this function to be called.
  10333. *
  10334. * @listens Player#durationchange
  10335. * @listens Player#timeupdate
  10336. * @listens Player#loadedmetadata
  10337. */
  10338. updateContent(event) {
  10339. const duration = this.player_.duration();
  10340. this.updateTextNode_(duration);
  10341. }
  10342. }
  10343. /**
  10344. * The text that is added to the `DurationDisplay` for screen reader users.
  10345. *
  10346. * @type {string}
  10347. * @private
  10348. */
  10349. DurationDisplay.prototype.labelText_ = 'Duration';
  10350. /**
  10351. * The text that should display over the `DurationDisplay`s controls. Added to for localization.
  10352. *
  10353. * @type {string}
  10354. * @protected
  10355. *
  10356. * @deprecated in v7; controlText_ is not used in non-active display Components
  10357. */
  10358. DurationDisplay.prototype.controlText_ = 'Duration';
  10359. Component$1.registerComponent('DurationDisplay', DurationDisplay);
  10360. /**
  10361. * @file time-divider.js
  10362. */
  10363. /**
  10364. * The separator between the current time and duration.
  10365. * Can be hidden if it's not needed in the design.
  10366. *
  10367. * @extends Component
  10368. */
  10369. class TimeDivider extends Component$1 {
  10370. /**
  10371. * Create the component's DOM element
  10372. *
  10373. * @return {Element}
  10374. * The element that was created.
  10375. */
  10376. createEl() {
  10377. const el = super.createEl('div', {
  10378. className: 'vjs-time-control vjs-time-divider'
  10379. }, {
  10380. // this element and its contents can be hidden from assistive techs since
  10381. // it is made extraneous by the announcement of the control text
  10382. // for the current time and duration displays
  10383. 'aria-hidden': true
  10384. });
  10385. const div = super.createEl('div');
  10386. const span = super.createEl('span', {
  10387. textContent: '/'
  10388. });
  10389. div.appendChild(span);
  10390. el.appendChild(div);
  10391. return el;
  10392. }
  10393. }
  10394. Component$1.registerComponent('TimeDivider', TimeDivider);
  10395. /**
  10396. * @file remaining-time-display.js
  10397. */
  10398. /**
  10399. * Displays the time left in the video
  10400. *
  10401. * @extends Component
  10402. */
  10403. class RemainingTimeDisplay extends TimeDisplay {
  10404. /**
  10405. * Creates an instance of this class.
  10406. *
  10407. * @param { import('../../player').default } player
  10408. * The `Player` that this class should be attached to.
  10409. *
  10410. * @param {Object} [options]
  10411. * The key/value store of player options.
  10412. */
  10413. constructor(player, options) {
  10414. super(player, options);
  10415. this.on(player, 'durationchange', e => this.updateContent(e));
  10416. }
  10417. /**
  10418. * Builds the default DOM `className`.
  10419. *
  10420. * @return {string}
  10421. * The DOM `className` for this object.
  10422. */
  10423. buildCSSClass() {
  10424. return 'vjs-remaining-time';
  10425. }
  10426. /**
  10427. * Create the `Component`'s DOM element with the "minus" character prepend to the time
  10428. *
  10429. * @return {Element}
  10430. * The element that was created.
  10431. */
  10432. createEl() {
  10433. const el = super.createEl();
  10434. if (this.options_.displayNegative !== false) {
  10435. el.insertBefore(createEl('span', {}, {
  10436. 'aria-hidden': true
  10437. }, '-'), this.contentEl_);
  10438. }
  10439. return el;
  10440. }
  10441. /**
  10442. * Update remaining time display.
  10443. *
  10444. * @param {Event} [event]
  10445. * The `timeupdate` or `durationchange` event that caused this to run.
  10446. *
  10447. * @listens Player#timeupdate
  10448. * @listens Player#durationchange
  10449. */
  10450. updateContent(event) {
  10451. if (typeof this.player_.duration() !== 'number') {
  10452. return;
  10453. }
  10454. let time;
  10455. // @deprecated We should only use remainingTimeDisplay
  10456. // as of video.js 7
  10457. if (this.player_.ended()) {
  10458. time = 0;
  10459. } else if (this.player_.remainingTimeDisplay) {
  10460. time = this.player_.remainingTimeDisplay();
  10461. } else {
  10462. time = this.player_.remainingTime();
  10463. }
  10464. this.updateTextNode_(time);
  10465. }
  10466. }
  10467. /**
  10468. * The text that is added to the `RemainingTimeDisplay` for screen reader users.
  10469. *
  10470. * @type {string}
  10471. * @private
  10472. */
  10473. RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';
  10474. /**
  10475. * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
  10476. *
  10477. * @type {string}
  10478. * @protected
  10479. *
  10480. * @deprecated in v7; controlText_ is not used in non-active display Components
  10481. */
  10482. RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
  10483. Component$1.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
  10484. /**
  10485. * @file live-display.js
  10486. */
  10487. // TODO - Future make it click to snap to live
  10488. /**
  10489. * Displays the live indicator when duration is Infinity.
  10490. *
  10491. * @extends Component
  10492. */
  10493. class LiveDisplay extends Component$1 {
  10494. /**
  10495. * Creates an instance of this class.
  10496. *
  10497. * @param { import('./player').default } player
  10498. * The `Player` that this class should be attached to.
  10499. *
  10500. * @param {Object} [options]
  10501. * The key/value store of player options.
  10502. */
  10503. constructor(player, options) {
  10504. super(player, options);
  10505. this.updateShowing();
  10506. this.on(this.player(), 'durationchange', e => this.updateShowing(e));
  10507. }
  10508. /**
  10509. * Create the `Component`'s DOM element
  10510. *
  10511. * @return {Element}
  10512. * The element that was created.
  10513. */
  10514. createEl() {
  10515. const el = super.createEl('div', {
  10516. className: 'vjs-live-control vjs-control'
  10517. });
  10518. this.contentEl_ = createEl('div', {
  10519. className: 'vjs-live-display'
  10520. }, {
  10521. 'aria-live': 'off'
  10522. });
  10523. this.contentEl_.appendChild(createEl('span', {
  10524. className: 'vjs-control-text',
  10525. textContent: `${this.localize('Stream Type')}\u00a0`
  10526. }));
  10527. this.contentEl_.appendChild(document.createTextNode(this.localize('LIVE')));
  10528. el.appendChild(this.contentEl_);
  10529. return el;
  10530. }
  10531. dispose() {
  10532. this.contentEl_ = null;
  10533. super.dispose();
  10534. }
  10535. /**
  10536. * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide
  10537. * it accordingly
  10538. *
  10539. * @param {Event} [event]
  10540. * The {@link Player#durationchange} event that caused this function to run.
  10541. *
  10542. * @listens Player#durationchange
  10543. */
  10544. updateShowing(event) {
  10545. if (this.player().duration() === Infinity) {
  10546. this.show();
  10547. } else {
  10548. this.hide();
  10549. }
  10550. }
  10551. }
  10552. Component$1.registerComponent('LiveDisplay', LiveDisplay);
  10553. /**
  10554. * @file seek-to-live.js
  10555. */
  10556. /**
  10557. * Displays the live indicator when duration is Infinity.
  10558. *
  10559. * @extends Component
  10560. */
  10561. class SeekToLive extends Button {
  10562. /**
  10563. * Creates an instance of this class.
  10564. *
  10565. * @param { import('./player').default } player
  10566. * The `Player` that this class should be attached to.
  10567. *
  10568. * @param {Object} [options]
  10569. * The key/value store of player options.
  10570. */
  10571. constructor(player, options) {
  10572. super(player, options);
  10573. this.updateLiveEdgeStatus();
  10574. if (this.player_.liveTracker) {
  10575. this.updateLiveEdgeStatusHandler_ = e => this.updateLiveEdgeStatus(e);
  10576. this.on(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  10577. }
  10578. }
  10579. /**
  10580. * Create the `Component`'s DOM element
  10581. *
  10582. * @return {Element}
  10583. * The element that was created.
  10584. */
  10585. createEl() {
  10586. const el = super.createEl('button', {
  10587. className: 'vjs-seek-to-live-control vjs-control'
  10588. });
  10589. this.textEl_ = createEl('span', {
  10590. className: 'vjs-seek-to-live-text',
  10591. textContent: this.localize('LIVE')
  10592. }, {
  10593. 'aria-hidden': 'true'
  10594. });
  10595. el.appendChild(this.textEl_);
  10596. return el;
  10597. }
  10598. /**
  10599. * Update the state of this button if we are at the live edge
  10600. * or not
  10601. */
  10602. updateLiveEdgeStatus() {
  10603. // default to live edge
  10604. if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {
  10605. this.setAttribute('aria-disabled', true);
  10606. this.addClass('vjs-at-live-edge');
  10607. this.controlText('Seek to live, currently playing live');
  10608. } else {
  10609. this.setAttribute('aria-disabled', false);
  10610. this.removeClass('vjs-at-live-edge');
  10611. this.controlText('Seek to live, currently behind live');
  10612. }
  10613. }
  10614. /**
  10615. * On click bring us as near to the live point as possible.
  10616. * This requires that we wait for the next `live-seekable-change`
  10617. * event which will happen every segment length seconds.
  10618. */
  10619. handleClick() {
  10620. this.player_.liveTracker.seekToLiveEdge();
  10621. }
  10622. /**
  10623. * Dispose of the element and stop tracking
  10624. */
  10625. dispose() {
  10626. if (this.player_.liveTracker) {
  10627. this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  10628. }
  10629. this.textEl_ = null;
  10630. super.dispose();
  10631. }
  10632. }
  10633. /**
  10634. * The text that should display over the `SeekToLive`s control. Added for localization.
  10635. *
  10636. * @type {string}
  10637. * @protected
  10638. */
  10639. SeekToLive.prototype.controlText_ = 'Seek to live, currently playing live';
  10640. Component$1.registerComponent('SeekToLive', SeekToLive);
  10641. /**
  10642. * @file num.js
  10643. * @module num
  10644. */
  10645. /**
  10646. * Keep a number between a min and a max value
  10647. *
  10648. * @param {number} number
  10649. * The number to clamp
  10650. *
  10651. * @param {number} min
  10652. * The minimum value
  10653. * @param {number} max
  10654. * The maximum value
  10655. *
  10656. * @return {number}
  10657. * the clamped number
  10658. */
  10659. function clamp(number, min, max) {
  10660. number = Number(number);
  10661. return Math.min(max, Math.max(min, isNaN(number) ? min : number));
  10662. }
  10663. var Num = /*#__PURE__*/Object.freeze({
  10664. __proto__: null,
  10665. clamp: clamp
  10666. });
  10667. /**
  10668. * @file slider.js
  10669. */
  10670. /**
  10671. * The base functionality for a slider. Can be vertical or horizontal.
  10672. * For instance the volume bar or the seek bar on a video is a slider.
  10673. *
  10674. * @extends Component
  10675. */
  10676. class Slider extends Component$1 {
  10677. /**
  10678. * Create an instance of this class
  10679. *
  10680. * @param { import('../player').default } player
  10681. * The `Player` that this class should be attached to.
  10682. *
  10683. * @param {Object} [options]
  10684. * The key/value store of player options.
  10685. */
  10686. constructor(player, options) {
  10687. super(player, options);
  10688. this.handleMouseDown_ = e => this.handleMouseDown(e);
  10689. this.handleMouseUp_ = e => this.handleMouseUp(e);
  10690. this.handleKeyDown_ = e => this.handleKeyDown(e);
  10691. this.handleClick_ = e => this.handleClick(e);
  10692. this.handleMouseMove_ = e => this.handleMouseMove(e);
  10693. this.update_ = e => this.update(e);
  10694. // Set property names to bar to match with the child Slider class is looking for
  10695. this.bar = this.getChild(this.options_.barName);
  10696. // Set a horizontal or vertical class on the slider depending on the slider type
  10697. this.vertical(!!this.options_.vertical);
  10698. this.enable();
  10699. }
  10700. /**
  10701. * Are controls are currently enabled for this slider or not.
  10702. *
  10703. * @return {boolean}
  10704. * true if controls are enabled, false otherwise
  10705. */
  10706. enabled() {
  10707. return this.enabled_;
  10708. }
  10709. /**
  10710. * Enable controls for this slider if they are disabled
  10711. */
  10712. enable() {
  10713. if (this.enabled()) {
  10714. return;
  10715. }
  10716. this.on('mousedown', this.handleMouseDown_);
  10717. this.on('touchstart', this.handleMouseDown_);
  10718. this.on('keydown', this.handleKeyDown_);
  10719. this.on('click', this.handleClick_);
  10720. // TODO: deprecated, controlsvisible does not seem to be fired
  10721. this.on(this.player_, 'controlsvisible', this.update);
  10722. if (this.playerEvent) {
  10723. this.on(this.player_, this.playerEvent, this.update);
  10724. }
  10725. this.removeClass('disabled');
  10726. this.setAttribute('tabindex', 0);
  10727. this.enabled_ = true;
  10728. }
  10729. /**
  10730. * Disable controls for this slider if they are enabled
  10731. */
  10732. disable() {
  10733. if (!this.enabled()) {
  10734. return;
  10735. }
  10736. const doc = this.bar.el_.ownerDocument;
  10737. this.off('mousedown', this.handleMouseDown_);
  10738. this.off('touchstart', this.handleMouseDown_);
  10739. this.off('keydown', this.handleKeyDown_);
  10740. this.off('click', this.handleClick_);
  10741. this.off(this.player_, 'controlsvisible', this.update_);
  10742. this.off(doc, 'mousemove', this.handleMouseMove_);
  10743. this.off(doc, 'mouseup', this.handleMouseUp_);
  10744. this.off(doc, 'touchmove', this.handleMouseMove_);
  10745. this.off(doc, 'touchend', this.handleMouseUp_);
  10746. this.removeAttribute('tabindex');
  10747. this.addClass('disabled');
  10748. if (this.playerEvent) {
  10749. this.off(this.player_, this.playerEvent, this.update);
  10750. }
  10751. this.enabled_ = false;
  10752. }
  10753. /**
  10754. * Create the `Slider`s DOM element.
  10755. *
  10756. * @param {string} type
  10757. * Type of element to create.
  10758. *
  10759. * @param {Object} [props={}]
  10760. * List of properties in Object form.
  10761. *
  10762. * @param {Object} [attributes={}]
  10763. * list of attributes in Object form.
  10764. *
  10765. * @return {Element}
  10766. * The element that gets created.
  10767. */
  10768. createEl(type, props = {}, attributes = {}) {
  10769. // Add the slider element class to all sub classes
  10770. props.className = props.className + ' vjs-slider';
  10771. props = Object.assign({
  10772. tabIndex: 0
  10773. }, props);
  10774. attributes = Object.assign({
  10775. 'role': 'slider',
  10776. 'aria-valuenow': 0,
  10777. 'aria-valuemin': 0,
  10778. 'aria-valuemax': 100
  10779. }, attributes);
  10780. return super.createEl(type, props, attributes);
  10781. }
  10782. /**
  10783. * Handle `mousedown` or `touchstart` events on the `Slider`.
  10784. *
  10785. * @param {MouseEvent} event
  10786. * `mousedown` or `touchstart` event that triggered this function
  10787. *
  10788. * @listens mousedown
  10789. * @listens touchstart
  10790. * @fires Slider#slideractive
  10791. */
  10792. handleMouseDown(event) {
  10793. const doc = this.bar.el_.ownerDocument;
  10794. if (event.type === 'mousedown') {
  10795. event.preventDefault();
  10796. }
  10797. // Do not call preventDefault() on touchstart in Chrome
  10798. // to avoid console warnings. Use a 'touch-action: none' style
  10799. // instead to prevent unintended scrolling.
  10800. // https://developers.google.com/web/updates/2017/01/scrolling-intervention
  10801. if (event.type === 'touchstart' && !IS_CHROME) {
  10802. event.preventDefault();
  10803. }
  10804. blockTextSelection();
  10805. this.addClass('vjs-sliding');
  10806. /**
  10807. * Triggered when the slider is in an active state
  10808. *
  10809. * @event Slider#slideractive
  10810. * @type {MouseEvent}
  10811. */
  10812. this.trigger('slideractive');
  10813. this.on(doc, 'mousemove', this.handleMouseMove_);
  10814. this.on(doc, 'mouseup', this.handleMouseUp_);
  10815. this.on(doc, 'touchmove', this.handleMouseMove_);
  10816. this.on(doc, 'touchend', this.handleMouseUp_);
  10817. this.handleMouseMove(event, true);
  10818. }
  10819. /**
  10820. * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.
  10821. * The `mousemove` and `touchmove` events will only only trigger this function during
  10822. * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and
  10823. * {@link Slider#handleMouseUp}.
  10824. *
  10825. * @param {MouseEvent} event
  10826. * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
  10827. * this function
  10828. * @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.
  10829. *
  10830. * @listens mousemove
  10831. * @listens touchmove
  10832. */
  10833. handleMouseMove(event) {}
  10834. /**
  10835. * Handle `mouseup` or `touchend` events on the `Slider`.
  10836. *
  10837. * @param {MouseEvent} event
  10838. * `mouseup` or `touchend` event that triggered this function.
  10839. *
  10840. * @listens touchend
  10841. * @listens mouseup
  10842. * @fires Slider#sliderinactive
  10843. */
  10844. handleMouseUp(event) {
  10845. const doc = this.bar.el_.ownerDocument;
  10846. unblockTextSelection();
  10847. this.removeClass('vjs-sliding');
  10848. /**
  10849. * Triggered when the slider is no longer in an active state.
  10850. *
  10851. * @event Slider#sliderinactive
  10852. * @type {Event}
  10853. */
  10854. this.trigger('sliderinactive');
  10855. this.off(doc, 'mousemove', this.handleMouseMove_);
  10856. this.off(doc, 'mouseup', this.handleMouseUp_);
  10857. this.off(doc, 'touchmove', this.handleMouseMove_);
  10858. this.off(doc, 'touchend', this.handleMouseUp_);
  10859. this.update();
  10860. }
  10861. /**
  10862. * Update the progress bar of the `Slider`.
  10863. *
  10864. * @return {number}
  10865. * The percentage of progress the progress bar represents as a
  10866. * number from 0 to 1.
  10867. */
  10868. update() {
  10869. // In VolumeBar init we have a setTimeout for update that pops and update
  10870. // to the end of the execution stack. The player is destroyed before then
  10871. // update will cause an error
  10872. // If there's no bar...
  10873. if (!this.el_ || !this.bar) {
  10874. return;
  10875. }
  10876. // clamp progress between 0 and 1
  10877. // and only round to four decimal places, as we round to two below
  10878. const progress = this.getProgress();
  10879. if (progress === this.progress_) {
  10880. return progress;
  10881. }
  10882. this.progress_ = progress;
  10883. this.requestNamedAnimationFrame('Slider#update', () => {
  10884. // Set the new bar width or height
  10885. const sizeKey = this.vertical() ? 'height' : 'width';
  10886. // Convert to a percentage for css value
  10887. this.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + '%';
  10888. });
  10889. return progress;
  10890. }
  10891. /**
  10892. * Get the percentage of the bar that should be filled
  10893. * but clamped and rounded.
  10894. *
  10895. * @return {number}
  10896. * percentage filled that the slider is
  10897. */
  10898. getProgress() {
  10899. return Number(clamp(this.getPercent(), 0, 1).toFixed(4));
  10900. }
  10901. /**
  10902. * Calculate distance for slider
  10903. *
  10904. * @param {Event} event
  10905. * The event that caused this function to run.
  10906. *
  10907. * @return {number}
  10908. * The current position of the Slider.
  10909. * - position.x for vertical `Slider`s
  10910. * - position.y for horizontal `Slider`s
  10911. */
  10912. calculateDistance(event) {
  10913. const position = getPointerPosition(this.el_, event);
  10914. if (this.vertical()) {
  10915. return position.y;
  10916. }
  10917. return position.x;
  10918. }
  10919. /**
  10920. * Handle a `keydown` event on the `Slider`. Watches for left, right, up, and down
  10921. * arrow keys. This function will only be called when the slider has focus. See
  10922. * {@link Slider#handleFocus} and {@link Slider#handleBlur}.
  10923. *
  10924. * @param {KeyboardEvent} event
  10925. * the `keydown` event that caused this function to run.
  10926. *
  10927. * @listens keydown
  10928. */
  10929. handleKeyDown(event) {
  10930. // Left and Down Arrows
  10931. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  10932. event.preventDefault();
  10933. event.stopPropagation();
  10934. this.stepBack();
  10935. // Up and Right Arrows
  10936. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  10937. event.preventDefault();
  10938. event.stopPropagation();
  10939. this.stepForward();
  10940. } else {
  10941. // Pass keydown handling up for unsupported keys
  10942. super.handleKeyDown(event);
  10943. }
  10944. }
  10945. /**
  10946. * Listener for click events on slider, used to prevent clicks
  10947. * from bubbling up to parent elements like button menus.
  10948. *
  10949. * @param {Object} event
  10950. * Event that caused this object to run
  10951. */
  10952. handleClick(event) {
  10953. event.stopPropagation();
  10954. event.preventDefault();
  10955. }
  10956. /**
  10957. * Get/set if slider is horizontal for vertical
  10958. *
  10959. * @param {boolean} [bool]
  10960. * - true if slider is vertical,
  10961. * - false is horizontal
  10962. *
  10963. * @return {boolean}
  10964. * - true if slider is vertical, and getting
  10965. * - false if the slider is horizontal, and getting
  10966. */
  10967. vertical(bool) {
  10968. if (bool === undefined) {
  10969. return this.vertical_ || false;
  10970. }
  10971. this.vertical_ = !!bool;
  10972. if (this.vertical_) {
  10973. this.addClass('vjs-slider-vertical');
  10974. } else {
  10975. this.addClass('vjs-slider-horizontal');
  10976. }
  10977. }
  10978. }
  10979. Component$1.registerComponent('Slider', Slider);
  10980. /**
  10981. * @file load-progress-bar.js
  10982. */
  10983. // get the percent width of a time compared to the total end
  10984. const percentify = (time, end) => clamp(time / end * 100, 0, 100).toFixed(2) + '%';
  10985. /**
  10986. * Shows loading progress
  10987. *
  10988. * @extends Component
  10989. */
  10990. class LoadProgressBar extends Component$1 {
  10991. /**
  10992. * Creates an instance of this class.
  10993. *
  10994. * @param { import('../../player').default } player
  10995. * The `Player` that this class should be attached to.
  10996. *
  10997. * @param {Object} [options]
  10998. * The key/value store of player options.
  10999. */
  11000. constructor(player, options) {
  11001. super(player, options);
  11002. this.partEls_ = [];
  11003. this.on(player, 'progress', e => this.update(e));
  11004. }
  11005. /**
  11006. * Create the `Component`'s DOM element
  11007. *
  11008. * @return {Element}
  11009. * The element that was created.
  11010. */
  11011. createEl() {
  11012. const el = super.createEl('div', {
  11013. className: 'vjs-load-progress'
  11014. });
  11015. const wrapper = createEl('span', {
  11016. className: 'vjs-control-text'
  11017. });
  11018. const loadedText = createEl('span', {
  11019. textContent: this.localize('Loaded')
  11020. });
  11021. const separator = document.createTextNode(': ');
  11022. this.percentageEl_ = createEl('span', {
  11023. className: 'vjs-control-text-loaded-percentage',
  11024. textContent: '0%'
  11025. });
  11026. el.appendChild(wrapper);
  11027. wrapper.appendChild(loadedText);
  11028. wrapper.appendChild(separator);
  11029. wrapper.appendChild(this.percentageEl_);
  11030. return el;
  11031. }
  11032. dispose() {
  11033. this.partEls_ = null;
  11034. this.percentageEl_ = null;
  11035. super.dispose();
  11036. }
  11037. /**
  11038. * Update progress bar
  11039. *
  11040. * @param {Event} [event]
  11041. * The `progress` event that caused this function to run.
  11042. *
  11043. * @listens Player#progress
  11044. */
  11045. update(event) {
  11046. this.requestNamedAnimationFrame('LoadProgressBar#update', () => {
  11047. const liveTracker = this.player_.liveTracker;
  11048. const buffered = this.player_.buffered();
  11049. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  11050. const bufferedEnd = this.player_.bufferedEnd();
  11051. const children = this.partEls_;
  11052. const percent = percentify(bufferedEnd, duration);
  11053. if (this.percent_ !== percent) {
  11054. // update the width of the progress bar
  11055. this.el_.style.width = percent;
  11056. // update the control-text
  11057. textContent(this.percentageEl_, percent);
  11058. this.percent_ = percent;
  11059. }
  11060. // add child elements to represent the individual buffered time ranges
  11061. for (let i = 0; i < buffered.length; i++) {
  11062. const start = buffered.start(i);
  11063. const end = buffered.end(i);
  11064. let part = children[i];
  11065. if (!part) {
  11066. part = this.el_.appendChild(createEl());
  11067. children[i] = part;
  11068. }
  11069. // only update if changed
  11070. if (part.dataset.start === start && part.dataset.end === end) {
  11071. continue;
  11072. }
  11073. part.dataset.start = start;
  11074. part.dataset.end = end;
  11075. // set the percent based on the width of the progress bar (bufferedEnd)
  11076. part.style.left = percentify(start, bufferedEnd);
  11077. part.style.width = percentify(end - start, bufferedEnd);
  11078. }
  11079. // remove unused buffered range elements
  11080. for (let i = children.length; i > buffered.length; i--) {
  11081. this.el_.removeChild(children[i - 1]);
  11082. }
  11083. children.length = buffered.length;
  11084. });
  11085. }
  11086. }
  11087. Component$1.registerComponent('LoadProgressBar', LoadProgressBar);
  11088. /**
  11089. * @file time-tooltip.js
  11090. */
  11091. /**
  11092. * Time tooltips display a time above the progress bar.
  11093. *
  11094. * @extends Component
  11095. */
  11096. class TimeTooltip extends Component$1 {
  11097. /**
  11098. * Creates an instance of this class.
  11099. *
  11100. * @param { import('../../player').default } player
  11101. * The {@link Player} that this class should be attached to.
  11102. *
  11103. * @param {Object} [options]
  11104. * The key/value store of player options.
  11105. */
  11106. constructor(player, options) {
  11107. super(player, options);
  11108. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  11109. }
  11110. /**
  11111. * Create the time tooltip DOM element
  11112. *
  11113. * @return {Element}
  11114. * The element that was created.
  11115. */
  11116. createEl() {
  11117. return super.createEl('div', {
  11118. className: 'vjs-time-tooltip'
  11119. }, {
  11120. 'aria-hidden': 'true'
  11121. });
  11122. }
  11123. /**
  11124. * Updates the position of the time tooltip relative to the `SeekBar`.
  11125. *
  11126. * @param {Object} seekBarRect
  11127. * The `ClientRect` for the {@link SeekBar} element.
  11128. *
  11129. * @param {number} seekBarPoint
  11130. * A number from 0 to 1, representing a horizontal reference point
  11131. * from the left edge of the {@link SeekBar}
  11132. */
  11133. update(seekBarRect, seekBarPoint, content) {
  11134. const tooltipRect = findPosition(this.el_);
  11135. const playerRect = getBoundingClientRect(this.player_.el());
  11136. const seekBarPointPx = seekBarRect.width * seekBarPoint;
  11137. // do nothing if either rect isn't available
  11138. // for example, if the player isn't in the DOM for testing
  11139. if (!playerRect || !tooltipRect) {
  11140. return;
  11141. }
  11142. // This is the space left of the `seekBarPoint` available within the bounds
  11143. // of the player. We calculate any gap between the left edge of the player
  11144. // and the left edge of the `SeekBar` and add the number of pixels in the
  11145. // `SeekBar` before hitting the `seekBarPoint`
  11146. const spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx;
  11147. // This is the space right of the `seekBarPoint` available within the bounds
  11148. // of the player. We calculate the number of pixels from the `seekBarPoint`
  11149. // to the right edge of the `SeekBar` and add to that any gap between the
  11150. // right edge of the `SeekBar` and the player.
  11151. const spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right);
  11152. // This is the number of pixels by which the tooltip will need to be pulled
  11153. // further to the right to center it over the `seekBarPoint`.
  11154. let pullTooltipBy = tooltipRect.width / 2;
  11155. // Adjust the `pullTooltipBy` distance to the left or right depending on
  11156. // the results of the space calculations above.
  11157. if (spaceLeftOfPoint < pullTooltipBy) {
  11158. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  11159. } else if (spaceRightOfPoint < pullTooltipBy) {
  11160. pullTooltipBy = spaceRightOfPoint;
  11161. }
  11162. // Due to the imprecision of decimal/ratio based calculations and varying
  11163. // rounding behaviors, there are cases where the spacing adjustment is off
  11164. // by a pixel or two. This adds insurance to these calculations.
  11165. if (pullTooltipBy < 0) {
  11166. pullTooltipBy = 0;
  11167. } else if (pullTooltipBy > tooltipRect.width) {
  11168. pullTooltipBy = tooltipRect.width;
  11169. }
  11170. // prevent small width fluctuations within 0.4px from
  11171. // changing the value below.
  11172. // This really helps for live to prevent the play
  11173. // progress time tooltip from jittering
  11174. pullTooltipBy = Math.round(pullTooltipBy);
  11175. this.el_.style.right = `-${pullTooltipBy}px`;
  11176. this.write(content);
  11177. }
  11178. /**
  11179. * Write the time to the tooltip DOM element.
  11180. *
  11181. * @param {string} content
  11182. * The formatted time for the tooltip.
  11183. */
  11184. write(content) {
  11185. textContent(this.el_, content);
  11186. }
  11187. /**
  11188. * Updates the position of the time tooltip relative to the `SeekBar`.
  11189. *
  11190. * @param {Object} seekBarRect
  11191. * The `ClientRect` for the {@link SeekBar} element.
  11192. *
  11193. * @param {number} seekBarPoint
  11194. * A number from 0 to 1, representing a horizontal reference point
  11195. * from the left edge of the {@link SeekBar}
  11196. *
  11197. * @param {number} time
  11198. * The time to update the tooltip to, not used during live playback
  11199. *
  11200. * @param {Function} cb
  11201. * A function that will be called during the request animation frame
  11202. * for tooltips that need to do additional animations from the default
  11203. */
  11204. updateTime(seekBarRect, seekBarPoint, time, cb) {
  11205. this.requestNamedAnimationFrame('TimeTooltip#updateTime', () => {
  11206. let content;
  11207. const duration = this.player_.duration();
  11208. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  11209. const liveWindow = this.player_.liveTracker.liveWindow();
  11210. const secondsBehind = liveWindow - seekBarPoint * liveWindow;
  11211. content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow);
  11212. } else {
  11213. content = formatTime(time, duration);
  11214. }
  11215. this.update(seekBarRect, seekBarPoint, content);
  11216. if (cb) {
  11217. cb();
  11218. }
  11219. });
  11220. }
  11221. }
  11222. Component$1.registerComponent('TimeTooltip', TimeTooltip);
  11223. /**
  11224. * @file play-progress-bar.js
  11225. */
  11226. /**
  11227. * Used by {@link SeekBar} to display media playback progress as part of the
  11228. * {@link ProgressControl}.
  11229. *
  11230. * @extends Component
  11231. */
  11232. class PlayProgressBar extends Component$1 {
  11233. /**
  11234. * Creates an instance of this class.
  11235. *
  11236. * @param { import('../../player').default } player
  11237. * The {@link Player} that this class should be attached to.
  11238. *
  11239. * @param {Object} [options]
  11240. * The key/value store of player options.
  11241. */
  11242. constructor(player, options) {
  11243. super(player, options);
  11244. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  11245. }
  11246. /**
  11247. * Create the the DOM element for this class.
  11248. *
  11249. * @return {Element}
  11250. * The element that was created.
  11251. */
  11252. createEl() {
  11253. return super.createEl('div', {
  11254. className: 'vjs-play-progress vjs-slider-bar'
  11255. }, {
  11256. 'aria-hidden': 'true'
  11257. });
  11258. }
  11259. /**
  11260. * Enqueues updates to its own DOM as well as the DOM of its
  11261. * {@link TimeTooltip} child.
  11262. *
  11263. * @param {Object} seekBarRect
  11264. * The `ClientRect` for the {@link SeekBar} element.
  11265. *
  11266. * @param {number} seekBarPoint
  11267. * A number from 0 to 1, representing a horizontal reference point
  11268. * from the left edge of the {@link SeekBar}
  11269. */
  11270. update(seekBarRect, seekBarPoint) {
  11271. const timeTooltip = this.getChild('timeTooltip');
  11272. if (!timeTooltip) {
  11273. return;
  11274. }
  11275. const time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  11276. timeTooltip.updateTime(seekBarRect, seekBarPoint, time);
  11277. }
  11278. }
  11279. /**
  11280. * Default options for {@link PlayProgressBar}.
  11281. *
  11282. * @type {Object}
  11283. * @private
  11284. */
  11285. PlayProgressBar.prototype.options_ = {
  11286. children: []
  11287. };
  11288. // Time tooltips should not be added to a player on mobile devices
  11289. if (!IS_IOS && !IS_ANDROID) {
  11290. PlayProgressBar.prototype.options_.children.push('timeTooltip');
  11291. }
  11292. Component$1.registerComponent('PlayProgressBar', PlayProgressBar);
  11293. /**
  11294. * @file mouse-time-display.js
  11295. */
  11296. /**
  11297. * The {@link MouseTimeDisplay} component tracks mouse movement over the
  11298. * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}
  11299. * indicating the time which is represented by a given point in the
  11300. * {@link ProgressControl}.
  11301. *
  11302. * @extends Component
  11303. */
  11304. class MouseTimeDisplay extends Component$1 {
  11305. /**
  11306. * Creates an instance of this class.
  11307. *
  11308. * @param { import('../../player').default } player
  11309. * The {@link Player} that this class should be attached to.
  11310. *
  11311. * @param {Object} [options]
  11312. * The key/value store of player options.
  11313. */
  11314. constructor(player, options) {
  11315. super(player, options);
  11316. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  11317. }
  11318. /**
  11319. * Create the DOM element for this class.
  11320. *
  11321. * @return {Element}
  11322. * The element that was created.
  11323. */
  11324. createEl() {
  11325. return super.createEl('div', {
  11326. className: 'vjs-mouse-display'
  11327. });
  11328. }
  11329. /**
  11330. * Enqueues updates to its own DOM as well as the DOM of its
  11331. * {@link TimeTooltip} child.
  11332. *
  11333. * @param {Object} seekBarRect
  11334. * The `ClientRect` for the {@link SeekBar} element.
  11335. *
  11336. * @param {number} seekBarPoint
  11337. * A number from 0 to 1, representing a horizontal reference point
  11338. * from the left edge of the {@link SeekBar}
  11339. */
  11340. update(seekBarRect, seekBarPoint) {
  11341. const time = seekBarPoint * this.player_.duration();
  11342. this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, () => {
  11343. this.el_.style.left = `${seekBarRect.width * seekBarPoint}px`;
  11344. });
  11345. }
  11346. }
  11347. /**
  11348. * Default options for `MouseTimeDisplay`
  11349. *
  11350. * @type {Object}
  11351. * @private
  11352. */
  11353. MouseTimeDisplay.prototype.options_ = {
  11354. children: ['timeTooltip']
  11355. };
  11356. Component$1.registerComponent('MouseTimeDisplay', MouseTimeDisplay);
  11357. /**
  11358. * @file seek-bar.js
  11359. */
  11360. // The number of seconds the `step*` functions move the timeline.
  11361. const STEP_SECONDS = 5;
  11362. // The multiplier of STEP_SECONDS that PgUp/PgDown move the timeline.
  11363. const PAGE_KEY_MULTIPLIER = 12;
  11364. /**
  11365. * Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
  11366. * as its `bar`.
  11367. *
  11368. * @extends Slider
  11369. */
  11370. class SeekBar extends Slider {
  11371. /**
  11372. * Creates an instance of this class.
  11373. *
  11374. * @param { import('../../player').default } player
  11375. * The `Player` that this class should be attached to.
  11376. *
  11377. * @param {Object} [options]
  11378. * The key/value store of player options.
  11379. */
  11380. constructor(player, options) {
  11381. super(player, options);
  11382. this.setEventHandlers_();
  11383. }
  11384. /**
  11385. * Sets the event handlers
  11386. *
  11387. * @private
  11388. */
  11389. setEventHandlers_() {
  11390. this.update_ = bind_(this, this.update);
  11391. this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);
  11392. this.on(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  11393. if (this.player_.liveTracker) {
  11394. this.on(this.player_.liveTracker, 'liveedgechange', this.update);
  11395. }
  11396. // when playing, let's ensure we smoothly update the play progress bar
  11397. // via an interval
  11398. this.updateInterval = null;
  11399. this.enableIntervalHandler_ = e => this.enableInterval_(e);
  11400. this.disableIntervalHandler_ = e => this.disableInterval_(e);
  11401. this.on(this.player_, ['playing'], this.enableIntervalHandler_);
  11402. this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  11403. // we don't need to update the play progress if the document is hidden,
  11404. // also, this causes the CPU to spike and eventually crash the page on IE11.
  11405. if ('hidden' in document && 'visibilityState' in document) {
  11406. this.on(document, 'visibilitychange', this.toggleVisibility_);
  11407. }
  11408. }
  11409. toggleVisibility_(e) {
  11410. if (document.visibilityState === 'hidden') {
  11411. this.cancelNamedAnimationFrame('SeekBar#update');
  11412. this.cancelNamedAnimationFrame('Slider#update');
  11413. this.disableInterval_(e);
  11414. } else {
  11415. if (!this.player_.ended() && !this.player_.paused()) {
  11416. this.enableInterval_();
  11417. }
  11418. // we just switched back to the page and someone may be looking, so, update ASAP
  11419. this.update();
  11420. }
  11421. }
  11422. enableInterval_() {
  11423. if (this.updateInterval) {
  11424. return;
  11425. }
  11426. this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);
  11427. }
  11428. disableInterval_(e) {
  11429. if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== 'ended') {
  11430. return;
  11431. }
  11432. if (!this.updateInterval) {
  11433. return;
  11434. }
  11435. this.clearInterval(this.updateInterval);
  11436. this.updateInterval = null;
  11437. }
  11438. /**
  11439. * Create the `Component`'s DOM element
  11440. *
  11441. * @return {Element}
  11442. * The element that was created.
  11443. */
  11444. createEl() {
  11445. return super.createEl('div', {
  11446. className: 'vjs-progress-holder'
  11447. }, {
  11448. 'aria-label': this.localize('Progress Bar')
  11449. });
  11450. }
  11451. /**
  11452. * This function updates the play progress bar and accessibility
  11453. * attributes to whatever is passed in.
  11454. *
  11455. * @param {Event} [event]
  11456. * The `timeupdate` or `ended` event that caused this to run.
  11457. *
  11458. * @listens Player#timeupdate
  11459. *
  11460. * @return {number}
  11461. * The current percent at a number from 0-1
  11462. */
  11463. update(event) {
  11464. // ignore updates while the tab is hidden
  11465. if (document.visibilityState === 'hidden') {
  11466. return;
  11467. }
  11468. const percent = super.update();
  11469. this.requestNamedAnimationFrame('SeekBar#update', () => {
  11470. const currentTime = this.player_.ended() ? this.player_.duration() : this.getCurrentTime_();
  11471. const liveTracker = this.player_.liveTracker;
  11472. let duration = this.player_.duration();
  11473. if (liveTracker && liveTracker.isLive()) {
  11474. duration = this.player_.liveTracker.liveCurrentTime();
  11475. }
  11476. if (this.percent_ !== percent) {
  11477. // machine readable value of progress bar (percentage complete)
  11478. this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
  11479. this.percent_ = percent;
  11480. }
  11481. if (this.currentTime_ !== currentTime || this.duration_ !== duration) {
  11482. // human readable value of progress bar (time complete)
  11483. this.el_.setAttribute('aria-valuetext', this.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));
  11484. this.currentTime_ = currentTime;
  11485. this.duration_ = duration;
  11486. }
  11487. // update the progress bar time tooltip with the current time
  11488. if (this.bar) {
  11489. this.bar.update(getBoundingClientRect(this.el()), this.getProgress());
  11490. }
  11491. });
  11492. return percent;
  11493. }
  11494. /**
  11495. * Prevent liveThreshold from causing seeks to seem like they
  11496. * are not happening from a user perspective.
  11497. *
  11498. * @param {number} ct
  11499. * current time to seek to
  11500. */
  11501. userSeek_(ct) {
  11502. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  11503. this.player_.liveTracker.nextSeekedFromUser();
  11504. }
  11505. this.player_.currentTime(ct);
  11506. }
  11507. /**
  11508. * Get the value of current time but allows for smooth scrubbing,
  11509. * when player can't keep up.
  11510. *
  11511. * @return {number}
  11512. * The current time value to display
  11513. *
  11514. * @private
  11515. */
  11516. getCurrentTime_() {
  11517. return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  11518. }
  11519. /**
  11520. * Get the percentage of media played so far.
  11521. *
  11522. * @return {number}
  11523. * The percentage of media played so far (0 to 1).
  11524. */
  11525. getPercent() {
  11526. const currentTime = this.getCurrentTime_();
  11527. let percent;
  11528. const liveTracker = this.player_.liveTracker;
  11529. if (liveTracker && liveTracker.isLive()) {
  11530. percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow();
  11531. // prevent the percent from changing at the live edge
  11532. if (liveTracker.atLiveEdge()) {
  11533. percent = 1;
  11534. }
  11535. } else {
  11536. percent = currentTime / this.player_.duration();
  11537. }
  11538. return percent;
  11539. }
  11540. /**
  11541. * Handle mouse down on seek bar
  11542. *
  11543. * @param {MouseEvent} event
  11544. * The `mousedown` event that caused this to run.
  11545. *
  11546. * @listens mousedown
  11547. */
  11548. handleMouseDown(event) {
  11549. if (!isSingleLeftClick(event)) {
  11550. return;
  11551. }
  11552. // Stop event propagation to prevent double fire in progress-control.js
  11553. event.stopPropagation();
  11554. this.videoWasPlaying = !this.player_.paused();
  11555. this.player_.pause();
  11556. super.handleMouseDown(event);
  11557. }
  11558. /**
  11559. * Handle mouse move on seek bar
  11560. *
  11561. * @param {MouseEvent} event
  11562. * The `mousemove` event that caused this to run.
  11563. * @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
  11564. *
  11565. * @listens mousemove
  11566. */
  11567. handleMouseMove(event, mouseDown = false) {
  11568. if (!isSingleLeftClick(event)) {
  11569. return;
  11570. }
  11571. if (!mouseDown && !this.player_.scrubbing()) {
  11572. this.player_.scrubbing(true);
  11573. }
  11574. let newTime;
  11575. const distance = this.calculateDistance(event);
  11576. const liveTracker = this.player_.liveTracker;
  11577. if (!liveTracker || !liveTracker.isLive()) {
  11578. newTime = distance * this.player_.duration();
  11579. // Don't let video end while scrubbing.
  11580. if (newTime === this.player_.duration()) {
  11581. newTime = newTime - 0.1;
  11582. }
  11583. } else {
  11584. if (distance >= 0.99) {
  11585. liveTracker.seekToLiveEdge();
  11586. return;
  11587. }
  11588. const seekableStart = liveTracker.seekableStart();
  11589. const seekableEnd = liveTracker.liveCurrentTime();
  11590. newTime = seekableStart + distance * liveTracker.liveWindow();
  11591. // Don't let video end while scrubbing.
  11592. if (newTime >= seekableEnd) {
  11593. newTime = seekableEnd;
  11594. }
  11595. // Compensate for precision differences so that currentTime is not less
  11596. // than seekable start
  11597. if (newTime <= seekableStart) {
  11598. newTime = seekableStart + 0.1;
  11599. }
  11600. // On android seekableEnd can be Infinity sometimes,
  11601. // this will cause newTime to be Infinity, which is
  11602. // not a valid currentTime.
  11603. if (newTime === Infinity) {
  11604. return;
  11605. }
  11606. }
  11607. // Set new time (tell player to seek to new time)
  11608. this.userSeek_(newTime);
  11609. }
  11610. enable() {
  11611. super.enable();
  11612. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  11613. if (!mouseTimeDisplay) {
  11614. return;
  11615. }
  11616. mouseTimeDisplay.show();
  11617. }
  11618. disable() {
  11619. super.disable();
  11620. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  11621. if (!mouseTimeDisplay) {
  11622. return;
  11623. }
  11624. mouseTimeDisplay.hide();
  11625. }
  11626. /**
  11627. * Handle mouse up on seek bar
  11628. *
  11629. * @param {MouseEvent} event
  11630. * The `mouseup` event that caused this to run.
  11631. *
  11632. * @listens mouseup
  11633. */
  11634. handleMouseUp(event) {
  11635. super.handleMouseUp(event);
  11636. // Stop event propagation to prevent double fire in progress-control.js
  11637. if (event) {
  11638. event.stopPropagation();
  11639. }
  11640. this.player_.scrubbing(false);
  11641. /**
  11642. * Trigger timeupdate because we're done seeking and the time has changed.
  11643. * This is particularly useful for if the player is paused to time the time displays.
  11644. *
  11645. * @event Tech#timeupdate
  11646. * @type {Event}
  11647. */
  11648. this.player_.trigger({
  11649. type: 'timeupdate',
  11650. target: this,
  11651. manuallyTriggered: true
  11652. });
  11653. if (this.videoWasPlaying) {
  11654. silencePromise(this.player_.play());
  11655. } else {
  11656. // We're done seeking and the time has changed.
  11657. // If the player is paused, make sure we display the correct time on the seek bar.
  11658. this.update_();
  11659. }
  11660. }
  11661. /**
  11662. * Move more quickly fast forward for keyboard-only users
  11663. */
  11664. stepForward() {
  11665. this.userSeek_(this.player_.currentTime() + STEP_SECONDS);
  11666. }
  11667. /**
  11668. * Move more quickly rewind for keyboard-only users
  11669. */
  11670. stepBack() {
  11671. this.userSeek_(this.player_.currentTime() - STEP_SECONDS);
  11672. }
  11673. /**
  11674. * Toggles the playback state of the player
  11675. * This gets called when enter or space is used on the seekbar
  11676. *
  11677. * @param {KeyboardEvent} event
  11678. * The `keydown` event that caused this function to be called
  11679. *
  11680. */
  11681. handleAction(event) {
  11682. if (this.player_.paused()) {
  11683. this.player_.play();
  11684. } else {
  11685. this.player_.pause();
  11686. }
  11687. }
  11688. /**
  11689. * Called when this SeekBar has focus and a key gets pressed down.
  11690. * Supports the following keys:
  11691. *
  11692. * Space or Enter key fire a click event
  11693. * Home key moves to start of the timeline
  11694. * End key moves to end of the timeline
  11695. * Digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline
  11696. * PageDown key moves back a larger step than ArrowDown
  11697. * PageUp key moves forward a large step
  11698. *
  11699. * @param {KeyboardEvent} event
  11700. * The `keydown` event that caused this function to be called.
  11701. *
  11702. * @listens keydown
  11703. */
  11704. handleKeyDown(event) {
  11705. const liveTracker = this.player_.liveTracker;
  11706. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  11707. event.preventDefault();
  11708. event.stopPropagation();
  11709. this.handleAction(event);
  11710. } else if (keycode.isEventKey(event, 'Home')) {
  11711. event.preventDefault();
  11712. event.stopPropagation();
  11713. this.userSeek_(0);
  11714. } else if (keycode.isEventKey(event, 'End')) {
  11715. event.preventDefault();
  11716. event.stopPropagation();
  11717. if (liveTracker && liveTracker.isLive()) {
  11718. this.userSeek_(liveTracker.liveCurrentTime());
  11719. } else {
  11720. this.userSeek_(this.player_.duration());
  11721. }
  11722. } else if (/^[0-9]$/.test(keycode(event))) {
  11723. event.preventDefault();
  11724. event.stopPropagation();
  11725. const gotoFraction = (keycode.codes[keycode(event)] - keycode.codes['0']) * 10.0 / 100.0;
  11726. if (liveTracker && liveTracker.isLive()) {
  11727. this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);
  11728. } else {
  11729. this.userSeek_(this.player_.duration() * gotoFraction);
  11730. }
  11731. } else if (keycode.isEventKey(event, 'PgDn')) {
  11732. event.preventDefault();
  11733. event.stopPropagation();
  11734. this.userSeek_(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  11735. } else if (keycode.isEventKey(event, 'PgUp')) {
  11736. event.preventDefault();
  11737. event.stopPropagation();
  11738. this.userSeek_(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  11739. } else {
  11740. // Pass keydown handling up for unsupported keys
  11741. super.handleKeyDown(event);
  11742. }
  11743. }
  11744. dispose() {
  11745. this.disableInterval_();
  11746. this.off(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  11747. if (this.player_.liveTracker) {
  11748. this.off(this.player_.liveTracker, 'liveedgechange', this.update);
  11749. }
  11750. this.off(this.player_, ['playing'], this.enableIntervalHandler_);
  11751. this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  11752. // we don't need to update the play progress if the document is hidden,
  11753. // also, this causes the CPU to spike and eventually crash the page on IE11.
  11754. if ('hidden' in document && 'visibilityState' in document) {
  11755. this.off(document, 'visibilitychange', this.toggleVisibility_);
  11756. }
  11757. super.dispose();
  11758. }
  11759. }
  11760. /**
  11761. * Default options for the `SeekBar`
  11762. *
  11763. * @type {Object}
  11764. * @private
  11765. */
  11766. SeekBar.prototype.options_ = {
  11767. children: ['loadProgressBar', 'playProgressBar'],
  11768. barName: 'playProgressBar'
  11769. };
  11770. // MouseTimeDisplay tooltips should not be added to a player on mobile devices
  11771. if (!IS_IOS && !IS_ANDROID) {
  11772. SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay');
  11773. }
  11774. Component$1.registerComponent('SeekBar', SeekBar);
  11775. /**
  11776. * @file progress-control.js
  11777. */
  11778. /**
  11779. * The Progress Control component contains the seek bar, load progress,
  11780. * and play progress.
  11781. *
  11782. * @extends Component
  11783. */
  11784. class ProgressControl extends Component$1 {
  11785. /**
  11786. * Creates an instance of this class.
  11787. *
  11788. * @param { import('../../player').default } player
  11789. * The `Player` that this class should be attached to.
  11790. *
  11791. * @param {Object} [options]
  11792. * The key/value store of player options.
  11793. */
  11794. constructor(player, options) {
  11795. super(player, options);
  11796. this.handleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  11797. this.throttledHandleMouseSeek = throttle(bind_(this, this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);
  11798. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  11799. this.handleMouseDownHandler_ = e => this.handleMouseDown(e);
  11800. this.enable();
  11801. }
  11802. /**
  11803. * Create the `Component`'s DOM element
  11804. *
  11805. * @return {Element}
  11806. * The element that was created.
  11807. */
  11808. createEl() {
  11809. return super.createEl('div', {
  11810. className: 'vjs-progress-control vjs-control'
  11811. });
  11812. }
  11813. /**
  11814. * When the mouse moves over the `ProgressControl`, the pointer position
  11815. * gets passed down to the `MouseTimeDisplay` component.
  11816. *
  11817. * @param {Event} event
  11818. * The `mousemove` event that caused this function to run.
  11819. *
  11820. * @listen mousemove
  11821. */
  11822. handleMouseMove(event) {
  11823. const seekBar = this.getChild('seekBar');
  11824. if (!seekBar) {
  11825. return;
  11826. }
  11827. const playProgressBar = seekBar.getChild('playProgressBar');
  11828. const mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');
  11829. if (!playProgressBar && !mouseTimeDisplay) {
  11830. return;
  11831. }
  11832. const seekBarEl = seekBar.el();
  11833. const seekBarRect = findPosition(seekBarEl);
  11834. let seekBarPoint = getPointerPosition(seekBarEl, event).x;
  11835. // The default skin has a gap on either side of the `SeekBar`. This means
  11836. // that it's possible to trigger this behavior outside the boundaries of
  11837. // the `SeekBar`. This ensures we stay within it at all times.
  11838. seekBarPoint = clamp(seekBarPoint, 0, 1);
  11839. if (mouseTimeDisplay) {
  11840. mouseTimeDisplay.update(seekBarRect, seekBarPoint);
  11841. }
  11842. if (playProgressBar) {
  11843. playProgressBar.update(seekBarRect, seekBar.getProgress());
  11844. }
  11845. }
  11846. /**
  11847. * A throttled version of the {@link ProgressControl#handleMouseSeek} listener.
  11848. *
  11849. * @method ProgressControl#throttledHandleMouseSeek
  11850. * @param {Event} event
  11851. * The `mousemove` event that caused this function to run.
  11852. *
  11853. * @listen mousemove
  11854. * @listen touchmove
  11855. */
  11856. /**
  11857. * Handle `mousemove` or `touchmove` events on the `ProgressControl`.
  11858. *
  11859. * @param {Event} event
  11860. * `mousedown` or `touchstart` event that triggered this function
  11861. *
  11862. * @listens mousemove
  11863. * @listens touchmove
  11864. */
  11865. handleMouseSeek(event) {
  11866. const seekBar = this.getChild('seekBar');
  11867. if (seekBar) {
  11868. seekBar.handleMouseMove(event);
  11869. }
  11870. }
  11871. /**
  11872. * Are controls are currently enabled for this progress control.
  11873. *
  11874. * @return {boolean}
  11875. * true if controls are enabled, false otherwise
  11876. */
  11877. enabled() {
  11878. return this.enabled_;
  11879. }
  11880. /**
  11881. * Disable all controls on the progress control and its children
  11882. */
  11883. disable() {
  11884. this.children().forEach(child => child.disable && child.disable());
  11885. if (!this.enabled()) {
  11886. return;
  11887. }
  11888. this.off(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  11889. this.off(this.el_, 'mousemove', this.handleMouseMove);
  11890. this.removeListenersAddedOnMousedownAndTouchstart();
  11891. this.addClass('disabled');
  11892. this.enabled_ = false;
  11893. // Restore normal playback state if controls are disabled while scrubbing
  11894. if (this.player_.scrubbing()) {
  11895. const seekBar = this.getChild('seekBar');
  11896. this.player_.scrubbing(false);
  11897. if (seekBar.videoWasPlaying) {
  11898. silencePromise(this.player_.play());
  11899. }
  11900. }
  11901. }
  11902. /**
  11903. * Enable all controls on the progress control and its children
  11904. */
  11905. enable() {
  11906. this.children().forEach(child => child.enable && child.enable());
  11907. if (this.enabled()) {
  11908. return;
  11909. }
  11910. this.on(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  11911. this.on(this.el_, 'mousemove', this.handleMouseMove);
  11912. this.removeClass('disabled');
  11913. this.enabled_ = true;
  11914. }
  11915. /**
  11916. * Cleanup listeners after the user finishes interacting with the progress controls
  11917. */
  11918. removeListenersAddedOnMousedownAndTouchstart() {
  11919. const doc = this.el_.ownerDocument;
  11920. this.off(doc, 'mousemove', this.throttledHandleMouseSeek);
  11921. this.off(doc, 'touchmove', this.throttledHandleMouseSeek);
  11922. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  11923. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  11924. }
  11925. /**
  11926. * Handle `mousedown` or `touchstart` events on the `ProgressControl`.
  11927. *
  11928. * @param {Event} event
  11929. * `mousedown` or `touchstart` event that triggered this function
  11930. *
  11931. * @listens mousedown
  11932. * @listens touchstart
  11933. */
  11934. handleMouseDown(event) {
  11935. const doc = this.el_.ownerDocument;
  11936. const seekBar = this.getChild('seekBar');
  11937. if (seekBar) {
  11938. seekBar.handleMouseDown(event);
  11939. }
  11940. this.on(doc, 'mousemove', this.throttledHandleMouseSeek);
  11941. this.on(doc, 'touchmove', this.throttledHandleMouseSeek);
  11942. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  11943. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  11944. }
  11945. /**
  11946. * Handle `mouseup` or `touchend` events on the `ProgressControl`.
  11947. *
  11948. * @param {Event} event
  11949. * `mouseup` or `touchend` event that triggered this function.
  11950. *
  11951. * @listens touchend
  11952. * @listens mouseup
  11953. */
  11954. handleMouseUp(event) {
  11955. const seekBar = this.getChild('seekBar');
  11956. if (seekBar) {
  11957. seekBar.handleMouseUp(event);
  11958. }
  11959. this.removeListenersAddedOnMousedownAndTouchstart();
  11960. }
  11961. }
  11962. /**
  11963. * Default options for `ProgressControl`
  11964. *
  11965. * @type {Object}
  11966. * @private
  11967. */
  11968. ProgressControl.prototype.options_ = {
  11969. children: ['seekBar']
  11970. };
  11971. Component$1.registerComponent('ProgressControl', ProgressControl);
  11972. /**
  11973. * @file picture-in-picture-toggle.js
  11974. */
  11975. /**
  11976. * Toggle Picture-in-Picture mode
  11977. *
  11978. * @extends Button
  11979. */
  11980. class PictureInPictureToggle extends Button {
  11981. /**
  11982. * Creates an instance of this class.
  11983. *
  11984. * @param { import('./player').default } player
  11985. * The `Player` that this class should be attached to.
  11986. *
  11987. * @param {Object} [options]
  11988. * The key/value store of player options.
  11989. *
  11990. * @listens Player#enterpictureinpicture
  11991. * @listens Player#leavepictureinpicture
  11992. */
  11993. constructor(player, options) {
  11994. super(player, options);
  11995. this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], e => this.handlePictureInPictureChange(e));
  11996. this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], e => this.handlePictureInPictureEnabledChange(e));
  11997. this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], () => {
  11998. // This audio detection will not detect HLS or DASH audio-only streams because there was no reliable way to detect them at the time
  11999. const isSourceAudio = player.currentType().substring(0, 5) === 'audio';
  12000. if (isSourceAudio || player.audioPosterMode() || player.audioOnlyMode()) {
  12001. if (player.isInPictureInPicture()) {
  12002. player.exitPictureInPicture();
  12003. }
  12004. this.hide();
  12005. } else {
  12006. this.show();
  12007. }
  12008. });
  12009. // TODO: Deactivate button on player emptied event.
  12010. this.disable();
  12011. }
  12012. /**
  12013. * Builds the default DOM `className`.
  12014. *
  12015. * @return {string}
  12016. * The DOM `className` for this object.
  12017. */
  12018. buildCSSClass() {
  12019. return `vjs-picture-in-picture-control ${super.buildCSSClass()}`;
  12020. }
  12021. /**
  12022. * Enables or disables button based on availability of a Picture-In-Picture mode.
  12023. *
  12024. * Enabled if
  12025. * - `player.options().enableDocumentPictureInPicture` is true and
  12026. * window.documentPictureInPicture is available; or
  12027. * - `player.disablePictureInPicture()` is false and
  12028. * element.requestPictureInPicture is available
  12029. */
  12030. handlePictureInPictureEnabledChange() {
  12031. if (document.pictureInPictureEnabled && this.player_.disablePictureInPicture() === false || this.player_.options_.enableDocumentPictureInPicture && 'documentPictureInPicture' in window$1) {
  12032. this.enable();
  12033. } else {
  12034. this.disable();
  12035. }
  12036. }
  12037. /**
  12038. * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.
  12039. *
  12040. * @param {Event} [event]
  12041. * The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be
  12042. * called.
  12043. *
  12044. * @listens Player#enterpictureinpicture
  12045. * @listens Player#leavepictureinpicture
  12046. */
  12047. handlePictureInPictureChange(event) {
  12048. if (this.player_.isInPictureInPicture()) {
  12049. this.controlText('Exit Picture-in-Picture');
  12050. } else {
  12051. this.controlText('Picture-in-Picture');
  12052. }
  12053. this.handlePictureInPictureEnabledChange();
  12054. }
  12055. /**
  12056. * This gets called when an `PictureInPictureToggle` is "clicked". See
  12057. * {@link ClickableComponent} for more detailed information on what a click can be.
  12058. *
  12059. * @param {Event} [event]
  12060. * The `keydown`, `tap`, or `click` event that caused this function to be
  12061. * called.
  12062. *
  12063. * @listens tap
  12064. * @listens click
  12065. */
  12066. handleClick(event) {
  12067. if (!this.player_.isInPictureInPicture()) {
  12068. this.player_.requestPictureInPicture();
  12069. } else {
  12070. this.player_.exitPictureInPicture();
  12071. }
  12072. }
  12073. }
  12074. /**
  12075. * The text that should display over the `PictureInPictureToggle`s controls. Added for localization.
  12076. *
  12077. * @type {string}
  12078. * @protected
  12079. */
  12080. PictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture';
  12081. Component$1.registerComponent('PictureInPictureToggle', PictureInPictureToggle);
  12082. /**
  12083. * @file fullscreen-toggle.js
  12084. */
  12085. /**
  12086. * Toggle fullscreen video
  12087. *
  12088. * @extends Button
  12089. */
  12090. class FullscreenToggle extends Button {
  12091. /**
  12092. * Creates an instance of this class.
  12093. *
  12094. * @param { import('./player').default } player
  12095. * The `Player` that this class should be attached to.
  12096. *
  12097. * @param {Object} [options]
  12098. * The key/value store of player options.
  12099. */
  12100. constructor(player, options) {
  12101. super(player, options);
  12102. this.on(player, 'fullscreenchange', e => this.handleFullscreenChange(e));
  12103. if (document[player.fsApi_.fullscreenEnabled] === false) {
  12104. this.disable();
  12105. }
  12106. }
  12107. /**
  12108. * Builds the default DOM `className`.
  12109. *
  12110. * @return {string}
  12111. * The DOM `className` for this object.
  12112. */
  12113. buildCSSClass() {
  12114. return `vjs-fullscreen-control ${super.buildCSSClass()}`;
  12115. }
  12116. /**
  12117. * Handles fullscreenchange on the player and change control text accordingly.
  12118. *
  12119. * @param {Event} [event]
  12120. * The {@link Player#fullscreenchange} event that caused this function to be
  12121. * called.
  12122. *
  12123. * @listens Player#fullscreenchange
  12124. */
  12125. handleFullscreenChange(event) {
  12126. if (this.player_.isFullscreen()) {
  12127. this.controlText('Exit Fullscreen');
  12128. } else {
  12129. this.controlText('Fullscreen');
  12130. }
  12131. }
  12132. /**
  12133. * This gets called when an `FullscreenToggle` is "clicked". See
  12134. * {@link ClickableComponent} for more detailed information on what a click can be.
  12135. *
  12136. * @param {Event} [event]
  12137. * The `keydown`, `tap`, or `click` event that caused this function to be
  12138. * called.
  12139. *
  12140. * @listens tap
  12141. * @listens click
  12142. */
  12143. handleClick(event) {
  12144. if (!this.player_.isFullscreen()) {
  12145. this.player_.requestFullscreen();
  12146. } else {
  12147. this.player_.exitFullscreen();
  12148. }
  12149. }
  12150. }
  12151. /**
  12152. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  12153. *
  12154. * @type {string}
  12155. * @protected
  12156. */
  12157. FullscreenToggle.prototype.controlText_ = 'Fullscreen';
  12158. Component$1.registerComponent('FullscreenToggle', FullscreenToggle);
  12159. /**
  12160. * Check if volume control is supported and if it isn't hide the
  12161. * `Component` that was passed using the `vjs-hidden` class.
  12162. *
  12163. * @param { import('../../component').default } self
  12164. * The component that should be hidden if volume is unsupported
  12165. *
  12166. * @param { import('../../player').default } player
  12167. * A reference to the player
  12168. *
  12169. * @private
  12170. */
  12171. const checkVolumeSupport = function (self, player) {
  12172. // hide volume controls when they're not supported by the current tech
  12173. if (player.tech_ && !player.tech_.featuresVolumeControl) {
  12174. self.addClass('vjs-hidden');
  12175. }
  12176. self.on(player, 'loadstart', function () {
  12177. if (!player.tech_.featuresVolumeControl) {
  12178. self.addClass('vjs-hidden');
  12179. } else {
  12180. self.removeClass('vjs-hidden');
  12181. }
  12182. });
  12183. };
  12184. /**
  12185. * @file volume-level.js
  12186. */
  12187. /**
  12188. * Shows volume level
  12189. *
  12190. * @extends Component
  12191. */
  12192. class VolumeLevel extends Component$1 {
  12193. /**
  12194. * Create the `Component`'s DOM element
  12195. *
  12196. * @return {Element}
  12197. * The element that was created.
  12198. */
  12199. createEl() {
  12200. const el = super.createEl('div', {
  12201. className: 'vjs-volume-level'
  12202. });
  12203. el.appendChild(super.createEl('span', {
  12204. className: 'vjs-control-text'
  12205. }));
  12206. return el;
  12207. }
  12208. }
  12209. Component$1.registerComponent('VolumeLevel', VolumeLevel);
  12210. /**
  12211. * @file volume-level-tooltip.js
  12212. */
  12213. /**
  12214. * Volume level tooltips display a volume above or side by side the volume bar.
  12215. *
  12216. * @extends Component
  12217. */
  12218. class VolumeLevelTooltip extends Component$1 {
  12219. /**
  12220. * Creates an instance of this class.
  12221. *
  12222. * @param { import('../../player').default } player
  12223. * The {@link Player} that this class should be attached to.
  12224. *
  12225. * @param {Object} [options]
  12226. * The key/value store of player options.
  12227. */
  12228. constructor(player, options) {
  12229. super(player, options);
  12230. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  12231. }
  12232. /**
  12233. * Create the volume tooltip DOM element
  12234. *
  12235. * @return {Element}
  12236. * The element that was created.
  12237. */
  12238. createEl() {
  12239. return super.createEl('div', {
  12240. className: 'vjs-volume-tooltip'
  12241. }, {
  12242. 'aria-hidden': 'true'
  12243. });
  12244. }
  12245. /**
  12246. * Updates the position of the tooltip relative to the `VolumeBar` and
  12247. * its content text.
  12248. *
  12249. * @param {Object} rangeBarRect
  12250. * The `ClientRect` for the {@link VolumeBar} element.
  12251. *
  12252. * @param {number} rangeBarPoint
  12253. * A number from 0 to 1, representing a horizontal/vertical reference point
  12254. * from the left edge of the {@link VolumeBar}
  12255. *
  12256. * @param {boolean} vertical
  12257. * Referees to the Volume control position
  12258. * in the control bar{@link VolumeControl}
  12259. *
  12260. */
  12261. update(rangeBarRect, rangeBarPoint, vertical, content) {
  12262. if (!vertical) {
  12263. const tooltipRect = getBoundingClientRect(this.el_);
  12264. const playerRect = getBoundingClientRect(this.player_.el());
  12265. const volumeBarPointPx = rangeBarRect.width * rangeBarPoint;
  12266. if (!playerRect || !tooltipRect) {
  12267. return;
  12268. }
  12269. const spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;
  12270. const spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);
  12271. let pullTooltipBy = tooltipRect.width / 2;
  12272. if (spaceLeftOfPoint < pullTooltipBy) {
  12273. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  12274. } else if (spaceRightOfPoint < pullTooltipBy) {
  12275. pullTooltipBy = spaceRightOfPoint;
  12276. }
  12277. if (pullTooltipBy < 0) {
  12278. pullTooltipBy = 0;
  12279. } else if (pullTooltipBy > tooltipRect.width) {
  12280. pullTooltipBy = tooltipRect.width;
  12281. }
  12282. this.el_.style.right = `-${pullTooltipBy}px`;
  12283. }
  12284. this.write(`${content}%`);
  12285. }
  12286. /**
  12287. * Write the volume to the tooltip DOM element.
  12288. *
  12289. * @param {string} content
  12290. * The formatted volume for the tooltip.
  12291. */
  12292. write(content) {
  12293. textContent(this.el_, content);
  12294. }
  12295. /**
  12296. * Updates the position of the volume tooltip relative to the `VolumeBar`.
  12297. *
  12298. * @param {Object} rangeBarRect
  12299. * The `ClientRect` for the {@link VolumeBar} element.
  12300. *
  12301. * @param {number} rangeBarPoint
  12302. * A number from 0 to 1, representing a horizontal/vertical reference point
  12303. * from the left edge of the {@link VolumeBar}
  12304. *
  12305. * @param {boolean} vertical
  12306. * Referees to the Volume control position
  12307. * in the control bar{@link VolumeControl}
  12308. *
  12309. * @param {number} volume
  12310. * The volume level to update the tooltip to
  12311. *
  12312. * @param {Function} cb
  12313. * A function that will be called during the request animation frame
  12314. * for tooltips that need to do additional animations from the default
  12315. */
  12316. updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {
  12317. this.requestNamedAnimationFrame('VolumeLevelTooltip#updateVolume', () => {
  12318. this.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));
  12319. if (cb) {
  12320. cb();
  12321. }
  12322. });
  12323. }
  12324. }
  12325. Component$1.registerComponent('VolumeLevelTooltip', VolumeLevelTooltip);
  12326. /**
  12327. * @file mouse-volume-level-display.js
  12328. */
  12329. /**
  12330. * The {@link MouseVolumeLevelDisplay} component tracks mouse movement over the
  12331. * {@link VolumeControl}. It displays an indicator and a {@link VolumeLevelTooltip}
  12332. * indicating the volume level which is represented by a given point in the
  12333. * {@link VolumeBar}.
  12334. *
  12335. * @extends Component
  12336. */
  12337. class MouseVolumeLevelDisplay extends Component$1 {
  12338. /**
  12339. * Creates an instance of this class.
  12340. *
  12341. * @param { import('../../player').default } player
  12342. * The {@link Player} that this class should be attached to.
  12343. *
  12344. * @param {Object} [options]
  12345. * The key/value store of player options.
  12346. */
  12347. constructor(player, options) {
  12348. super(player, options);
  12349. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  12350. }
  12351. /**
  12352. * Create the DOM element for this class.
  12353. *
  12354. * @return {Element}
  12355. * The element that was created.
  12356. */
  12357. createEl() {
  12358. return super.createEl('div', {
  12359. className: 'vjs-mouse-display'
  12360. });
  12361. }
  12362. /**
  12363. * Enquires updates to its own DOM as well as the DOM of its
  12364. * {@link VolumeLevelTooltip} child.
  12365. *
  12366. * @param {Object} rangeBarRect
  12367. * The `ClientRect` for the {@link VolumeBar} element.
  12368. *
  12369. * @param {number} rangeBarPoint
  12370. * A number from 0 to 1, representing a horizontal/vertical reference point
  12371. * from the left edge of the {@link VolumeBar}
  12372. *
  12373. * @param {boolean} vertical
  12374. * Referees to the Volume control position
  12375. * in the control bar{@link VolumeControl}
  12376. *
  12377. */
  12378. update(rangeBarRect, rangeBarPoint, vertical) {
  12379. const volume = 100 * rangeBarPoint;
  12380. this.getChild('volumeLevelTooltip').updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, () => {
  12381. if (vertical) {
  12382. this.el_.style.bottom = `${rangeBarRect.height * rangeBarPoint}px`;
  12383. } else {
  12384. this.el_.style.left = `${rangeBarRect.width * rangeBarPoint}px`;
  12385. }
  12386. });
  12387. }
  12388. }
  12389. /**
  12390. * Default options for `MouseVolumeLevelDisplay`
  12391. *
  12392. * @type {Object}
  12393. * @private
  12394. */
  12395. MouseVolumeLevelDisplay.prototype.options_ = {
  12396. children: ['volumeLevelTooltip']
  12397. };
  12398. Component$1.registerComponent('MouseVolumeLevelDisplay', MouseVolumeLevelDisplay);
  12399. /**
  12400. * @file volume-bar.js
  12401. */
  12402. /**
  12403. * The bar that contains the volume level and can be clicked on to adjust the level
  12404. *
  12405. * @extends Slider
  12406. */
  12407. class VolumeBar extends Slider {
  12408. /**
  12409. * Creates an instance of this class.
  12410. *
  12411. * @param { import('../../player').default } player
  12412. * The `Player` that this class should be attached to.
  12413. *
  12414. * @param {Object} [options]
  12415. * The key/value store of player options.
  12416. */
  12417. constructor(player, options) {
  12418. super(player, options);
  12419. this.on('slideractive', e => this.updateLastVolume_(e));
  12420. this.on(player, 'volumechange', e => this.updateARIAAttributes(e));
  12421. player.ready(() => this.updateARIAAttributes());
  12422. }
  12423. /**
  12424. * Create the `Component`'s DOM element
  12425. *
  12426. * @return {Element}
  12427. * The element that was created.
  12428. */
  12429. createEl() {
  12430. return super.createEl('div', {
  12431. className: 'vjs-volume-bar vjs-slider-bar'
  12432. }, {
  12433. 'aria-label': this.localize('Volume Level'),
  12434. 'aria-live': 'polite'
  12435. });
  12436. }
  12437. /**
  12438. * Handle mouse down on volume bar
  12439. *
  12440. * @param {Event} event
  12441. * The `mousedown` event that caused this to run.
  12442. *
  12443. * @listens mousedown
  12444. */
  12445. handleMouseDown(event) {
  12446. if (!isSingleLeftClick(event)) {
  12447. return;
  12448. }
  12449. super.handleMouseDown(event);
  12450. }
  12451. /**
  12452. * Handle movement events on the {@link VolumeMenuButton}.
  12453. *
  12454. * @param {Event} event
  12455. * The event that caused this function to run.
  12456. *
  12457. * @listens mousemove
  12458. */
  12459. handleMouseMove(event) {
  12460. const mouseVolumeLevelDisplay = this.getChild('mouseVolumeLevelDisplay');
  12461. if (mouseVolumeLevelDisplay) {
  12462. const volumeBarEl = this.el();
  12463. const volumeBarRect = getBoundingClientRect(volumeBarEl);
  12464. const vertical = this.vertical();
  12465. let volumeBarPoint = getPointerPosition(volumeBarEl, event);
  12466. volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x;
  12467. // The default skin has a gap on either side of the `VolumeBar`. This means
  12468. // that it's possible to trigger this behavior outside the boundaries of
  12469. // the `VolumeBar`. This ensures we stay within it at all times.
  12470. volumeBarPoint = clamp(volumeBarPoint, 0, 1);
  12471. mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);
  12472. }
  12473. if (!isSingleLeftClick(event)) {
  12474. return;
  12475. }
  12476. this.checkMuted();
  12477. this.player_.volume(this.calculateDistance(event));
  12478. }
  12479. /**
  12480. * If the player is muted unmute it.
  12481. */
  12482. checkMuted() {
  12483. if (this.player_.muted()) {
  12484. this.player_.muted(false);
  12485. }
  12486. }
  12487. /**
  12488. * Get percent of volume level
  12489. *
  12490. * @return {number}
  12491. * Volume level percent as a decimal number.
  12492. */
  12493. getPercent() {
  12494. if (this.player_.muted()) {
  12495. return 0;
  12496. }
  12497. return this.player_.volume();
  12498. }
  12499. /**
  12500. * Increase volume level for keyboard users
  12501. */
  12502. stepForward() {
  12503. this.checkMuted();
  12504. this.player_.volume(this.player_.volume() + 0.1);
  12505. }
  12506. /**
  12507. * Decrease volume level for keyboard users
  12508. */
  12509. stepBack() {
  12510. this.checkMuted();
  12511. this.player_.volume(this.player_.volume() - 0.1);
  12512. }
  12513. /**
  12514. * Update ARIA accessibility attributes
  12515. *
  12516. * @param {Event} [event]
  12517. * The `volumechange` event that caused this function to run.
  12518. *
  12519. * @listens Player#volumechange
  12520. */
  12521. updateARIAAttributes(event) {
  12522. const ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
  12523. this.el_.setAttribute('aria-valuenow', ariaValue);
  12524. this.el_.setAttribute('aria-valuetext', ariaValue + '%');
  12525. }
  12526. /**
  12527. * Returns the current value of the player volume as a percentage
  12528. *
  12529. * @private
  12530. */
  12531. volumeAsPercentage_() {
  12532. return Math.round(this.player_.volume() * 100);
  12533. }
  12534. /**
  12535. * When user starts dragging the VolumeBar, store the volume and listen for
  12536. * the end of the drag. When the drag ends, if the volume was set to zero,
  12537. * set lastVolume to the stored volume.
  12538. *
  12539. * @listens slideractive
  12540. * @private
  12541. */
  12542. updateLastVolume_() {
  12543. const volumeBeforeDrag = this.player_.volume();
  12544. this.one('sliderinactive', () => {
  12545. if (this.player_.volume() === 0) {
  12546. this.player_.lastVolume_(volumeBeforeDrag);
  12547. }
  12548. });
  12549. }
  12550. }
  12551. /**
  12552. * Default options for the `VolumeBar`
  12553. *
  12554. * @type {Object}
  12555. * @private
  12556. */
  12557. VolumeBar.prototype.options_ = {
  12558. children: ['volumeLevel'],
  12559. barName: 'volumeLevel'
  12560. };
  12561. // MouseVolumeLevelDisplay tooltip should not be added to a player on mobile devices
  12562. if (!IS_IOS && !IS_ANDROID) {
  12563. VolumeBar.prototype.options_.children.splice(0, 0, 'mouseVolumeLevelDisplay');
  12564. }
  12565. /**
  12566. * Call the update event for this Slider when this event happens on the player.
  12567. *
  12568. * @type {string}
  12569. */
  12570. VolumeBar.prototype.playerEvent = 'volumechange';
  12571. Component$1.registerComponent('VolumeBar', VolumeBar);
  12572. /**
  12573. * @file volume-control.js
  12574. */
  12575. /**
  12576. * The component for controlling the volume level
  12577. *
  12578. * @extends Component
  12579. */
  12580. class VolumeControl extends Component$1 {
  12581. /**
  12582. * Creates an instance of this class.
  12583. *
  12584. * @param { import('../../player').default } player
  12585. * The `Player` that this class should be attached to.
  12586. *
  12587. * @param {Object} [options={}]
  12588. * The key/value store of player options.
  12589. */
  12590. constructor(player, options = {}) {
  12591. options.vertical = options.vertical || false;
  12592. // Pass the vertical option down to the VolumeBar if
  12593. // the VolumeBar is turned on.
  12594. if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {
  12595. options.volumeBar = options.volumeBar || {};
  12596. options.volumeBar.vertical = options.vertical;
  12597. }
  12598. super(player, options);
  12599. // hide this control if volume support is missing
  12600. checkVolumeSupport(this, player);
  12601. this.throttledHandleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  12602. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  12603. this.on('mousedown', e => this.handleMouseDown(e));
  12604. this.on('touchstart', e => this.handleMouseDown(e));
  12605. this.on('mousemove', e => this.handleMouseMove(e));
  12606. // while the slider is active (the mouse has been pressed down and
  12607. // is dragging) or in focus we do not want to hide the VolumeBar
  12608. this.on(this.volumeBar, ['focus', 'slideractive'], () => {
  12609. this.volumeBar.addClass('vjs-slider-active');
  12610. this.addClass('vjs-slider-active');
  12611. this.trigger('slideractive');
  12612. });
  12613. this.on(this.volumeBar, ['blur', 'sliderinactive'], () => {
  12614. this.volumeBar.removeClass('vjs-slider-active');
  12615. this.removeClass('vjs-slider-active');
  12616. this.trigger('sliderinactive');
  12617. });
  12618. }
  12619. /**
  12620. * Create the `Component`'s DOM element
  12621. *
  12622. * @return {Element}
  12623. * The element that was created.
  12624. */
  12625. createEl() {
  12626. let orientationClass = 'vjs-volume-horizontal';
  12627. if (this.options_.vertical) {
  12628. orientationClass = 'vjs-volume-vertical';
  12629. }
  12630. return super.createEl('div', {
  12631. className: `vjs-volume-control vjs-control ${orientationClass}`
  12632. });
  12633. }
  12634. /**
  12635. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  12636. *
  12637. * @param {Event} event
  12638. * `mousedown` or `touchstart` event that triggered this function
  12639. *
  12640. * @listens mousedown
  12641. * @listens touchstart
  12642. */
  12643. handleMouseDown(event) {
  12644. const doc = this.el_.ownerDocument;
  12645. this.on(doc, 'mousemove', this.throttledHandleMouseMove);
  12646. this.on(doc, 'touchmove', this.throttledHandleMouseMove);
  12647. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  12648. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  12649. }
  12650. /**
  12651. * Handle `mouseup` or `touchend` events on the `VolumeControl`.
  12652. *
  12653. * @param {Event} event
  12654. * `mouseup` or `touchend` event that triggered this function.
  12655. *
  12656. * @listens touchend
  12657. * @listens mouseup
  12658. */
  12659. handleMouseUp(event) {
  12660. const doc = this.el_.ownerDocument;
  12661. this.off(doc, 'mousemove', this.throttledHandleMouseMove);
  12662. this.off(doc, 'touchmove', this.throttledHandleMouseMove);
  12663. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  12664. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  12665. }
  12666. /**
  12667. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  12668. *
  12669. * @param {Event} event
  12670. * `mousedown` or `touchstart` event that triggered this function
  12671. *
  12672. * @listens mousedown
  12673. * @listens touchstart
  12674. */
  12675. handleMouseMove(event) {
  12676. this.volumeBar.handleMouseMove(event);
  12677. }
  12678. }
  12679. /**
  12680. * Default options for the `VolumeControl`
  12681. *
  12682. * @type {Object}
  12683. * @private
  12684. */
  12685. VolumeControl.prototype.options_ = {
  12686. children: ['volumeBar']
  12687. };
  12688. Component$1.registerComponent('VolumeControl', VolumeControl);
  12689. /**
  12690. * Check if muting volume is supported and if it isn't hide the mute toggle
  12691. * button.
  12692. *
  12693. * @param { import('../../component').default } self
  12694. * A reference to the mute toggle button
  12695. *
  12696. * @param { import('../../player').default } player
  12697. * A reference to the player
  12698. *
  12699. * @private
  12700. */
  12701. const checkMuteSupport = function (self, player) {
  12702. // hide mute toggle button if it's not supported by the current tech
  12703. if (player.tech_ && !player.tech_.featuresMuteControl) {
  12704. self.addClass('vjs-hidden');
  12705. }
  12706. self.on(player, 'loadstart', function () {
  12707. if (!player.tech_.featuresMuteControl) {
  12708. self.addClass('vjs-hidden');
  12709. } else {
  12710. self.removeClass('vjs-hidden');
  12711. }
  12712. });
  12713. };
  12714. /**
  12715. * @file mute-toggle.js
  12716. */
  12717. /**
  12718. * A button component for muting the audio.
  12719. *
  12720. * @extends Button
  12721. */
  12722. class MuteToggle extends Button {
  12723. /**
  12724. * Creates an instance of this class.
  12725. *
  12726. * @param { import('./player').default } player
  12727. * The `Player` that this class should be attached to.
  12728. *
  12729. * @param {Object} [options]
  12730. * The key/value store of player options.
  12731. */
  12732. constructor(player, options) {
  12733. super(player, options);
  12734. // hide this control if volume support is missing
  12735. checkMuteSupport(this, player);
  12736. this.on(player, ['loadstart', 'volumechange'], e => this.update(e));
  12737. }
  12738. /**
  12739. * Builds the default DOM `className`.
  12740. *
  12741. * @return {string}
  12742. * The DOM `className` for this object.
  12743. */
  12744. buildCSSClass() {
  12745. return `vjs-mute-control ${super.buildCSSClass()}`;
  12746. }
  12747. /**
  12748. * This gets called when an `MuteToggle` is "clicked". See
  12749. * {@link ClickableComponent} for more detailed information on what a click can be.
  12750. *
  12751. * @param {Event} [event]
  12752. * The `keydown`, `tap`, or `click` event that caused this function to be
  12753. * called.
  12754. *
  12755. * @listens tap
  12756. * @listens click
  12757. */
  12758. handleClick(event) {
  12759. const vol = this.player_.volume();
  12760. const lastVolume = this.player_.lastVolume_();
  12761. if (vol === 0) {
  12762. const volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
  12763. this.player_.volume(volumeToSet);
  12764. this.player_.muted(false);
  12765. } else {
  12766. this.player_.muted(this.player_.muted() ? false : true);
  12767. }
  12768. }
  12769. /**
  12770. * Update the `MuteToggle` button based on the state of `volume` and `muted`
  12771. * on the player.
  12772. *
  12773. * @param {Event} [event]
  12774. * The {@link Player#loadstart} event if this function was called
  12775. * through an event.
  12776. *
  12777. * @listens Player#loadstart
  12778. * @listens Player#volumechange
  12779. */
  12780. update(event) {
  12781. this.updateIcon_();
  12782. this.updateControlText_();
  12783. }
  12784. /**
  12785. * Update the appearance of the `MuteToggle` icon.
  12786. *
  12787. * Possible states (given `level` variable below):
  12788. * - 0: crossed out
  12789. * - 1: zero bars of volume
  12790. * - 2: one bar of volume
  12791. * - 3: two bars of volume
  12792. *
  12793. * @private
  12794. */
  12795. updateIcon_() {
  12796. const vol = this.player_.volume();
  12797. let level = 3;
  12798. // in iOS when a player is loaded with muted attribute
  12799. // and volume is changed with a native mute button
  12800. // we want to make sure muted state is updated
  12801. if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {
  12802. this.player_.muted(this.player_.tech_.el_.muted);
  12803. }
  12804. if (vol === 0 || this.player_.muted()) {
  12805. level = 0;
  12806. } else if (vol < 0.33) {
  12807. level = 1;
  12808. } else if (vol < 0.67) {
  12809. level = 2;
  12810. }
  12811. removeClass(this.el_, [0, 1, 2, 3].reduce((str, i) => str + `${i ? ' ' : ''}vjs-vol-${i}`, ''));
  12812. addClass(this.el_, `vjs-vol-${level}`);
  12813. }
  12814. /**
  12815. * If `muted` has changed on the player, update the control text
  12816. * (`title` attribute on `vjs-mute-control` element and content of
  12817. * `vjs-control-text` element).
  12818. *
  12819. * @private
  12820. */
  12821. updateControlText_() {
  12822. const soundOff = this.player_.muted() || this.player_.volume() === 0;
  12823. const text = soundOff ? 'Unmute' : 'Mute';
  12824. if (this.controlText() !== text) {
  12825. this.controlText(text);
  12826. }
  12827. }
  12828. }
  12829. /**
  12830. * The text that should display over the `MuteToggle`s controls. Added for localization.
  12831. *
  12832. * @type {string}
  12833. * @protected
  12834. */
  12835. MuteToggle.prototype.controlText_ = 'Mute';
  12836. Component$1.registerComponent('MuteToggle', MuteToggle);
  12837. /**
  12838. * @file volume-control.js
  12839. */
  12840. /**
  12841. * A Component to contain the MuteToggle and VolumeControl so that
  12842. * they can work together.
  12843. *
  12844. * @extends Component
  12845. */
  12846. class VolumePanel extends Component$1 {
  12847. /**
  12848. * Creates an instance of this class.
  12849. *
  12850. * @param { import('./player').default } player
  12851. * The `Player` that this class should be attached to.
  12852. *
  12853. * @param {Object} [options={}]
  12854. * The key/value store of player options.
  12855. */
  12856. constructor(player, options = {}) {
  12857. if (typeof options.inline !== 'undefined') {
  12858. options.inline = options.inline;
  12859. } else {
  12860. options.inline = true;
  12861. }
  12862. // pass the inline option down to the VolumeControl as vertical if
  12863. // the VolumeControl is on.
  12864. if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {
  12865. options.volumeControl = options.volumeControl || {};
  12866. options.volumeControl.vertical = !options.inline;
  12867. }
  12868. super(player, options);
  12869. // this handler is used by mouse handler methods below
  12870. this.handleKeyPressHandler_ = e => this.handleKeyPress(e);
  12871. this.on(player, ['loadstart'], e => this.volumePanelState_(e));
  12872. this.on(this.muteToggle, 'keyup', e => this.handleKeyPress(e));
  12873. this.on(this.volumeControl, 'keyup', e => this.handleVolumeControlKeyUp(e));
  12874. this.on('keydown', e => this.handleKeyPress(e));
  12875. this.on('mouseover', e => this.handleMouseOver(e));
  12876. this.on('mouseout', e => this.handleMouseOut(e));
  12877. // while the slider is active (the mouse has been pressed down and
  12878. // is dragging) we do not want to hide the VolumeBar
  12879. this.on(this.volumeControl, ['slideractive'], this.sliderActive_);
  12880. this.on(this.volumeControl, ['sliderinactive'], this.sliderInactive_);
  12881. }
  12882. /**
  12883. * Add vjs-slider-active class to the VolumePanel
  12884. *
  12885. * @listens VolumeControl#slideractive
  12886. * @private
  12887. */
  12888. sliderActive_() {
  12889. this.addClass('vjs-slider-active');
  12890. }
  12891. /**
  12892. * Removes vjs-slider-active class to the VolumePanel
  12893. *
  12894. * @listens VolumeControl#sliderinactive
  12895. * @private
  12896. */
  12897. sliderInactive_() {
  12898. this.removeClass('vjs-slider-active');
  12899. }
  12900. /**
  12901. * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel
  12902. * depending on MuteToggle and VolumeControl state
  12903. *
  12904. * @listens Player#loadstart
  12905. * @private
  12906. */
  12907. volumePanelState_() {
  12908. // hide volume panel if neither volume control or mute toggle
  12909. // are displayed
  12910. if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {
  12911. this.addClass('vjs-hidden');
  12912. }
  12913. // if only mute toggle is visible we don't want
  12914. // volume panel expanding when hovered or active
  12915. if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {
  12916. this.addClass('vjs-mute-toggle-only');
  12917. }
  12918. }
  12919. /**
  12920. * Create the `Component`'s DOM element
  12921. *
  12922. * @return {Element}
  12923. * The element that was created.
  12924. */
  12925. createEl() {
  12926. let orientationClass = 'vjs-volume-panel-horizontal';
  12927. if (!this.options_.inline) {
  12928. orientationClass = 'vjs-volume-panel-vertical';
  12929. }
  12930. return super.createEl('div', {
  12931. className: `vjs-volume-panel vjs-control ${orientationClass}`
  12932. });
  12933. }
  12934. /**
  12935. * Dispose of the `volume-panel` and all child components.
  12936. */
  12937. dispose() {
  12938. this.handleMouseOut();
  12939. super.dispose();
  12940. }
  12941. /**
  12942. * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes
  12943. * the volume panel and sets focus on `MuteToggle`.
  12944. *
  12945. * @param {Event} event
  12946. * The `keyup` event that caused this function to be called.
  12947. *
  12948. * @listens keyup
  12949. */
  12950. handleVolumeControlKeyUp(event) {
  12951. if (keycode.isEventKey(event, 'Esc')) {
  12952. this.muteToggle.focus();
  12953. }
  12954. }
  12955. /**
  12956. * This gets called when a `VolumePanel` gains hover via a `mouseover` event.
  12957. * Turns on listening for `mouseover` event. When they happen it
  12958. * calls `this.handleMouseOver`.
  12959. *
  12960. * @param {Event} event
  12961. * The `mouseover` event that caused this function to be called.
  12962. *
  12963. * @listens mouseover
  12964. */
  12965. handleMouseOver(event) {
  12966. this.addClass('vjs-hover');
  12967. on(document, 'keyup', this.handleKeyPressHandler_);
  12968. }
  12969. /**
  12970. * This gets called when a `VolumePanel` gains hover via a `mouseout` event.
  12971. * Turns on listening for `mouseout` event. When they happen it
  12972. * calls `this.handleMouseOut`.
  12973. *
  12974. * @param {Event} event
  12975. * The `mouseout` event that caused this function to be called.
  12976. *
  12977. * @listens mouseout
  12978. */
  12979. handleMouseOut(event) {
  12980. this.removeClass('vjs-hover');
  12981. off(document, 'keyup', this.handleKeyPressHandler_);
  12982. }
  12983. /**
  12984. * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`,
  12985. * looking for ESC, which hides the `VolumeControl`.
  12986. *
  12987. * @param {Event} event
  12988. * The keypress that triggered this event.
  12989. *
  12990. * @listens keydown | keyup
  12991. */
  12992. handleKeyPress(event) {
  12993. if (keycode.isEventKey(event, 'Esc')) {
  12994. this.handleMouseOut();
  12995. }
  12996. }
  12997. }
  12998. /**
  12999. * Default options for the `VolumeControl`
  13000. *
  13001. * @type {Object}
  13002. * @private
  13003. */
  13004. VolumePanel.prototype.options_ = {
  13005. children: ['muteToggle', 'volumeControl']
  13006. };
  13007. Component$1.registerComponent('VolumePanel', VolumePanel);
  13008. /**
  13009. * Button to skip forward a configurable amount of time
  13010. * through a video. Renders in the control bar.
  13011. *
  13012. * e.g. options: {controlBar: {skipButtons: forward: 5}}
  13013. *
  13014. * @extends Button
  13015. */
  13016. class SkipForward extends Button {
  13017. constructor(player, options) {
  13018. super(player, options);
  13019. this.validOptions = [5, 10, 30];
  13020. this.skipTime = this.getSkipForwardTime();
  13021. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  13022. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  13023. this.show();
  13024. } else {
  13025. this.hide();
  13026. }
  13027. }
  13028. getSkipForwardTime() {
  13029. const playerOptions = this.options_.playerOptions;
  13030. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.forward;
  13031. }
  13032. buildCSSClass() {
  13033. return `vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`;
  13034. }
  13035. /**
  13036. * On click, skips forward in the duration/seekable range by a configurable amount of seconds.
  13037. * If the time left in the duration/seekable range is less than the configured 'skip forward' time,
  13038. * skips to end of duration/seekable range.
  13039. *
  13040. * Handle a click on a `SkipForward` button
  13041. *
  13042. * @param {EventTarget~Event} event
  13043. * The `click` event that caused this function
  13044. * to be called
  13045. */
  13046. handleClick(event) {
  13047. const currentVideoTime = this.player_.currentTime();
  13048. const liveTracker = this.player_.liveTracker;
  13049. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  13050. let newTime;
  13051. if (currentVideoTime + this.skipTime <= duration) {
  13052. newTime = currentVideoTime + this.skipTime;
  13053. } else {
  13054. newTime = duration;
  13055. }
  13056. this.player_.currentTime(newTime);
  13057. }
  13058. /**
  13059. * Update control text on languagechange
  13060. */
  13061. handleLanguagechange() {
  13062. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  13063. }
  13064. }
  13065. Component$1.registerComponent('SkipForward', SkipForward);
  13066. /**
  13067. * Button to skip backward a configurable amount of time
  13068. * through a video. Renders in the control bar.
  13069. *
  13070. * * e.g. options: {controlBar: {skipButtons: backward: 5}}
  13071. *
  13072. * @extends Button
  13073. */
  13074. class SkipBackward extends Button {
  13075. constructor(player, options) {
  13076. super(player, options);
  13077. this.validOptions = [5, 10, 30];
  13078. this.skipTime = this.getSkipBackwardTime();
  13079. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  13080. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  13081. this.show();
  13082. } else {
  13083. this.hide();
  13084. }
  13085. }
  13086. getSkipBackwardTime() {
  13087. const playerOptions = this.options_.playerOptions;
  13088. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.backward;
  13089. }
  13090. buildCSSClass() {
  13091. return `vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`;
  13092. }
  13093. /**
  13094. * On click, skips backward in the video by a configurable amount of seconds.
  13095. * If the current time in the video is less than the configured 'skip backward' time,
  13096. * skips to beginning of video or seekable range.
  13097. *
  13098. * Handle a click on a `SkipBackward` button
  13099. *
  13100. * @param {EventTarget~Event} event
  13101. * The `click` event that caused this function
  13102. * to be called
  13103. */
  13104. handleClick(event) {
  13105. const currentVideoTime = this.player_.currentTime();
  13106. const liveTracker = this.player_.liveTracker;
  13107. const seekableStart = liveTracker && liveTracker.isLive() && liveTracker.seekableStart();
  13108. let newTime;
  13109. if (seekableStart && currentVideoTime - this.skipTime <= seekableStart) {
  13110. newTime = seekableStart;
  13111. } else if (currentVideoTime >= this.skipTime) {
  13112. newTime = currentVideoTime - this.skipTime;
  13113. } else {
  13114. newTime = 0;
  13115. }
  13116. this.player_.currentTime(newTime);
  13117. }
  13118. /**
  13119. * Update control text on languagechange
  13120. */
  13121. handleLanguagechange() {
  13122. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  13123. }
  13124. }
  13125. SkipBackward.prototype.controlText_ = 'Skip Backward';
  13126. Component$1.registerComponent('SkipBackward', SkipBackward);
  13127. /**
  13128. * @file menu.js
  13129. */
  13130. /**
  13131. * The Menu component is used to build popup menus, including subtitle and
  13132. * captions selection menus.
  13133. *
  13134. * @extends Component
  13135. */
  13136. class Menu extends Component$1 {
  13137. /**
  13138. * Create an instance of this class.
  13139. *
  13140. * @param { import('../player').default } player
  13141. * the player that this component should attach to
  13142. *
  13143. * @param {Object} [options]
  13144. * Object of option names and values
  13145. *
  13146. */
  13147. constructor(player, options) {
  13148. super(player, options);
  13149. if (options) {
  13150. this.menuButton_ = options.menuButton;
  13151. }
  13152. this.focusedChild_ = -1;
  13153. this.on('keydown', e => this.handleKeyDown(e));
  13154. // All the menu item instances share the same blur handler provided by the menu container.
  13155. this.boundHandleBlur_ = e => this.handleBlur(e);
  13156. this.boundHandleTapClick_ = e => this.handleTapClick(e);
  13157. }
  13158. /**
  13159. * Add event listeners to the {@link MenuItem}.
  13160. *
  13161. * @param {Object} component
  13162. * The instance of the `MenuItem` to add listeners to.
  13163. *
  13164. */
  13165. addEventListenerForItem(component) {
  13166. if (!(component instanceof Component$1)) {
  13167. return;
  13168. }
  13169. this.on(component, 'blur', this.boundHandleBlur_);
  13170. this.on(component, ['tap', 'click'], this.boundHandleTapClick_);
  13171. }
  13172. /**
  13173. * Remove event listeners from the {@link MenuItem}.
  13174. *
  13175. * @param {Object} component
  13176. * The instance of the `MenuItem` to remove listeners.
  13177. *
  13178. */
  13179. removeEventListenerForItem(component) {
  13180. if (!(component instanceof Component$1)) {
  13181. return;
  13182. }
  13183. this.off(component, 'blur', this.boundHandleBlur_);
  13184. this.off(component, ['tap', 'click'], this.boundHandleTapClick_);
  13185. }
  13186. /**
  13187. * This method will be called indirectly when the component has been added
  13188. * before the component adds to the new menu instance by `addItem`.
  13189. * In this case, the original menu instance will remove the component
  13190. * by calling `removeChild`.
  13191. *
  13192. * @param {Object} component
  13193. * The instance of the `MenuItem`
  13194. */
  13195. removeChild(component) {
  13196. if (typeof component === 'string') {
  13197. component = this.getChild(component);
  13198. }
  13199. this.removeEventListenerForItem(component);
  13200. super.removeChild(component);
  13201. }
  13202. /**
  13203. * Add a {@link MenuItem} to the menu.
  13204. *
  13205. * @param {Object|string} component
  13206. * The name or instance of the `MenuItem` to add.
  13207. *
  13208. */
  13209. addItem(component) {
  13210. const childComponent = this.addChild(component);
  13211. if (childComponent) {
  13212. this.addEventListenerForItem(childComponent);
  13213. }
  13214. }
  13215. /**
  13216. * Create the `Menu`s DOM element.
  13217. *
  13218. * @return {Element}
  13219. * the element that was created
  13220. */
  13221. createEl() {
  13222. const contentElType = this.options_.contentElType || 'ul';
  13223. this.contentEl_ = createEl(contentElType, {
  13224. className: 'vjs-menu-content'
  13225. });
  13226. this.contentEl_.setAttribute('role', 'menu');
  13227. const el = super.createEl('div', {
  13228. append: this.contentEl_,
  13229. className: 'vjs-menu'
  13230. });
  13231. el.appendChild(this.contentEl_);
  13232. // Prevent clicks from bubbling up. Needed for Menu Buttons,
  13233. // where a click on the parent is significant
  13234. on(el, 'click', function (event) {
  13235. event.preventDefault();
  13236. event.stopImmediatePropagation();
  13237. });
  13238. return el;
  13239. }
  13240. dispose() {
  13241. this.contentEl_ = null;
  13242. this.boundHandleBlur_ = null;
  13243. this.boundHandleTapClick_ = null;
  13244. super.dispose();
  13245. }
  13246. /**
  13247. * Called when a `MenuItem` loses focus.
  13248. *
  13249. * @param {Event} event
  13250. * The `blur` event that caused this function to be called.
  13251. *
  13252. * @listens blur
  13253. */
  13254. handleBlur(event) {
  13255. const relatedTarget = event.relatedTarget || document.activeElement;
  13256. // Close menu popup when a user clicks outside the menu
  13257. if (!this.children().some(element => {
  13258. return element.el() === relatedTarget;
  13259. })) {
  13260. const btn = this.menuButton_;
  13261. if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {
  13262. btn.unpressButton();
  13263. }
  13264. }
  13265. }
  13266. /**
  13267. * Called when a `MenuItem` gets clicked or tapped.
  13268. *
  13269. * @param {Event} event
  13270. * The `click` or `tap` event that caused this function to be called.
  13271. *
  13272. * @listens click,tap
  13273. */
  13274. handleTapClick(event) {
  13275. // Unpress the associated MenuButton, and move focus back to it
  13276. if (this.menuButton_) {
  13277. this.menuButton_.unpressButton();
  13278. const childComponents = this.children();
  13279. if (!Array.isArray(childComponents)) {
  13280. return;
  13281. }
  13282. const foundComponent = childComponents.filter(component => component.el() === event.target)[0];
  13283. if (!foundComponent) {
  13284. return;
  13285. }
  13286. // don't focus menu button if item is a caption settings item
  13287. // because focus will move elsewhere
  13288. if (foundComponent.name() !== 'CaptionSettingsMenuItem') {
  13289. this.menuButton_.focus();
  13290. }
  13291. }
  13292. }
  13293. /**
  13294. * Handle a `keydown` event on this menu. This listener is added in the constructor.
  13295. *
  13296. * @param {Event} event
  13297. * A `keydown` event that happened on the menu.
  13298. *
  13299. * @listens keydown
  13300. */
  13301. handleKeyDown(event) {
  13302. // Left and Down Arrows
  13303. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  13304. event.preventDefault();
  13305. event.stopPropagation();
  13306. this.stepForward();
  13307. // Up and Right Arrows
  13308. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  13309. event.preventDefault();
  13310. event.stopPropagation();
  13311. this.stepBack();
  13312. }
  13313. }
  13314. /**
  13315. * Move to next (lower) menu item for keyboard users.
  13316. */
  13317. stepForward() {
  13318. let stepChild = 0;
  13319. if (this.focusedChild_ !== undefined) {
  13320. stepChild = this.focusedChild_ + 1;
  13321. }
  13322. this.focus(stepChild);
  13323. }
  13324. /**
  13325. * Move to previous (higher) menu item for keyboard users.
  13326. */
  13327. stepBack() {
  13328. let stepChild = 0;
  13329. if (this.focusedChild_ !== undefined) {
  13330. stepChild = this.focusedChild_ - 1;
  13331. }
  13332. this.focus(stepChild);
  13333. }
  13334. /**
  13335. * Set focus on a {@link MenuItem} in the `Menu`.
  13336. *
  13337. * @param {Object|string} [item=0]
  13338. * Index of child item set focus on.
  13339. */
  13340. focus(item = 0) {
  13341. const children = this.children().slice();
  13342. const haveTitle = children.length && children[0].hasClass('vjs-menu-title');
  13343. if (haveTitle) {
  13344. children.shift();
  13345. }
  13346. if (children.length > 0) {
  13347. if (item < 0) {
  13348. item = 0;
  13349. } else if (item >= children.length) {
  13350. item = children.length - 1;
  13351. }
  13352. this.focusedChild_ = item;
  13353. children[item].el_.focus();
  13354. }
  13355. }
  13356. }
  13357. Component$1.registerComponent('Menu', Menu);
  13358. /**
  13359. * @file menu-button.js
  13360. */
  13361. /**
  13362. * A `MenuButton` class for any popup {@link Menu}.
  13363. *
  13364. * @extends Component
  13365. */
  13366. class MenuButton extends Component$1 {
  13367. /**
  13368. * Creates an instance of this class.
  13369. *
  13370. * @param { import('../player').default } player
  13371. * The `Player` that this class should be attached to.
  13372. *
  13373. * @param {Object} [options={}]
  13374. * The key/value store of player options.
  13375. */
  13376. constructor(player, options = {}) {
  13377. super(player, options);
  13378. this.menuButton_ = new Button(player, options);
  13379. this.menuButton_.controlText(this.controlText_);
  13380. this.menuButton_.el_.setAttribute('aria-haspopup', 'true');
  13381. // Add buildCSSClass values to the button, not the wrapper
  13382. const buttonClass = Button.prototype.buildCSSClass();
  13383. this.menuButton_.el_.className = this.buildCSSClass() + ' ' + buttonClass;
  13384. this.menuButton_.removeClass('vjs-control');
  13385. this.addChild(this.menuButton_);
  13386. this.update();
  13387. this.enabled_ = true;
  13388. const handleClick = e => this.handleClick(e);
  13389. this.handleMenuKeyUp_ = e => this.handleMenuKeyUp(e);
  13390. this.on(this.menuButton_, 'tap', handleClick);
  13391. this.on(this.menuButton_, 'click', handleClick);
  13392. this.on(this.menuButton_, 'keydown', e => this.handleKeyDown(e));
  13393. this.on(this.menuButton_, 'mouseenter', () => {
  13394. this.addClass('vjs-hover');
  13395. this.menu.show();
  13396. on(document, 'keyup', this.handleMenuKeyUp_);
  13397. });
  13398. this.on('mouseleave', e => this.handleMouseLeave(e));
  13399. this.on('keydown', e => this.handleSubmenuKeyDown(e));
  13400. }
  13401. /**
  13402. * Update the menu based on the current state of its items.
  13403. */
  13404. update() {
  13405. const menu = this.createMenu();
  13406. if (this.menu) {
  13407. this.menu.dispose();
  13408. this.removeChild(this.menu);
  13409. }
  13410. this.menu = menu;
  13411. this.addChild(menu);
  13412. /**
  13413. * Track the state of the menu button
  13414. *
  13415. * @type {Boolean}
  13416. * @private
  13417. */
  13418. this.buttonPressed_ = false;
  13419. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  13420. if (this.items && this.items.length <= this.hideThreshold_) {
  13421. this.hide();
  13422. this.menu.contentEl_.removeAttribute('role');
  13423. } else {
  13424. this.show();
  13425. this.menu.contentEl_.setAttribute('role', 'menu');
  13426. }
  13427. }
  13428. /**
  13429. * Create the menu and add all items to it.
  13430. *
  13431. * @return {Menu}
  13432. * The constructed menu
  13433. */
  13434. createMenu() {
  13435. const menu = new Menu(this.player_, {
  13436. menuButton: this
  13437. });
  13438. /**
  13439. * Hide the menu if the number of items is less than or equal to this threshold. This defaults
  13440. * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list
  13441. * it here because every time we run `createMenu` we need to reset the value.
  13442. *
  13443. * @protected
  13444. * @type {Number}
  13445. */
  13446. this.hideThreshold_ = 0;
  13447. // Add a title list item to the top
  13448. if (this.options_.title) {
  13449. const titleEl = createEl('li', {
  13450. className: 'vjs-menu-title',
  13451. textContent: toTitleCase$1(this.options_.title),
  13452. tabIndex: -1
  13453. });
  13454. const titleComponent = new Component$1(this.player_, {
  13455. el: titleEl
  13456. });
  13457. menu.addItem(titleComponent);
  13458. }
  13459. this.items = this.createItems();
  13460. if (this.items) {
  13461. // Add menu items to the menu
  13462. for (let i = 0; i < this.items.length; i++) {
  13463. menu.addItem(this.items[i]);
  13464. }
  13465. }
  13466. return menu;
  13467. }
  13468. /**
  13469. * Create the list of menu items. Specific to each subclass.
  13470. *
  13471. * @abstract
  13472. */
  13473. createItems() {}
  13474. /**
  13475. * Create the `MenuButtons`s DOM element.
  13476. *
  13477. * @return {Element}
  13478. * The element that gets created.
  13479. */
  13480. createEl() {
  13481. return super.createEl('div', {
  13482. className: this.buildWrapperCSSClass()
  13483. }, {});
  13484. }
  13485. /**
  13486. * Allow sub components to stack CSS class names for the wrapper element
  13487. *
  13488. * @return {string}
  13489. * The constructed wrapper DOM `className`
  13490. */
  13491. buildWrapperCSSClass() {
  13492. let menuButtonClass = 'vjs-menu-button';
  13493. // If the inline option is passed, we want to use different styles altogether.
  13494. if (this.options_.inline === true) {
  13495. menuButtonClass += '-inline';
  13496. } else {
  13497. menuButtonClass += '-popup';
  13498. }
  13499. // TODO: Fix the CSS so that this isn't necessary
  13500. const buttonClass = Button.prototype.buildCSSClass();
  13501. return `vjs-menu-button ${menuButtonClass} ${buttonClass} ${super.buildCSSClass()}`;
  13502. }
  13503. /**
  13504. * Builds the default DOM `className`.
  13505. *
  13506. * @return {string}
  13507. * The DOM `className` for this object.
  13508. */
  13509. buildCSSClass() {
  13510. let menuButtonClass = 'vjs-menu-button';
  13511. // If the inline option is passed, we want to use different styles altogether.
  13512. if (this.options_.inline === true) {
  13513. menuButtonClass += '-inline';
  13514. } else {
  13515. menuButtonClass += '-popup';
  13516. }
  13517. return `vjs-menu-button ${menuButtonClass} ${super.buildCSSClass()}`;
  13518. }
  13519. /**
  13520. * Get or set the localized control text that will be used for accessibility.
  13521. *
  13522. * > NOTE: This will come from the internal `menuButton_` element.
  13523. *
  13524. * @param {string} [text]
  13525. * Control text for element.
  13526. *
  13527. * @param {Element} [el=this.menuButton_.el()]
  13528. * Element to set the title on.
  13529. *
  13530. * @return {string}
  13531. * - The control text when getting
  13532. */
  13533. controlText(text, el = this.menuButton_.el()) {
  13534. return this.menuButton_.controlText(text, el);
  13535. }
  13536. /**
  13537. * Dispose of the `menu-button` and all child components.
  13538. */
  13539. dispose() {
  13540. this.handleMouseLeave();
  13541. super.dispose();
  13542. }
  13543. /**
  13544. * Handle a click on a `MenuButton`.
  13545. * See {@link ClickableComponent#handleClick} for instances where this is called.
  13546. *
  13547. * @param {Event} event
  13548. * The `keydown`, `tap`, or `click` event that caused this function to be
  13549. * called.
  13550. *
  13551. * @listens tap
  13552. * @listens click
  13553. */
  13554. handleClick(event) {
  13555. if (this.buttonPressed_) {
  13556. this.unpressButton();
  13557. } else {
  13558. this.pressButton();
  13559. }
  13560. }
  13561. /**
  13562. * Handle `mouseleave` for `MenuButton`.
  13563. *
  13564. * @param {Event} event
  13565. * The `mouseleave` event that caused this function to be called.
  13566. *
  13567. * @listens mouseleave
  13568. */
  13569. handleMouseLeave(event) {
  13570. this.removeClass('vjs-hover');
  13571. off(document, 'keyup', this.handleMenuKeyUp_);
  13572. }
  13573. /**
  13574. * Set the focus to the actual button, not to this element
  13575. */
  13576. focus() {
  13577. this.menuButton_.focus();
  13578. }
  13579. /**
  13580. * Remove the focus from the actual button, not this element
  13581. */
  13582. blur() {
  13583. this.menuButton_.blur();
  13584. }
  13585. /**
  13586. * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See
  13587. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  13588. *
  13589. * @param {Event} event
  13590. * The `keydown` event that caused this function to be called.
  13591. *
  13592. * @listens keydown
  13593. */
  13594. handleKeyDown(event) {
  13595. // Escape or Tab unpress the 'button'
  13596. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  13597. if (this.buttonPressed_) {
  13598. this.unpressButton();
  13599. }
  13600. // Don't preventDefault for Tab key - we still want to lose focus
  13601. if (!keycode.isEventKey(event, 'Tab')) {
  13602. event.preventDefault();
  13603. // Set focus back to the menu button's button
  13604. this.menuButton_.focus();
  13605. }
  13606. // Up Arrow or Down Arrow also 'press' the button to open the menu
  13607. } else if (keycode.isEventKey(event, 'Up') || keycode.isEventKey(event, 'Down')) {
  13608. if (!this.buttonPressed_) {
  13609. event.preventDefault();
  13610. this.pressButton();
  13611. }
  13612. }
  13613. }
  13614. /**
  13615. * Handle a `keyup` event on a `MenuButton`. The listener for this is added in
  13616. * the constructor.
  13617. *
  13618. * @param {Event} event
  13619. * Key press event
  13620. *
  13621. * @listens keyup
  13622. */
  13623. handleMenuKeyUp(event) {
  13624. // Escape hides popup menu
  13625. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  13626. this.removeClass('vjs-hover');
  13627. }
  13628. }
  13629. /**
  13630. * This method name now delegates to `handleSubmenuKeyDown`. This means
  13631. * anyone calling `handleSubmenuKeyPress` will not see their method calls
  13632. * stop working.
  13633. *
  13634. * @param {Event} event
  13635. * The event that caused this function to be called.
  13636. */
  13637. handleSubmenuKeyPress(event) {
  13638. this.handleSubmenuKeyDown(event);
  13639. }
  13640. /**
  13641. * Handle a `keydown` event on a sub-menu. The listener for this is added in
  13642. * the constructor.
  13643. *
  13644. * @param {Event} event
  13645. * Key press event
  13646. *
  13647. * @listens keydown
  13648. */
  13649. handleSubmenuKeyDown(event) {
  13650. // Escape or Tab unpress the 'button'
  13651. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  13652. if (this.buttonPressed_) {
  13653. this.unpressButton();
  13654. }
  13655. // Don't preventDefault for Tab key - we still want to lose focus
  13656. if (!keycode.isEventKey(event, 'Tab')) {
  13657. event.preventDefault();
  13658. // Set focus back to the menu button's button
  13659. this.menuButton_.focus();
  13660. }
  13661. }
  13662. }
  13663. /**
  13664. * Put the current `MenuButton` into a pressed state.
  13665. */
  13666. pressButton() {
  13667. if (this.enabled_) {
  13668. this.buttonPressed_ = true;
  13669. this.menu.show();
  13670. this.menu.lockShowing();
  13671. this.menuButton_.el_.setAttribute('aria-expanded', 'true');
  13672. // set the focus into the submenu, except on iOS where it is resulting in
  13673. // undesired scrolling behavior when the player is in an iframe
  13674. if (IS_IOS && isInFrame()) {
  13675. // Return early so that the menu isn't focused
  13676. return;
  13677. }
  13678. this.menu.focus();
  13679. }
  13680. }
  13681. /**
  13682. * Take the current `MenuButton` out of a pressed state.
  13683. */
  13684. unpressButton() {
  13685. if (this.enabled_) {
  13686. this.buttonPressed_ = false;
  13687. this.menu.unlockShowing();
  13688. this.menu.hide();
  13689. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  13690. }
  13691. }
  13692. /**
  13693. * Disable the `MenuButton`. Don't allow it to be clicked.
  13694. */
  13695. disable() {
  13696. this.unpressButton();
  13697. this.enabled_ = false;
  13698. this.addClass('vjs-disabled');
  13699. this.menuButton_.disable();
  13700. }
  13701. /**
  13702. * Enable the `MenuButton`. Allow it to be clicked.
  13703. */
  13704. enable() {
  13705. this.enabled_ = true;
  13706. this.removeClass('vjs-disabled');
  13707. this.menuButton_.enable();
  13708. }
  13709. }
  13710. Component$1.registerComponent('MenuButton', MenuButton);
  13711. /**
  13712. * @file track-button.js
  13713. */
  13714. /**
  13715. * The base class for buttons that toggle specific track types (e.g. subtitles).
  13716. *
  13717. * @extends MenuButton
  13718. */
  13719. class TrackButton extends MenuButton {
  13720. /**
  13721. * Creates an instance of this class.
  13722. *
  13723. * @param { import('./player').default } player
  13724. * The `Player` that this class should be attached to.
  13725. *
  13726. * @param {Object} [options]
  13727. * The key/value store of player options.
  13728. */
  13729. constructor(player, options) {
  13730. const tracks = options.tracks;
  13731. super(player, options);
  13732. if (this.items.length <= 1) {
  13733. this.hide();
  13734. }
  13735. if (!tracks) {
  13736. return;
  13737. }
  13738. const updateHandler = bind_(this, this.update);
  13739. tracks.addEventListener('removetrack', updateHandler);
  13740. tracks.addEventListener('addtrack', updateHandler);
  13741. tracks.addEventListener('labelchange', updateHandler);
  13742. this.player_.on('ready', updateHandler);
  13743. this.player_.on('dispose', function () {
  13744. tracks.removeEventListener('removetrack', updateHandler);
  13745. tracks.removeEventListener('addtrack', updateHandler);
  13746. tracks.removeEventListener('labelchange', updateHandler);
  13747. });
  13748. }
  13749. }
  13750. Component$1.registerComponent('TrackButton', TrackButton);
  13751. /**
  13752. * @file menu-keys.js
  13753. */
  13754. /**
  13755. * All keys used for operation of a menu (`MenuButton`, `Menu`, and `MenuItem`)
  13756. * Note that 'Enter' and 'Space' are not included here (otherwise they would
  13757. * prevent the `MenuButton` and `MenuItem` from being keyboard-clickable)
  13758. *
  13759. * @typedef MenuKeys
  13760. * @array
  13761. */
  13762. const MenuKeys = ['Tab', 'Esc', 'Up', 'Down', 'Right', 'Left'];
  13763. /**
  13764. * @file menu-item.js
  13765. */
  13766. /**
  13767. * The component for a menu item. `<li>`
  13768. *
  13769. * @extends ClickableComponent
  13770. */
  13771. class MenuItem extends ClickableComponent {
  13772. /**
  13773. * Creates an instance of the this class.
  13774. *
  13775. * @param { import('../player').default } player
  13776. * The `Player` that this class should be attached to.
  13777. *
  13778. * @param {Object} [options={}]
  13779. * The key/value store of player options.
  13780. *
  13781. */
  13782. constructor(player, options) {
  13783. super(player, options);
  13784. this.selectable = options.selectable;
  13785. this.isSelected_ = options.selected || false;
  13786. this.multiSelectable = options.multiSelectable;
  13787. this.selected(this.isSelected_);
  13788. if (this.selectable) {
  13789. if (this.multiSelectable) {
  13790. this.el_.setAttribute('role', 'menuitemcheckbox');
  13791. } else {
  13792. this.el_.setAttribute('role', 'menuitemradio');
  13793. }
  13794. } else {
  13795. this.el_.setAttribute('role', 'menuitem');
  13796. }
  13797. }
  13798. /**
  13799. * Create the `MenuItem's DOM element
  13800. *
  13801. * @param {string} [type=li]
  13802. * Element's node type, not actually used, always set to `li`.
  13803. *
  13804. * @param {Object} [props={}]
  13805. * An object of properties that should be set on the element
  13806. *
  13807. * @param {Object} [attrs={}]
  13808. * An object of attributes that should be set on the element
  13809. *
  13810. * @return {Element}
  13811. * The element that gets created.
  13812. */
  13813. createEl(type, props, attrs) {
  13814. // The control is textual, not just an icon
  13815. this.nonIconControl = true;
  13816. const el = super.createEl('li', Object.assign({
  13817. className: 'vjs-menu-item',
  13818. tabIndex: -1
  13819. }, props), attrs);
  13820. // swap icon with menu item text.
  13821. el.replaceChild(createEl('span', {
  13822. className: 'vjs-menu-item-text',
  13823. textContent: this.localize(this.options_.label)
  13824. }), el.querySelector('.vjs-icon-placeholder'));
  13825. return el;
  13826. }
  13827. /**
  13828. * Ignore keys which are used by the menu, but pass any other ones up. See
  13829. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  13830. *
  13831. * @param {Event} event
  13832. * The `keydown` event that caused this function to be called.
  13833. *
  13834. * @listens keydown
  13835. */
  13836. handleKeyDown(event) {
  13837. if (!MenuKeys.some(key => keycode.isEventKey(event, key))) {
  13838. // Pass keydown handling up for unused keys
  13839. super.handleKeyDown(event);
  13840. }
  13841. }
  13842. /**
  13843. * Any click on a `MenuItem` puts it into the selected state.
  13844. * See {@link ClickableComponent#handleClick} for instances where this is called.
  13845. *
  13846. * @param {Event} event
  13847. * The `keydown`, `tap`, or `click` event that caused this function to be
  13848. * called.
  13849. *
  13850. * @listens tap
  13851. * @listens click
  13852. */
  13853. handleClick(event) {
  13854. this.selected(true);
  13855. }
  13856. /**
  13857. * Set the state for this menu item as selected or not.
  13858. *
  13859. * @param {boolean} selected
  13860. * if the menu item is selected or not
  13861. */
  13862. selected(selected) {
  13863. if (this.selectable) {
  13864. if (selected) {
  13865. this.addClass('vjs-selected');
  13866. this.el_.setAttribute('aria-checked', 'true');
  13867. // aria-checked isn't fully supported by browsers/screen readers,
  13868. // so indicate selected state to screen reader in the control text.
  13869. this.controlText(', selected');
  13870. this.isSelected_ = true;
  13871. } else {
  13872. this.removeClass('vjs-selected');
  13873. this.el_.setAttribute('aria-checked', 'false');
  13874. // Indicate un-selected state to screen reader
  13875. this.controlText('');
  13876. this.isSelected_ = false;
  13877. }
  13878. }
  13879. }
  13880. }
  13881. Component$1.registerComponent('MenuItem', MenuItem);
  13882. /**
  13883. * @file text-track-menu-item.js
  13884. */
  13885. /**
  13886. * The specific menu item type for selecting a language within a text track kind
  13887. *
  13888. * @extends MenuItem
  13889. */
  13890. class TextTrackMenuItem extends MenuItem {
  13891. /**
  13892. * Creates an instance of this class.
  13893. *
  13894. * @param { import('../../player').default } player
  13895. * The `Player` that this class should be attached to.
  13896. *
  13897. * @param {Object} [options]
  13898. * The key/value store of player options.
  13899. */
  13900. constructor(player, options) {
  13901. const track = options.track;
  13902. const tracks = player.textTracks();
  13903. // Modify options for parent MenuItem class's init.
  13904. options.label = track.label || track.language || 'Unknown';
  13905. options.selected = track.mode === 'showing';
  13906. super(player, options);
  13907. this.track = track;
  13908. // Determine the relevant kind(s) of tracks for this component and filter
  13909. // out empty kinds.
  13910. this.kinds = (options.kinds || [options.kind || this.track.kind]).filter(Boolean);
  13911. const changeHandler = (...args) => {
  13912. this.handleTracksChange.apply(this, args);
  13913. };
  13914. const selectedLanguageChangeHandler = (...args) => {
  13915. this.handleSelectedLanguageChange.apply(this, args);
  13916. };
  13917. player.on(['loadstart', 'texttrackchange'], changeHandler);
  13918. tracks.addEventListener('change', changeHandler);
  13919. tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  13920. this.on('dispose', function () {
  13921. player.off(['loadstart', 'texttrackchange'], changeHandler);
  13922. tracks.removeEventListener('change', changeHandler);
  13923. tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  13924. });
  13925. // iOS7 doesn't dispatch change events to TextTrackLists when an
  13926. // associated track's mode changes. Without something like
  13927. // Object.observe() (also not present on iOS7), it's not
  13928. // possible to detect changes to the mode attribute and polyfill
  13929. // the change event. As a poor substitute, we manually dispatch
  13930. // change events whenever the controls modify the mode.
  13931. if (tracks.onchange === undefined) {
  13932. let event;
  13933. this.on(['tap', 'click'], function () {
  13934. if (typeof window$1.Event !== 'object') {
  13935. // Android 2.3 throws an Illegal Constructor error for window.Event
  13936. try {
  13937. event = new window$1.Event('change');
  13938. } catch (err) {
  13939. // continue regardless of error
  13940. }
  13941. }
  13942. if (!event) {
  13943. event = document.createEvent('Event');
  13944. event.initEvent('change', true, true);
  13945. }
  13946. tracks.dispatchEvent(event);
  13947. });
  13948. }
  13949. // set the default state based on current tracks
  13950. this.handleTracksChange();
  13951. }
  13952. /**
  13953. * This gets called when an `TextTrackMenuItem` is "clicked". See
  13954. * {@link ClickableComponent} for more detailed information on what a click can be.
  13955. *
  13956. * @param {Event} event
  13957. * The `keydown`, `tap`, or `click` event that caused this function to be
  13958. * called.
  13959. *
  13960. * @listens tap
  13961. * @listens click
  13962. */
  13963. handleClick(event) {
  13964. const referenceTrack = this.track;
  13965. const tracks = this.player_.textTracks();
  13966. super.handleClick(event);
  13967. if (!tracks) {
  13968. return;
  13969. }
  13970. for (let i = 0; i < tracks.length; i++) {
  13971. const track = tracks[i];
  13972. // If the track from the text tracks list is not of the right kind,
  13973. // skip it. We do not want to affect tracks of incompatible kind(s).
  13974. if (this.kinds.indexOf(track.kind) === -1) {
  13975. continue;
  13976. }
  13977. // If this text track is the component's track and it is not showing,
  13978. // set it to showing.
  13979. if (track === referenceTrack) {
  13980. if (track.mode !== 'showing') {
  13981. track.mode = 'showing';
  13982. }
  13983. // If this text track is not the component's track and it is not
  13984. // disabled, set it to disabled.
  13985. } else if (track.mode !== 'disabled') {
  13986. track.mode = 'disabled';
  13987. }
  13988. }
  13989. }
  13990. /**
  13991. * Handle text track list change
  13992. *
  13993. * @param {Event} event
  13994. * The `change` event that caused this function to be called.
  13995. *
  13996. * @listens TextTrackList#change
  13997. */
  13998. handleTracksChange(event) {
  13999. const shouldBeSelected = this.track.mode === 'showing';
  14000. // Prevent redundant selected() calls because they may cause
  14001. // screen readers to read the appended control text unnecessarily
  14002. if (shouldBeSelected !== this.isSelected_) {
  14003. this.selected(shouldBeSelected);
  14004. }
  14005. }
  14006. handleSelectedLanguageChange(event) {
  14007. if (this.track.mode === 'showing') {
  14008. const selectedLanguage = this.player_.cache_.selectedLanguage;
  14009. // Don't replace the kind of track across the same language
  14010. if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
  14011. return;
  14012. }
  14013. this.player_.cache_.selectedLanguage = {
  14014. enabled: true,
  14015. language: this.track.language,
  14016. kind: this.track.kind
  14017. };
  14018. }
  14019. }
  14020. dispose() {
  14021. // remove reference to track object on dispose
  14022. this.track = null;
  14023. super.dispose();
  14024. }
  14025. }
  14026. Component$1.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
  14027. /**
  14028. * @file off-text-track-menu-item.js
  14029. */
  14030. /**
  14031. * A special menu item for turning of a specific type of text track
  14032. *
  14033. * @extends TextTrackMenuItem
  14034. */
  14035. class OffTextTrackMenuItem extends TextTrackMenuItem {
  14036. /**
  14037. * Creates an instance of this class.
  14038. *
  14039. * @param { import('../../player').default } player
  14040. * The `Player` that this class should be attached to.
  14041. *
  14042. * @param {Object} [options]
  14043. * The key/value store of player options.
  14044. */
  14045. constructor(player, options) {
  14046. // Create pseudo track info
  14047. // Requires options['kind']
  14048. options.track = {
  14049. player,
  14050. // it is no longer necessary to store `kind` or `kinds` on the track itself
  14051. // since they are now stored in the `kinds` property of all instances of
  14052. // TextTrackMenuItem, but this will remain for backwards compatibility
  14053. kind: options.kind,
  14054. kinds: options.kinds,
  14055. default: false,
  14056. mode: 'disabled'
  14057. };
  14058. if (!options.kinds) {
  14059. options.kinds = [options.kind];
  14060. }
  14061. if (options.label) {
  14062. options.track.label = options.label;
  14063. } else {
  14064. options.track.label = options.kinds.join(' and ') + ' off';
  14065. }
  14066. // MenuItem is selectable
  14067. options.selectable = true;
  14068. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14069. options.multiSelectable = false;
  14070. super(player, options);
  14071. }
  14072. /**
  14073. * Handle text track change
  14074. *
  14075. * @param {Event} event
  14076. * The event that caused this function to run
  14077. */
  14078. handleTracksChange(event) {
  14079. const tracks = this.player().textTracks();
  14080. let shouldBeSelected = true;
  14081. for (let i = 0, l = tracks.length; i < l; i++) {
  14082. const track = tracks[i];
  14083. if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {
  14084. shouldBeSelected = false;
  14085. break;
  14086. }
  14087. }
  14088. // Prevent redundant selected() calls because they may cause
  14089. // screen readers to read the appended control text unnecessarily
  14090. if (shouldBeSelected !== this.isSelected_) {
  14091. this.selected(shouldBeSelected);
  14092. }
  14093. }
  14094. handleSelectedLanguageChange(event) {
  14095. const tracks = this.player().textTracks();
  14096. let allHidden = true;
  14097. for (let i = 0, l = tracks.length; i < l; i++) {
  14098. const track = tracks[i];
  14099. if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {
  14100. allHidden = false;
  14101. break;
  14102. }
  14103. }
  14104. if (allHidden) {
  14105. this.player_.cache_.selectedLanguage = {
  14106. enabled: false
  14107. };
  14108. }
  14109. }
  14110. /**
  14111. * Update control text and label on languagechange
  14112. */
  14113. handleLanguagechange() {
  14114. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.label);
  14115. super.handleLanguagechange();
  14116. }
  14117. }
  14118. Component$1.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
  14119. /**
  14120. * @file text-track-button.js
  14121. */
  14122. /**
  14123. * The base class for buttons that toggle specific text track types (e.g. subtitles)
  14124. *
  14125. * @extends MenuButton
  14126. */
  14127. class TextTrackButton extends TrackButton {
  14128. /**
  14129. * Creates an instance of this class.
  14130. *
  14131. * @param { import('../../player').default } player
  14132. * The `Player` that this class should be attached to.
  14133. *
  14134. * @param {Object} [options={}]
  14135. * The key/value store of player options.
  14136. */
  14137. constructor(player, options = {}) {
  14138. options.tracks = player.textTracks();
  14139. super(player, options);
  14140. }
  14141. /**
  14142. * Create a menu item for each text track
  14143. *
  14144. * @param {TextTrackMenuItem[]} [items=[]]
  14145. * Existing array of items to use during creation
  14146. *
  14147. * @return {TextTrackMenuItem[]}
  14148. * Array of menu items that were created
  14149. */
  14150. createItems(items = [], TrackMenuItem = TextTrackMenuItem) {
  14151. // Label is an override for the [track] off label
  14152. // USed to localise captions/subtitles
  14153. let label;
  14154. if (this.label_) {
  14155. label = `${this.label_} off`;
  14156. }
  14157. // Add an OFF menu item to turn all tracks off
  14158. items.push(new OffTextTrackMenuItem(this.player_, {
  14159. kinds: this.kinds_,
  14160. kind: this.kind_,
  14161. label
  14162. }));
  14163. this.hideThreshold_ += 1;
  14164. const tracks = this.player_.textTracks();
  14165. if (!Array.isArray(this.kinds_)) {
  14166. this.kinds_ = [this.kind_];
  14167. }
  14168. for (let i = 0; i < tracks.length; i++) {
  14169. const track = tracks[i];
  14170. // only add tracks that are of an appropriate kind and have a label
  14171. if (this.kinds_.indexOf(track.kind) > -1) {
  14172. const item = new TrackMenuItem(this.player_, {
  14173. track,
  14174. kinds: this.kinds_,
  14175. kind: this.kind_,
  14176. // MenuItem is selectable
  14177. selectable: true,
  14178. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14179. multiSelectable: false
  14180. });
  14181. item.addClass(`vjs-${track.kind}-menu-item`);
  14182. items.push(item);
  14183. }
  14184. }
  14185. return items;
  14186. }
  14187. }
  14188. Component$1.registerComponent('TextTrackButton', TextTrackButton);
  14189. /**
  14190. * @file chapters-track-menu-item.js
  14191. */
  14192. /**
  14193. * The chapter track menu item
  14194. *
  14195. * @extends MenuItem
  14196. */
  14197. class ChaptersTrackMenuItem extends MenuItem {
  14198. /**
  14199. * Creates an instance of this class.
  14200. *
  14201. * @param { import('../../player').default } player
  14202. * The `Player` that this class should be attached to.
  14203. *
  14204. * @param {Object} [options]
  14205. * The key/value store of player options.
  14206. */
  14207. constructor(player, options) {
  14208. const track = options.track;
  14209. const cue = options.cue;
  14210. const currentTime = player.currentTime();
  14211. // Modify options for parent MenuItem class's init.
  14212. options.selectable = true;
  14213. options.multiSelectable = false;
  14214. options.label = cue.text;
  14215. options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
  14216. super(player, options);
  14217. this.track = track;
  14218. this.cue = cue;
  14219. }
  14220. /**
  14221. * This gets called when an `ChaptersTrackMenuItem` is "clicked". See
  14222. * {@link ClickableComponent} for more detailed information on what a click can be.
  14223. *
  14224. * @param {Event} [event]
  14225. * The `keydown`, `tap`, or `click` event that caused this function to be
  14226. * called.
  14227. *
  14228. * @listens tap
  14229. * @listens click
  14230. */
  14231. handleClick(event) {
  14232. super.handleClick();
  14233. this.player_.currentTime(this.cue.startTime);
  14234. }
  14235. }
  14236. Component$1.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
  14237. /**
  14238. * @file chapters-button.js
  14239. */
  14240. /**
  14241. * The button component for toggling and selecting chapters
  14242. * Chapters act much differently than other text tracks
  14243. * Cues are navigation vs. other tracks of alternative languages
  14244. *
  14245. * @extends TextTrackButton
  14246. */
  14247. class ChaptersButton extends TextTrackButton {
  14248. /**
  14249. * Creates an instance of this class.
  14250. *
  14251. * @param { import('../../player').default } player
  14252. * The `Player` that this class should be attached to.
  14253. *
  14254. * @param {Object} [options]
  14255. * The key/value store of player options.
  14256. *
  14257. * @param {Function} [ready]
  14258. * The function to call when this function is ready.
  14259. */
  14260. constructor(player, options, ready) {
  14261. super(player, options, ready);
  14262. this.selectCurrentItem_ = () => {
  14263. this.items.forEach(item => {
  14264. item.selected(this.track_.activeCues[0] === item.cue);
  14265. });
  14266. };
  14267. }
  14268. /**
  14269. * Builds the default DOM `className`.
  14270. *
  14271. * @return {string}
  14272. * The DOM `className` for this object.
  14273. */
  14274. buildCSSClass() {
  14275. return `vjs-chapters-button ${super.buildCSSClass()}`;
  14276. }
  14277. buildWrapperCSSClass() {
  14278. return `vjs-chapters-button ${super.buildWrapperCSSClass()}`;
  14279. }
  14280. /**
  14281. * Update the menu based on the current state of its items.
  14282. *
  14283. * @param {Event} [event]
  14284. * An event that triggered this function to run.
  14285. *
  14286. * @listens TextTrackList#addtrack
  14287. * @listens TextTrackList#removetrack
  14288. * @listens TextTrackList#change
  14289. */
  14290. update(event) {
  14291. if (event && event.track && event.track.kind !== 'chapters') {
  14292. return;
  14293. }
  14294. const track = this.findChaptersTrack();
  14295. if (track !== this.track_) {
  14296. this.setTrack(track);
  14297. super.update();
  14298. } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
  14299. // Update the menu initially or if the number of cues has changed since set
  14300. super.update();
  14301. }
  14302. }
  14303. /**
  14304. * Set the currently selected track for the chapters button.
  14305. *
  14306. * @param {TextTrack} track
  14307. * The new track to select. Nothing will change if this is the currently selected
  14308. * track.
  14309. */
  14310. setTrack(track) {
  14311. if (this.track_ === track) {
  14312. return;
  14313. }
  14314. if (!this.updateHandler_) {
  14315. this.updateHandler_ = this.update.bind(this);
  14316. }
  14317. // here this.track_ refers to the old track instance
  14318. if (this.track_) {
  14319. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  14320. if (remoteTextTrackEl) {
  14321. remoteTextTrackEl.removeEventListener('load', this.updateHandler_);
  14322. }
  14323. this.track_.removeEventListener('cuechange', this.selectCurrentItem_);
  14324. this.track_ = null;
  14325. }
  14326. this.track_ = track;
  14327. // here this.track_ refers to the new track instance
  14328. if (this.track_) {
  14329. this.track_.mode = 'hidden';
  14330. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  14331. if (remoteTextTrackEl) {
  14332. remoteTextTrackEl.addEventListener('load', this.updateHandler_);
  14333. }
  14334. this.track_.addEventListener('cuechange', this.selectCurrentItem_);
  14335. }
  14336. }
  14337. /**
  14338. * Find the track object that is currently in use by this ChaptersButton
  14339. *
  14340. * @return {TextTrack|undefined}
  14341. * The current track or undefined if none was found.
  14342. */
  14343. findChaptersTrack() {
  14344. const tracks = this.player_.textTracks() || [];
  14345. for (let i = tracks.length - 1; i >= 0; i--) {
  14346. // We will always choose the last track as our chaptersTrack
  14347. const track = tracks[i];
  14348. if (track.kind === this.kind_) {
  14349. return track;
  14350. }
  14351. }
  14352. }
  14353. /**
  14354. * Get the caption for the ChaptersButton based on the track label. This will also
  14355. * use the current tracks localized kind as a fallback if a label does not exist.
  14356. *
  14357. * @return {string}
  14358. * The tracks current label or the localized track kind.
  14359. */
  14360. getMenuCaption() {
  14361. if (this.track_ && this.track_.label) {
  14362. return this.track_.label;
  14363. }
  14364. return this.localize(toTitleCase$1(this.kind_));
  14365. }
  14366. /**
  14367. * Create menu from chapter track
  14368. *
  14369. * @return { import('../../menu/menu').default }
  14370. * New menu for the chapter buttons
  14371. */
  14372. createMenu() {
  14373. this.options_.title = this.getMenuCaption();
  14374. return super.createMenu();
  14375. }
  14376. /**
  14377. * Create a menu item for each text track
  14378. *
  14379. * @return { import('./text-track-menu-item').default[] }
  14380. * Array of menu items
  14381. */
  14382. createItems() {
  14383. const items = [];
  14384. if (!this.track_) {
  14385. return items;
  14386. }
  14387. const cues = this.track_.cues;
  14388. if (!cues) {
  14389. return items;
  14390. }
  14391. for (let i = 0, l = cues.length; i < l; i++) {
  14392. const cue = cues[i];
  14393. const mi = new ChaptersTrackMenuItem(this.player_, {
  14394. track: this.track_,
  14395. cue
  14396. });
  14397. items.push(mi);
  14398. }
  14399. return items;
  14400. }
  14401. }
  14402. /**
  14403. * `kind` of TextTrack to look for to associate it with this menu.
  14404. *
  14405. * @type {string}
  14406. * @private
  14407. */
  14408. ChaptersButton.prototype.kind_ = 'chapters';
  14409. /**
  14410. * The text that should display over the `ChaptersButton`s controls. Added for localization.
  14411. *
  14412. * @type {string}
  14413. * @protected
  14414. */
  14415. ChaptersButton.prototype.controlText_ = 'Chapters';
  14416. Component$1.registerComponent('ChaptersButton', ChaptersButton);
  14417. /**
  14418. * @file descriptions-button.js
  14419. */
  14420. /**
  14421. * The button component for toggling and selecting descriptions
  14422. *
  14423. * @extends TextTrackButton
  14424. */
  14425. class DescriptionsButton extends TextTrackButton {
  14426. /**
  14427. * Creates an instance of this class.
  14428. *
  14429. * @param { import('../../player').default } player
  14430. * The `Player` that this class should be attached to.
  14431. *
  14432. * @param {Object} [options]
  14433. * The key/value store of player options.
  14434. *
  14435. * @param {Function} [ready]
  14436. * The function to call when this component is ready.
  14437. */
  14438. constructor(player, options, ready) {
  14439. super(player, options, ready);
  14440. const tracks = player.textTracks();
  14441. const changeHandler = bind_(this, this.handleTracksChange);
  14442. tracks.addEventListener('change', changeHandler);
  14443. this.on('dispose', function () {
  14444. tracks.removeEventListener('change', changeHandler);
  14445. });
  14446. }
  14447. /**
  14448. * Handle text track change
  14449. *
  14450. * @param {Event} event
  14451. * The event that caused this function to run
  14452. *
  14453. * @listens TextTrackList#change
  14454. */
  14455. handleTracksChange(event) {
  14456. const tracks = this.player().textTracks();
  14457. let disabled = false;
  14458. // Check whether a track of a different kind is showing
  14459. for (let i = 0, l = tracks.length; i < l; i++) {
  14460. const track = tracks[i];
  14461. if (track.kind !== this.kind_ && track.mode === 'showing') {
  14462. disabled = true;
  14463. break;
  14464. }
  14465. }
  14466. // If another track is showing, disable this menu button
  14467. if (disabled) {
  14468. this.disable();
  14469. } else {
  14470. this.enable();
  14471. }
  14472. }
  14473. /**
  14474. * Builds the default DOM `className`.
  14475. *
  14476. * @return {string}
  14477. * The DOM `className` for this object.
  14478. */
  14479. buildCSSClass() {
  14480. return `vjs-descriptions-button ${super.buildCSSClass()}`;
  14481. }
  14482. buildWrapperCSSClass() {
  14483. return `vjs-descriptions-button ${super.buildWrapperCSSClass()}`;
  14484. }
  14485. }
  14486. /**
  14487. * `kind` of TextTrack to look for to associate it with this menu.
  14488. *
  14489. * @type {string}
  14490. * @private
  14491. */
  14492. DescriptionsButton.prototype.kind_ = 'descriptions';
  14493. /**
  14494. * The text that should display over the `DescriptionsButton`s controls. Added for localization.
  14495. *
  14496. * @type {string}
  14497. * @protected
  14498. */
  14499. DescriptionsButton.prototype.controlText_ = 'Descriptions';
  14500. Component$1.registerComponent('DescriptionsButton', DescriptionsButton);
  14501. /**
  14502. * @file subtitles-button.js
  14503. */
  14504. /**
  14505. * The button component for toggling and selecting subtitles
  14506. *
  14507. * @extends TextTrackButton
  14508. */
  14509. class SubtitlesButton extends TextTrackButton {
  14510. /**
  14511. * Creates an instance of this class.
  14512. *
  14513. * @param { import('../../player').default } player
  14514. * The `Player` that this class should be attached to.
  14515. *
  14516. * @param {Object} [options]
  14517. * The key/value store of player options.
  14518. *
  14519. * @param {Function} [ready]
  14520. * The function to call when this component is ready.
  14521. */
  14522. constructor(player, options, ready) {
  14523. super(player, options, ready);
  14524. }
  14525. /**
  14526. * Builds the default DOM `className`.
  14527. *
  14528. * @return {string}
  14529. * The DOM `className` for this object.
  14530. */
  14531. buildCSSClass() {
  14532. return `vjs-subtitles-button ${super.buildCSSClass()}`;
  14533. }
  14534. buildWrapperCSSClass() {
  14535. return `vjs-subtitles-button ${super.buildWrapperCSSClass()}`;
  14536. }
  14537. }
  14538. /**
  14539. * `kind` of TextTrack to look for to associate it with this menu.
  14540. *
  14541. * @type {string}
  14542. * @private
  14543. */
  14544. SubtitlesButton.prototype.kind_ = 'subtitles';
  14545. /**
  14546. * The text that should display over the `SubtitlesButton`s controls. Added for localization.
  14547. *
  14548. * @type {string}
  14549. * @protected
  14550. */
  14551. SubtitlesButton.prototype.controlText_ = 'Subtitles';
  14552. Component$1.registerComponent('SubtitlesButton', SubtitlesButton);
  14553. /**
  14554. * @file caption-settings-menu-item.js
  14555. */
  14556. /**
  14557. * The menu item for caption track settings menu
  14558. *
  14559. * @extends TextTrackMenuItem
  14560. */
  14561. class CaptionSettingsMenuItem extends TextTrackMenuItem {
  14562. /**
  14563. * Creates an instance of this class.
  14564. *
  14565. * @param { import('../../player').default } player
  14566. * The `Player` that this class should be attached to.
  14567. *
  14568. * @param {Object} [options]
  14569. * The key/value store of player options.
  14570. */
  14571. constructor(player, options) {
  14572. options.track = {
  14573. player,
  14574. kind: options.kind,
  14575. label: options.kind + ' settings',
  14576. selectable: false,
  14577. default: false,
  14578. mode: 'disabled'
  14579. };
  14580. // CaptionSettingsMenuItem has no concept of 'selected'
  14581. options.selectable = false;
  14582. options.name = 'CaptionSettingsMenuItem';
  14583. super(player, options);
  14584. this.addClass('vjs-texttrack-settings');
  14585. this.controlText(', opens ' + options.kind + ' settings dialog');
  14586. }
  14587. /**
  14588. * This gets called when an `CaptionSettingsMenuItem` is "clicked". See
  14589. * {@link ClickableComponent} for more detailed information on what a click can be.
  14590. *
  14591. * @param {Event} [event]
  14592. * The `keydown`, `tap`, or `click` event that caused this function to be
  14593. * called.
  14594. *
  14595. * @listens tap
  14596. * @listens click
  14597. */
  14598. handleClick(event) {
  14599. this.player().getChild('textTrackSettings').open();
  14600. }
  14601. /**
  14602. * Update control text and label on languagechange
  14603. */
  14604. handleLanguagechange() {
  14605. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.kind + ' settings');
  14606. super.handleLanguagechange();
  14607. }
  14608. }
  14609. Component$1.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
  14610. /**
  14611. * @file captions-button.js
  14612. */
  14613. /**
  14614. * The button component for toggling and selecting captions
  14615. *
  14616. * @extends TextTrackButton
  14617. */
  14618. class CaptionsButton extends TextTrackButton {
  14619. /**
  14620. * Creates an instance of this class.
  14621. *
  14622. * @param { import('../../player').default } player
  14623. * The `Player` that this class should be attached to.
  14624. *
  14625. * @param {Object} [options]
  14626. * The key/value store of player options.
  14627. *
  14628. * @param {Function} [ready]
  14629. * The function to call when this component is ready.
  14630. */
  14631. constructor(player, options, ready) {
  14632. super(player, options, ready);
  14633. }
  14634. /**
  14635. * Builds the default DOM `className`.
  14636. *
  14637. * @return {string}
  14638. * The DOM `className` for this object.
  14639. */
  14640. buildCSSClass() {
  14641. return `vjs-captions-button ${super.buildCSSClass()}`;
  14642. }
  14643. buildWrapperCSSClass() {
  14644. return `vjs-captions-button ${super.buildWrapperCSSClass()}`;
  14645. }
  14646. /**
  14647. * Create caption menu items
  14648. *
  14649. * @return {CaptionSettingsMenuItem[]}
  14650. * The array of current menu items.
  14651. */
  14652. createItems() {
  14653. const items = [];
  14654. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  14655. items.push(new CaptionSettingsMenuItem(this.player_, {
  14656. kind: this.kind_
  14657. }));
  14658. this.hideThreshold_ += 1;
  14659. }
  14660. return super.createItems(items);
  14661. }
  14662. }
  14663. /**
  14664. * `kind` of TextTrack to look for to associate it with this menu.
  14665. *
  14666. * @type {string}
  14667. * @private
  14668. */
  14669. CaptionsButton.prototype.kind_ = 'captions';
  14670. /**
  14671. * The text that should display over the `CaptionsButton`s controls. Added for localization.
  14672. *
  14673. * @type {string}
  14674. * @protected
  14675. */
  14676. CaptionsButton.prototype.controlText_ = 'Captions';
  14677. Component$1.registerComponent('CaptionsButton', CaptionsButton);
  14678. /**
  14679. * @file subs-caps-menu-item.js
  14680. */
  14681. /**
  14682. * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
  14683. * in the SubsCapsMenu.
  14684. *
  14685. * @extends TextTrackMenuItem
  14686. */
  14687. class SubsCapsMenuItem extends TextTrackMenuItem {
  14688. createEl(type, props, attrs) {
  14689. const el = super.createEl(type, props, attrs);
  14690. const parentSpan = el.querySelector('.vjs-menu-item-text');
  14691. if (this.options_.track.kind === 'captions') {
  14692. parentSpan.appendChild(createEl('span', {
  14693. className: 'vjs-icon-placeholder'
  14694. }, {
  14695. 'aria-hidden': true
  14696. }));
  14697. parentSpan.appendChild(createEl('span', {
  14698. className: 'vjs-control-text',
  14699. // space added as the text will visually flow with the
  14700. // label
  14701. textContent: ` ${this.localize('Captions')}`
  14702. }));
  14703. }
  14704. return el;
  14705. }
  14706. }
  14707. Component$1.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);
  14708. /**
  14709. * @file sub-caps-button.js
  14710. */
  14711. /**
  14712. * The button component for toggling and selecting captions and/or subtitles
  14713. *
  14714. * @extends TextTrackButton
  14715. */
  14716. class SubsCapsButton extends TextTrackButton {
  14717. /**
  14718. * Creates an instance of this class.
  14719. *
  14720. * @param { import('../../player').default } player
  14721. * The `Player` that this class should be attached to.
  14722. *
  14723. * @param {Object} [options]
  14724. * The key/value store of player options.
  14725. *
  14726. * @param {Function} [ready]
  14727. * The function to call when this component is ready.
  14728. */
  14729. constructor(player, options = {}) {
  14730. super(player, options);
  14731. // Although North America uses "captions" in most cases for
  14732. // "captions and subtitles" other locales use "subtitles"
  14733. this.label_ = 'subtitles';
  14734. if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(this.player_.language_) > -1) {
  14735. this.label_ = 'captions';
  14736. }
  14737. this.menuButton_.controlText(toTitleCase$1(this.label_));
  14738. }
  14739. /**
  14740. * Builds the default DOM `className`.
  14741. *
  14742. * @return {string}
  14743. * The DOM `className` for this object.
  14744. */
  14745. buildCSSClass() {
  14746. return `vjs-subs-caps-button ${super.buildCSSClass()}`;
  14747. }
  14748. buildWrapperCSSClass() {
  14749. return `vjs-subs-caps-button ${super.buildWrapperCSSClass()}`;
  14750. }
  14751. /**
  14752. * Create caption/subtitles menu items
  14753. *
  14754. * @return {CaptionSettingsMenuItem[]}
  14755. * The array of current menu items.
  14756. */
  14757. createItems() {
  14758. let items = [];
  14759. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  14760. items.push(new CaptionSettingsMenuItem(this.player_, {
  14761. kind: this.label_
  14762. }));
  14763. this.hideThreshold_ += 1;
  14764. }
  14765. items = super.createItems(items, SubsCapsMenuItem);
  14766. return items;
  14767. }
  14768. }
  14769. /**
  14770. * `kind`s of TextTrack to look for to associate it with this menu.
  14771. *
  14772. * @type {array}
  14773. * @private
  14774. */
  14775. SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];
  14776. /**
  14777. * The text that should display over the `SubsCapsButton`s controls.
  14778. *
  14779. *
  14780. * @type {string}
  14781. * @protected
  14782. */
  14783. SubsCapsButton.prototype.controlText_ = 'Subtitles';
  14784. Component$1.registerComponent('SubsCapsButton', SubsCapsButton);
  14785. /**
  14786. * @file audio-track-menu-item.js
  14787. */
  14788. /**
  14789. * An {@link AudioTrack} {@link MenuItem}
  14790. *
  14791. * @extends MenuItem
  14792. */
  14793. class AudioTrackMenuItem extends MenuItem {
  14794. /**
  14795. * Creates an instance of this class.
  14796. *
  14797. * @param { import('../../player').default } player
  14798. * The `Player` that this class should be attached to.
  14799. *
  14800. * @param {Object} [options]
  14801. * The key/value store of player options.
  14802. */
  14803. constructor(player, options) {
  14804. const track = options.track;
  14805. const tracks = player.audioTracks();
  14806. // Modify options for parent MenuItem class's init.
  14807. options.label = track.label || track.language || 'Unknown';
  14808. options.selected = track.enabled;
  14809. super(player, options);
  14810. this.track = track;
  14811. this.addClass(`vjs-${track.kind}-menu-item`);
  14812. const changeHandler = (...args) => {
  14813. this.handleTracksChange.apply(this, args);
  14814. };
  14815. tracks.addEventListener('change', changeHandler);
  14816. this.on('dispose', () => {
  14817. tracks.removeEventListener('change', changeHandler);
  14818. });
  14819. }
  14820. createEl(type, props, attrs) {
  14821. const el = super.createEl(type, props, attrs);
  14822. const parentSpan = el.querySelector('.vjs-menu-item-text');
  14823. if (this.options_.track.kind === 'main-desc') {
  14824. parentSpan.appendChild(createEl('span', {
  14825. className: 'vjs-icon-placeholder'
  14826. }, {
  14827. 'aria-hidden': true
  14828. }));
  14829. parentSpan.appendChild(createEl('span', {
  14830. className: 'vjs-control-text',
  14831. textContent: ' ' + this.localize('Descriptions')
  14832. }));
  14833. }
  14834. return el;
  14835. }
  14836. /**
  14837. * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent}
  14838. * for more detailed information on what a click can be.
  14839. *
  14840. * @param {Event} [event]
  14841. * The `keydown`, `tap`, or `click` event that caused this function to be
  14842. * called.
  14843. *
  14844. * @listens tap
  14845. * @listens click
  14846. */
  14847. handleClick(event) {
  14848. super.handleClick(event);
  14849. // the audio track list will automatically toggle other tracks
  14850. // off for us.
  14851. this.track.enabled = true;
  14852. // when native audio tracks are used, we want to make sure that other tracks are turned off
  14853. if (this.player_.tech_.featuresNativeAudioTracks) {
  14854. const tracks = this.player_.audioTracks();
  14855. for (let i = 0; i < tracks.length; i++) {
  14856. const track = tracks[i];
  14857. // skip the current track since we enabled it above
  14858. if (track === this.track) {
  14859. continue;
  14860. }
  14861. track.enabled = track === this.track;
  14862. }
  14863. }
  14864. }
  14865. /**
  14866. * Handle any {@link AudioTrack} change.
  14867. *
  14868. * @param {Event} [event]
  14869. * The {@link AudioTrackList#change} event that caused this to run.
  14870. *
  14871. * @listens AudioTrackList#change
  14872. */
  14873. handleTracksChange(event) {
  14874. this.selected(this.track.enabled);
  14875. }
  14876. }
  14877. Component$1.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);
  14878. /**
  14879. * @file audio-track-button.js
  14880. */
  14881. /**
  14882. * The base class for buttons that toggle specific {@link AudioTrack} types.
  14883. *
  14884. * @extends TrackButton
  14885. */
  14886. class AudioTrackButton extends TrackButton {
  14887. /**
  14888. * Creates an instance of this class.
  14889. *
  14890. * @param {Player} player
  14891. * The `Player` that this class should be attached to.
  14892. *
  14893. * @param {Object} [options={}]
  14894. * The key/value store of player options.
  14895. */
  14896. constructor(player, options = {}) {
  14897. options.tracks = player.audioTracks();
  14898. super(player, options);
  14899. }
  14900. /**
  14901. * Builds the default DOM `className`.
  14902. *
  14903. * @return {string}
  14904. * The DOM `className` for this object.
  14905. */
  14906. buildCSSClass() {
  14907. return `vjs-audio-button ${super.buildCSSClass()}`;
  14908. }
  14909. buildWrapperCSSClass() {
  14910. return `vjs-audio-button ${super.buildWrapperCSSClass()}`;
  14911. }
  14912. /**
  14913. * Create a menu item for each audio track
  14914. *
  14915. * @param {AudioTrackMenuItem[]} [items=[]]
  14916. * An array of existing menu items to use.
  14917. *
  14918. * @return {AudioTrackMenuItem[]}
  14919. * An array of menu items
  14920. */
  14921. createItems(items = []) {
  14922. // if there's only one audio track, there no point in showing it
  14923. this.hideThreshold_ = 1;
  14924. const tracks = this.player_.audioTracks();
  14925. for (let i = 0; i < tracks.length; i++) {
  14926. const track = tracks[i];
  14927. items.push(new AudioTrackMenuItem(this.player_, {
  14928. track,
  14929. // MenuItem is selectable
  14930. selectable: true,
  14931. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14932. multiSelectable: false
  14933. }));
  14934. }
  14935. return items;
  14936. }
  14937. }
  14938. /**
  14939. * The text that should display over the `AudioTrackButton`s controls. Added for localization.
  14940. *
  14941. * @type {string}
  14942. * @protected
  14943. */
  14944. AudioTrackButton.prototype.controlText_ = 'Audio Track';
  14945. Component$1.registerComponent('AudioTrackButton', AudioTrackButton);
  14946. /**
  14947. * @file playback-rate-menu-item.js
  14948. */
  14949. /**
  14950. * The specific menu item type for selecting a playback rate.
  14951. *
  14952. * @extends MenuItem
  14953. */
  14954. class PlaybackRateMenuItem extends MenuItem {
  14955. /**
  14956. * Creates an instance of this class.
  14957. *
  14958. * @param { import('../../player').default } player
  14959. * The `Player` that this class should be attached to.
  14960. *
  14961. * @param {Object} [options]
  14962. * The key/value store of player options.
  14963. */
  14964. constructor(player, options) {
  14965. const label = options.rate;
  14966. const rate = parseFloat(label, 10);
  14967. // Modify options for parent MenuItem class's init.
  14968. options.label = label;
  14969. options.selected = rate === player.playbackRate();
  14970. options.selectable = true;
  14971. options.multiSelectable = false;
  14972. super(player, options);
  14973. this.label = label;
  14974. this.rate = rate;
  14975. this.on(player, 'ratechange', e => this.update(e));
  14976. }
  14977. /**
  14978. * This gets called when an `PlaybackRateMenuItem` is "clicked". See
  14979. * {@link ClickableComponent} for more detailed information on what a click can be.
  14980. *
  14981. * @param {Event} [event]
  14982. * The `keydown`, `tap`, or `click` event that caused this function to be
  14983. * called.
  14984. *
  14985. * @listens tap
  14986. * @listens click
  14987. */
  14988. handleClick(event) {
  14989. super.handleClick();
  14990. this.player().playbackRate(this.rate);
  14991. }
  14992. /**
  14993. * Update the PlaybackRateMenuItem when the playbackrate changes.
  14994. *
  14995. * @param {Event} [event]
  14996. * The `ratechange` event that caused this function to run.
  14997. *
  14998. * @listens Player#ratechange
  14999. */
  15000. update(event) {
  15001. this.selected(this.player().playbackRate() === this.rate);
  15002. }
  15003. }
  15004. /**
  15005. * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.
  15006. *
  15007. * @type {string}
  15008. * @private
  15009. */
  15010. PlaybackRateMenuItem.prototype.contentElType = 'button';
  15011. Component$1.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
  15012. /**
  15013. * @file playback-rate-menu-button.js
  15014. */
  15015. /**
  15016. * The component for controlling the playback rate.
  15017. *
  15018. * @extends MenuButton
  15019. */
  15020. class PlaybackRateMenuButton extends MenuButton {
  15021. /**
  15022. * Creates an instance of this class.
  15023. *
  15024. * @param { import('../../player').default } player
  15025. * The `Player` that this class should be attached to.
  15026. *
  15027. * @param {Object} [options]
  15028. * The key/value store of player options.
  15029. */
  15030. constructor(player, options) {
  15031. super(player, options);
  15032. this.menuButton_.el_.setAttribute('aria-describedby', this.labelElId_);
  15033. this.updateVisibility();
  15034. this.updateLabel();
  15035. this.on(player, 'loadstart', e => this.updateVisibility(e));
  15036. this.on(player, 'ratechange', e => this.updateLabel(e));
  15037. this.on(player, 'playbackrateschange', e => this.handlePlaybackRateschange(e));
  15038. }
  15039. /**
  15040. * Create the `Component`'s DOM element
  15041. *
  15042. * @return {Element}
  15043. * The element that was created.
  15044. */
  15045. createEl() {
  15046. const el = super.createEl();
  15047. this.labelElId_ = 'vjs-playback-rate-value-label-' + this.id_;
  15048. this.labelEl_ = createEl('div', {
  15049. className: 'vjs-playback-rate-value',
  15050. id: this.labelElId_,
  15051. textContent: '1x'
  15052. });
  15053. el.appendChild(this.labelEl_);
  15054. return el;
  15055. }
  15056. dispose() {
  15057. this.labelEl_ = null;
  15058. super.dispose();
  15059. }
  15060. /**
  15061. * Builds the default DOM `className`.
  15062. *
  15063. * @return {string}
  15064. * The DOM `className` for this object.
  15065. */
  15066. buildCSSClass() {
  15067. return `vjs-playback-rate ${super.buildCSSClass()}`;
  15068. }
  15069. buildWrapperCSSClass() {
  15070. return `vjs-playback-rate ${super.buildWrapperCSSClass()}`;
  15071. }
  15072. /**
  15073. * Create the list of menu items. Specific to each subclass.
  15074. *
  15075. */
  15076. createItems() {
  15077. const rates = this.playbackRates();
  15078. const items = [];
  15079. for (let i = rates.length - 1; i >= 0; i--) {
  15080. items.push(new PlaybackRateMenuItem(this.player(), {
  15081. rate: rates[i] + 'x'
  15082. }));
  15083. }
  15084. return items;
  15085. }
  15086. /**
  15087. * On playbackrateschange, update the menu to account for the new items.
  15088. *
  15089. * @listens Player#playbackrateschange
  15090. */
  15091. handlePlaybackRateschange(event) {
  15092. this.update();
  15093. }
  15094. /**
  15095. * Get possible playback rates
  15096. *
  15097. * @return {Array}
  15098. * All possible playback rates
  15099. */
  15100. playbackRates() {
  15101. const player = this.player();
  15102. return player.playbackRates && player.playbackRates() || [];
  15103. }
  15104. /**
  15105. * Get whether playback rates is supported by the tech
  15106. * and an array of playback rates exists
  15107. *
  15108. * @return {boolean}
  15109. * Whether changing playback rate is supported
  15110. */
  15111. playbackRateSupported() {
  15112. return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
  15113. }
  15114. /**
  15115. * Hide playback rate controls when they're no playback rate options to select
  15116. *
  15117. * @param {Event} [event]
  15118. * The event that caused this function to run.
  15119. *
  15120. * @listens Player#loadstart
  15121. */
  15122. updateVisibility(event) {
  15123. if (this.playbackRateSupported()) {
  15124. this.removeClass('vjs-hidden');
  15125. } else {
  15126. this.addClass('vjs-hidden');
  15127. }
  15128. }
  15129. /**
  15130. * Update button label when rate changed
  15131. *
  15132. * @param {Event} [event]
  15133. * The event that caused this function to run.
  15134. *
  15135. * @listens Player#ratechange
  15136. */
  15137. updateLabel(event) {
  15138. if (this.playbackRateSupported()) {
  15139. this.labelEl_.textContent = this.player().playbackRate() + 'x';
  15140. }
  15141. }
  15142. }
  15143. /**
  15144. * The text that should display over the `PlaybackRateMenuButton`s controls.
  15145. *
  15146. * Added for localization.
  15147. *
  15148. * @type {string}
  15149. * @protected
  15150. */
  15151. PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
  15152. Component$1.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
  15153. /**
  15154. * @file spacer.js
  15155. */
  15156. /**
  15157. * Just an empty spacer element that can be used as an append point for plugins, etc.
  15158. * Also can be used to create space between elements when necessary.
  15159. *
  15160. * @extends Component
  15161. */
  15162. class Spacer extends Component$1 {
  15163. /**
  15164. * Builds the default DOM `className`.
  15165. *
  15166. * @return {string}
  15167. * The DOM `className` for this object.
  15168. */
  15169. buildCSSClass() {
  15170. return `vjs-spacer ${super.buildCSSClass()}`;
  15171. }
  15172. /**
  15173. * Create the `Component`'s DOM element
  15174. *
  15175. * @return {Element}
  15176. * The element that was created.
  15177. */
  15178. createEl(tag = 'div', props = {}, attributes = {}) {
  15179. if (!props.className) {
  15180. props.className = this.buildCSSClass();
  15181. }
  15182. return super.createEl(tag, props, attributes);
  15183. }
  15184. }
  15185. Component$1.registerComponent('Spacer', Spacer);
  15186. /**
  15187. * @file custom-control-spacer.js
  15188. */
  15189. /**
  15190. * Spacer specifically meant to be used as an insertion point for new plugins, etc.
  15191. *
  15192. * @extends Spacer
  15193. */
  15194. class CustomControlSpacer extends Spacer {
  15195. /**
  15196. * Builds the default DOM `className`.
  15197. *
  15198. * @return {string}
  15199. * The DOM `className` for this object.
  15200. */
  15201. buildCSSClass() {
  15202. return `vjs-custom-control-spacer ${super.buildCSSClass()}`;
  15203. }
  15204. /**
  15205. * Create the `Component`'s DOM element
  15206. *
  15207. * @return {Element}
  15208. * The element that was created.
  15209. */
  15210. createEl() {
  15211. return super.createEl('div', {
  15212. className: this.buildCSSClass(),
  15213. // No-flex/table-cell mode requires there be some content
  15214. // in the cell to fill the remaining space of the table.
  15215. textContent: '\u00a0'
  15216. });
  15217. }
  15218. }
  15219. Component$1.registerComponent('CustomControlSpacer', CustomControlSpacer);
  15220. /**
  15221. * @file control-bar.js
  15222. */
  15223. /**
  15224. * Container of main controls.
  15225. *
  15226. * @extends Component
  15227. */
  15228. class ControlBar extends Component$1 {
  15229. /**
  15230. * Create the `Component`'s DOM element
  15231. *
  15232. * @return {Element}
  15233. * The element that was created.
  15234. */
  15235. createEl() {
  15236. return super.createEl('div', {
  15237. className: 'vjs-control-bar',
  15238. dir: 'ltr'
  15239. });
  15240. }
  15241. }
  15242. /**
  15243. * Default options for `ControlBar`
  15244. *
  15245. * @type {Object}
  15246. * @private
  15247. */
  15248. ControlBar.prototype.options_ = {
  15249. children: ['playToggle', 'skipBackward', 'skipForward', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'fullscreenToggle']
  15250. };
  15251. if ('exitPictureInPicture' in document) {
  15252. ControlBar.prototype.options_.children.splice(ControlBar.prototype.options_.children.length - 1, 0, 'pictureInPictureToggle');
  15253. }
  15254. Component$1.registerComponent('ControlBar', ControlBar);
  15255. /**
  15256. * @file error-display.js
  15257. */
  15258. /**
  15259. * A display that indicates an error has occurred. This means that the video
  15260. * is unplayable.
  15261. *
  15262. * @extends ModalDialog
  15263. */
  15264. class ErrorDisplay extends ModalDialog {
  15265. /**
  15266. * Creates an instance of this class.
  15267. *
  15268. * @param { import('./player').default } player
  15269. * The `Player` that this class should be attached to.
  15270. *
  15271. * @param {Object} [options]
  15272. * The key/value store of player options.
  15273. */
  15274. constructor(player, options) {
  15275. super(player, options);
  15276. this.on(player, 'error', e => this.open(e));
  15277. }
  15278. /**
  15279. * Builds the default DOM `className`.
  15280. *
  15281. * @return {string}
  15282. * The DOM `className` for this object.
  15283. *
  15284. * @deprecated Since version 5.
  15285. */
  15286. buildCSSClass() {
  15287. return `vjs-error-display ${super.buildCSSClass()}`;
  15288. }
  15289. /**
  15290. * Gets the localized error message based on the `Player`s error.
  15291. *
  15292. * @return {string}
  15293. * The `Player`s error message localized or an empty string.
  15294. */
  15295. content() {
  15296. const error = this.player().error();
  15297. return error ? this.localize(error.message) : '';
  15298. }
  15299. }
  15300. /**
  15301. * The default options for an `ErrorDisplay`.
  15302. *
  15303. * @private
  15304. */
  15305. ErrorDisplay.prototype.options_ = Object.assign({}, ModalDialog.prototype.options_, {
  15306. pauseOnOpen: false,
  15307. fillAlways: true,
  15308. temporary: false,
  15309. uncloseable: true
  15310. });
  15311. Component$1.registerComponent('ErrorDisplay', ErrorDisplay);
  15312. /**
  15313. * @file text-track-settings.js
  15314. */
  15315. const LOCAL_STORAGE_KEY$1 = 'vjs-text-track-settings';
  15316. const COLOR_BLACK = ['#000', 'Black'];
  15317. const COLOR_BLUE = ['#00F', 'Blue'];
  15318. const COLOR_CYAN = ['#0FF', 'Cyan'];
  15319. const COLOR_GREEN = ['#0F0', 'Green'];
  15320. const COLOR_MAGENTA = ['#F0F', 'Magenta'];
  15321. const COLOR_RED = ['#F00', 'Red'];
  15322. const COLOR_WHITE = ['#FFF', 'White'];
  15323. const COLOR_YELLOW = ['#FF0', 'Yellow'];
  15324. const OPACITY_OPAQUE = ['1', 'Opaque'];
  15325. const OPACITY_SEMI = ['0.5', 'Semi-Transparent'];
  15326. const OPACITY_TRANS = ['0', 'Transparent'];
  15327. // Configuration for the various <select> elements in the DOM of this component.
  15328. //
  15329. // Possible keys include:
  15330. //
  15331. // `default`:
  15332. // The default option index. Only needs to be provided if not zero.
  15333. // `parser`:
  15334. // A function which is used to parse the value from the selected option in
  15335. // a customized way.
  15336. // `selector`:
  15337. // The selector used to find the associated <select> element.
  15338. const selectConfigs = {
  15339. backgroundColor: {
  15340. selector: '.vjs-bg-color > select',
  15341. id: 'captions-background-color-%s',
  15342. label: 'Color',
  15343. options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  15344. },
  15345. backgroundOpacity: {
  15346. selector: '.vjs-bg-opacity > select',
  15347. id: 'captions-background-opacity-%s',
  15348. label: 'Opacity',
  15349. options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS]
  15350. },
  15351. color: {
  15352. selector: '.vjs-text-color > select',
  15353. id: 'captions-foreground-color-%s',
  15354. label: 'Color',
  15355. options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  15356. },
  15357. edgeStyle: {
  15358. selector: '.vjs-edge-style > select',
  15359. id: '%s',
  15360. label: 'Text Edge Style',
  15361. options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']]
  15362. },
  15363. fontFamily: {
  15364. selector: '.vjs-font-family > select',
  15365. id: 'captions-font-family-%s',
  15366. label: 'Font Family',
  15367. options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]
  15368. },
  15369. fontPercent: {
  15370. selector: '.vjs-font-percent > select',
  15371. id: 'captions-font-size-%s',
  15372. label: 'Font Size',
  15373. 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%']],
  15374. default: 2,
  15375. parser: v => v === '1.00' ? null : Number(v)
  15376. },
  15377. textOpacity: {
  15378. selector: '.vjs-text-opacity > select',
  15379. id: 'captions-foreground-opacity-%s',
  15380. label: 'Opacity',
  15381. options: [OPACITY_OPAQUE, OPACITY_SEMI]
  15382. },
  15383. // Options for this object are defined below.
  15384. windowColor: {
  15385. selector: '.vjs-window-color > select',
  15386. id: 'captions-window-color-%s',
  15387. label: 'Color'
  15388. },
  15389. // Options for this object are defined below.
  15390. windowOpacity: {
  15391. selector: '.vjs-window-opacity > select',
  15392. id: 'captions-window-opacity-%s',
  15393. label: 'Opacity',
  15394. options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE]
  15395. }
  15396. };
  15397. selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
  15398. /**
  15399. * Get the actual value of an option.
  15400. *
  15401. * @param {string} value
  15402. * The value to get
  15403. *
  15404. * @param {Function} [parser]
  15405. * Optional function to adjust the value.
  15406. *
  15407. * @return {*}
  15408. * - Will be `undefined` if no value exists
  15409. * - Will be `undefined` if the given value is "none".
  15410. * - Will be the actual value otherwise.
  15411. *
  15412. * @private
  15413. */
  15414. function parseOptionValue(value, parser) {
  15415. if (parser) {
  15416. value = parser(value);
  15417. }
  15418. if (value && value !== 'none') {
  15419. return value;
  15420. }
  15421. }
  15422. /**
  15423. * Gets the value of the selected <option> element within a <select> element.
  15424. *
  15425. * @param {Element} el
  15426. * the element to look in
  15427. *
  15428. * @param {Function} [parser]
  15429. * Optional function to adjust the value.
  15430. *
  15431. * @return {*}
  15432. * - Will be `undefined` if no value exists
  15433. * - Will be `undefined` if the given value is "none".
  15434. * - Will be the actual value otherwise.
  15435. *
  15436. * @private
  15437. */
  15438. function getSelectedOptionValue(el, parser) {
  15439. const value = el.options[el.options.selectedIndex].value;
  15440. return parseOptionValue(value, parser);
  15441. }
  15442. /**
  15443. * Sets the selected <option> element within a <select> element based on a
  15444. * given value.
  15445. *
  15446. * @param {Element} el
  15447. * The element to look in.
  15448. *
  15449. * @param {string} value
  15450. * the property to look on.
  15451. *
  15452. * @param {Function} [parser]
  15453. * Optional function to adjust the value before comparing.
  15454. *
  15455. * @private
  15456. */
  15457. function setSelectedOption(el, value, parser) {
  15458. if (!value) {
  15459. return;
  15460. }
  15461. for (let i = 0; i < el.options.length; i++) {
  15462. if (parseOptionValue(el.options[i].value, parser) === value) {
  15463. el.selectedIndex = i;
  15464. break;
  15465. }
  15466. }
  15467. }
  15468. /**
  15469. * Manipulate Text Tracks settings.
  15470. *
  15471. * @extends ModalDialog
  15472. */
  15473. class TextTrackSettings extends ModalDialog {
  15474. /**
  15475. * Creates an instance of this class.
  15476. *
  15477. * @param { import('../player').default } player
  15478. * The `Player` that this class should be attached to.
  15479. *
  15480. * @param {Object} [options]
  15481. * The key/value store of player options.
  15482. */
  15483. constructor(player, options) {
  15484. options.temporary = false;
  15485. super(player, options);
  15486. this.updateDisplay = this.updateDisplay.bind(this);
  15487. // fill the modal and pretend we have opened it
  15488. this.fill();
  15489. this.hasBeenOpened_ = this.hasBeenFilled_ = true;
  15490. this.endDialog = createEl('p', {
  15491. className: 'vjs-control-text',
  15492. textContent: this.localize('End of dialog window.')
  15493. });
  15494. this.el().appendChild(this.endDialog);
  15495. this.setDefaults();
  15496. // Grab `persistTextTrackSettings` from the player options if not passed in child options
  15497. if (options.persistTextTrackSettings === undefined) {
  15498. this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings;
  15499. }
  15500. this.on(this.$('.vjs-done-button'), 'click', () => {
  15501. this.saveSettings();
  15502. this.close();
  15503. });
  15504. this.on(this.$('.vjs-default-button'), 'click', () => {
  15505. this.setDefaults();
  15506. this.updateDisplay();
  15507. });
  15508. each(selectConfigs, config => {
  15509. this.on(this.$(config.selector), 'change', this.updateDisplay);
  15510. });
  15511. if (this.options_.persistTextTrackSettings) {
  15512. this.restoreSettings();
  15513. }
  15514. }
  15515. dispose() {
  15516. this.endDialog = null;
  15517. super.dispose();
  15518. }
  15519. /**
  15520. * Create a <select> element with configured options.
  15521. *
  15522. * @param {string} key
  15523. * Configuration key to use during creation.
  15524. *
  15525. * @return {string}
  15526. * An HTML string.
  15527. *
  15528. * @private
  15529. */
  15530. createElSelect_(key, legendId = '', type = 'label') {
  15531. const config = selectConfigs[key];
  15532. const id = config.id.replace('%s', this.id_);
  15533. const selectLabelledbyIds = [legendId, id].join(' ').trim();
  15534. return [`<${type} id="${id}" class="${type === 'label' ? 'vjs-label' : ''}">`, this.localize(config.label), `</${type}>`, `<select aria-labelledby="${selectLabelledbyIds}">`].concat(config.options.map(o => {
  15535. const optionId = id + '-' + o[1].replace(/\W+/g, '');
  15536. return [`<option id="${optionId}" value="${o[0]}" `, `aria-labelledby="${selectLabelledbyIds} ${optionId}">`, this.localize(o[1]), '</option>'].join('');
  15537. })).concat('</select>').join('');
  15538. }
  15539. /**
  15540. * Create foreground color element for the component
  15541. *
  15542. * @return {string}
  15543. * An HTML string.
  15544. *
  15545. * @private
  15546. */
  15547. createElFgColor_() {
  15548. const legendId = `captions-text-legend-${this.id_}`;
  15549. 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('');
  15550. }
  15551. /**
  15552. * Create background color element for the component
  15553. *
  15554. * @return {string}
  15555. * An HTML string.
  15556. *
  15557. * @private
  15558. */
  15559. createElBgColor_() {
  15560. const legendId = `captions-background-${this.id_}`;
  15561. 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('');
  15562. }
  15563. /**
  15564. * Create window color element for the component
  15565. *
  15566. * @return {string}
  15567. * An HTML string.
  15568. *
  15569. * @private
  15570. */
  15571. createElWinColor_() {
  15572. const legendId = `captions-window-${this.id_}`;
  15573. 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('');
  15574. }
  15575. /**
  15576. * Create color elements for the component
  15577. *
  15578. * @return {Element}
  15579. * The element that was created
  15580. *
  15581. * @private
  15582. */
  15583. createElColors_() {
  15584. return createEl('div', {
  15585. className: 'vjs-track-settings-colors',
  15586. innerHTML: [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()].join('')
  15587. });
  15588. }
  15589. /**
  15590. * Create font elements for the component
  15591. *
  15592. * @return {Element}
  15593. * The element that was created.
  15594. *
  15595. * @private
  15596. */
  15597. createElFont_() {
  15598. return createEl('div', {
  15599. className: 'vjs-track-settings-font',
  15600. 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('')
  15601. });
  15602. }
  15603. /**
  15604. * Create controls for the component
  15605. *
  15606. * @return {Element}
  15607. * The element that was created.
  15608. *
  15609. * @private
  15610. */
  15611. createElControls_() {
  15612. const defaultsDescription = this.localize('restore all settings to the default values');
  15613. return createEl('div', {
  15614. className: 'vjs-track-settings-controls',
  15615. 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('')
  15616. });
  15617. }
  15618. content() {
  15619. return [this.createElColors_(), this.createElFont_(), this.createElControls_()];
  15620. }
  15621. label() {
  15622. return this.localize('Caption Settings Dialog');
  15623. }
  15624. description() {
  15625. return this.localize('Beginning of dialog window. Escape will cancel and close the window.');
  15626. }
  15627. buildCSSClass() {
  15628. return super.buildCSSClass() + ' vjs-text-track-settings';
  15629. }
  15630. /**
  15631. * Gets an object of text track settings (or null).
  15632. *
  15633. * @return {Object}
  15634. * An object with config values parsed from the DOM or localStorage.
  15635. */
  15636. getValues() {
  15637. return reduce(selectConfigs, (accum, config, key) => {
  15638. const value = getSelectedOptionValue(this.$(config.selector), config.parser);
  15639. if (value !== undefined) {
  15640. accum[key] = value;
  15641. }
  15642. return accum;
  15643. }, {});
  15644. }
  15645. /**
  15646. * Sets text track settings from an object of values.
  15647. *
  15648. * @param {Object} values
  15649. * An object with config values parsed from the DOM or localStorage.
  15650. */
  15651. setValues(values) {
  15652. each(selectConfigs, (config, key) => {
  15653. setSelectedOption(this.$(config.selector), values[key], config.parser);
  15654. });
  15655. }
  15656. /**
  15657. * Sets all `<select>` elements to their default values.
  15658. */
  15659. setDefaults() {
  15660. each(selectConfigs, config => {
  15661. const index = config.hasOwnProperty('default') ? config.default : 0;
  15662. this.$(config.selector).selectedIndex = index;
  15663. });
  15664. }
  15665. /**
  15666. * Restore texttrack settings from localStorage
  15667. */
  15668. restoreSettings() {
  15669. let values;
  15670. try {
  15671. values = JSON.parse(window$1.localStorage.getItem(LOCAL_STORAGE_KEY$1));
  15672. } catch (err) {
  15673. log$1.warn(err);
  15674. }
  15675. if (values) {
  15676. this.setValues(values);
  15677. }
  15678. }
  15679. /**
  15680. * Save text track settings to localStorage
  15681. */
  15682. saveSettings() {
  15683. if (!this.options_.persistTextTrackSettings) {
  15684. return;
  15685. }
  15686. const values = this.getValues();
  15687. try {
  15688. if (Object.keys(values).length) {
  15689. window$1.localStorage.setItem(LOCAL_STORAGE_KEY$1, JSON.stringify(values));
  15690. } else {
  15691. window$1.localStorage.removeItem(LOCAL_STORAGE_KEY$1);
  15692. }
  15693. } catch (err) {
  15694. log$1.warn(err);
  15695. }
  15696. }
  15697. /**
  15698. * Update display of text track settings
  15699. */
  15700. updateDisplay() {
  15701. const ttDisplay = this.player_.getChild('textTrackDisplay');
  15702. if (ttDisplay) {
  15703. ttDisplay.updateDisplay();
  15704. }
  15705. }
  15706. /**
  15707. * conditionally blur the element and refocus the captions button
  15708. *
  15709. * @private
  15710. */
  15711. conditionalBlur_() {
  15712. this.previouslyActiveEl_ = null;
  15713. const cb = this.player_.controlBar;
  15714. const subsCapsBtn = cb && cb.subsCapsButton;
  15715. const ccBtn = cb && cb.captionsButton;
  15716. if (subsCapsBtn) {
  15717. subsCapsBtn.focus();
  15718. } else if (ccBtn) {
  15719. ccBtn.focus();
  15720. }
  15721. }
  15722. /**
  15723. * Repopulate dialog with new localizations on languagechange
  15724. */
  15725. handleLanguagechange() {
  15726. this.fill();
  15727. }
  15728. }
  15729. Component$1.registerComponent('TextTrackSettings', TextTrackSettings);
  15730. /**
  15731. * @file resize-manager.js
  15732. */
  15733. /**
  15734. * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
  15735. *
  15736. * 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}.
  15737. *
  15738. * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
  15739. * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
  15740. *
  15741. * @example <caption>How to disable the resize manager</caption>
  15742. * const player = videojs('#vid', {
  15743. * resizeManager: false
  15744. * });
  15745. *
  15746. * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
  15747. *
  15748. * @extends Component
  15749. */
  15750. class ResizeManager extends Component$1 {
  15751. /**
  15752. * Create the ResizeManager.
  15753. *
  15754. * @param {Object} player
  15755. * The `Player` that this class should be attached to.
  15756. *
  15757. * @param {Object} [options]
  15758. * The key/value store of ResizeManager options.
  15759. *
  15760. * @param {Object} [options.ResizeObserver]
  15761. * A polyfill for ResizeObserver can be passed in here.
  15762. * If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
  15763. */
  15764. constructor(player, options) {
  15765. let RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window$1.ResizeObserver;
  15766. // if `null` was passed, we want to disable the ResizeObserver
  15767. if (options.ResizeObserver === null) {
  15768. RESIZE_OBSERVER_AVAILABLE = false;
  15769. }
  15770. // Only create an element when ResizeObserver isn't available
  15771. const options_ = merge$1({
  15772. createEl: !RESIZE_OBSERVER_AVAILABLE,
  15773. reportTouchActivity: false
  15774. }, options);
  15775. super(player, options_);
  15776. this.ResizeObserver = options.ResizeObserver || window$1.ResizeObserver;
  15777. this.loadListener_ = null;
  15778. this.resizeObserver_ = null;
  15779. this.debouncedHandler_ = debounce(() => {
  15780. this.resizeHandler();
  15781. }, 100, false, this);
  15782. if (RESIZE_OBSERVER_AVAILABLE) {
  15783. this.resizeObserver_ = new this.ResizeObserver(this.debouncedHandler_);
  15784. this.resizeObserver_.observe(player.el());
  15785. } else {
  15786. this.loadListener_ = () => {
  15787. if (!this.el_ || !this.el_.contentWindow) {
  15788. return;
  15789. }
  15790. const debouncedHandler_ = this.debouncedHandler_;
  15791. let unloadListener_ = this.unloadListener_ = function () {
  15792. off(this, 'resize', debouncedHandler_);
  15793. off(this, 'unload', unloadListener_);
  15794. unloadListener_ = null;
  15795. };
  15796. // safari and edge can unload the iframe before resizemanager dispose
  15797. // we have to dispose of event handlers correctly before that happens
  15798. on(this.el_.contentWindow, 'unload', unloadListener_);
  15799. on(this.el_.contentWindow, 'resize', debouncedHandler_);
  15800. };
  15801. this.one('load', this.loadListener_);
  15802. }
  15803. }
  15804. createEl() {
  15805. return super.createEl('iframe', {
  15806. className: 'vjs-resize-manager',
  15807. tabIndex: -1,
  15808. title: this.localize('No content')
  15809. }, {
  15810. 'aria-hidden': 'true'
  15811. });
  15812. }
  15813. /**
  15814. * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
  15815. *
  15816. * @fires Player#playerresize
  15817. */
  15818. resizeHandler() {
  15819. /**
  15820. * Called when the player size has changed
  15821. *
  15822. * @event Player#playerresize
  15823. * @type {Event}
  15824. */
  15825. // make sure player is still around to trigger
  15826. // prevents this from causing an error after dispose
  15827. if (!this.player_ || !this.player_.trigger) {
  15828. return;
  15829. }
  15830. this.player_.trigger('playerresize');
  15831. }
  15832. dispose() {
  15833. if (this.debouncedHandler_) {
  15834. this.debouncedHandler_.cancel();
  15835. }
  15836. if (this.resizeObserver_) {
  15837. if (this.player_.el()) {
  15838. this.resizeObserver_.unobserve(this.player_.el());
  15839. }
  15840. this.resizeObserver_.disconnect();
  15841. }
  15842. if (this.loadListener_) {
  15843. this.off('load', this.loadListener_);
  15844. }
  15845. if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
  15846. this.unloadListener_.call(this.el_.contentWindow);
  15847. }
  15848. this.ResizeObserver = null;
  15849. this.resizeObserver = null;
  15850. this.debouncedHandler_ = null;
  15851. this.loadListener_ = null;
  15852. super.dispose();
  15853. }
  15854. }
  15855. Component$1.registerComponent('ResizeManager', ResizeManager);
  15856. const defaults = {
  15857. trackingThreshold: 20,
  15858. liveTolerance: 15
  15859. };
  15860. /*
  15861. track when we are at the live edge, and other helpers for live playback */
  15862. /**
  15863. * A class for checking live current time and determining when the player
  15864. * is at or behind the live edge.
  15865. */
  15866. class LiveTracker extends Component$1 {
  15867. /**
  15868. * Creates an instance of this class.
  15869. *
  15870. * @param { import('./player').default } player
  15871. * The `Player` that this class should be attached to.
  15872. *
  15873. * @param {Object} [options]
  15874. * The key/value store of player options.
  15875. *
  15876. * @param {number} [options.trackingThreshold=20]
  15877. * Number of seconds of live window (seekableEnd - seekableStart) that
  15878. * media needs to have before the liveui will be shown.
  15879. *
  15880. * @param {number} [options.liveTolerance=15]
  15881. * Number of seconds behind live that we have to be
  15882. * before we will be considered non-live. Note that this will only
  15883. * be used when playing at the live edge. This allows large seekable end
  15884. * changes to not effect whether we are live or not.
  15885. */
  15886. constructor(player, options) {
  15887. // LiveTracker does not need an element
  15888. const options_ = merge$1(defaults, options, {
  15889. createEl: false
  15890. });
  15891. super(player, options_);
  15892. this.trackLiveHandler_ = () => this.trackLive_();
  15893. this.handlePlay_ = e => this.handlePlay(e);
  15894. this.handleFirstTimeupdate_ = e => this.handleFirstTimeupdate(e);
  15895. this.handleSeeked_ = e => this.handleSeeked(e);
  15896. this.seekToLiveEdge_ = e => this.seekToLiveEdge(e);
  15897. this.reset_();
  15898. this.on(this.player_, 'durationchange', e => this.handleDurationchange(e));
  15899. // we should try to toggle tracking on canplay as native playback engines, like Safari
  15900. // may not have the proper values for things like seekableEnd until then
  15901. this.on(this.player_, 'canplay', () => this.toggleTracking());
  15902. }
  15903. /**
  15904. * all the functionality for tracking when seek end changes
  15905. * and for tracking how far past seek end we should be
  15906. */
  15907. trackLive_() {
  15908. const seekable = this.player_.seekable();
  15909. // skip undefined seekable
  15910. if (!seekable || !seekable.length) {
  15911. return;
  15912. }
  15913. const newTime = Number(window$1.performance.now().toFixed(4));
  15914. const deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1000;
  15915. this.lastTime_ = newTime;
  15916. this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;
  15917. const liveCurrentTime = this.liveCurrentTime();
  15918. const currentTime = this.player_.currentTime();
  15919. // we are behind live if any are true
  15920. // 1. the player is paused
  15921. // 2. the user seeked to a location 2 seconds away from live
  15922. // 3. the difference between live and current time is greater
  15923. // liveTolerance which defaults to 15s
  15924. let isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance;
  15925. // we cannot be behind if
  15926. // 1. until we have not seen a timeupdate yet
  15927. // 2. liveCurrentTime is Infinity, which happens on Android and Native Safari
  15928. if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {
  15929. isBehind = false;
  15930. }
  15931. if (isBehind !== this.behindLiveEdge_) {
  15932. this.behindLiveEdge_ = isBehind;
  15933. this.trigger('liveedgechange');
  15934. }
  15935. }
  15936. /**
  15937. * handle a durationchange event on the player
  15938. * and start/stop tracking accordingly.
  15939. */
  15940. handleDurationchange() {
  15941. this.toggleTracking();
  15942. }
  15943. /**
  15944. * start/stop tracking
  15945. */
  15946. toggleTracking() {
  15947. if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {
  15948. if (this.player_.options_.liveui) {
  15949. this.player_.addClass('vjs-liveui');
  15950. }
  15951. this.startTracking();
  15952. } else {
  15953. this.player_.removeClass('vjs-liveui');
  15954. this.stopTracking();
  15955. }
  15956. }
  15957. /**
  15958. * start tracking live playback
  15959. */
  15960. startTracking() {
  15961. if (this.isTracking()) {
  15962. return;
  15963. }
  15964. // If we haven't seen a timeupdate, we need to check whether playback
  15965. // began before this component started tracking. This can happen commonly
  15966. // when using autoplay.
  15967. if (!this.timeupdateSeen_) {
  15968. this.timeupdateSeen_ = this.player_.hasStarted();
  15969. }
  15970. this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);
  15971. this.trackLive_();
  15972. this.on(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  15973. if (!this.timeupdateSeen_) {
  15974. this.one(this.player_, 'play', this.handlePlay_);
  15975. this.one(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  15976. } else {
  15977. this.on(this.player_, 'seeked', this.handleSeeked_);
  15978. }
  15979. }
  15980. /**
  15981. * handle the first timeupdate on the player if it wasn't already playing
  15982. * when live tracker started tracking.
  15983. */
  15984. handleFirstTimeupdate() {
  15985. this.timeupdateSeen_ = true;
  15986. this.on(this.player_, 'seeked', this.handleSeeked_);
  15987. }
  15988. /**
  15989. * Keep track of what time a seek starts, and listen for seeked
  15990. * to find where a seek ends.
  15991. */
  15992. handleSeeked() {
  15993. const timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());
  15994. this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;
  15995. this.nextSeekedFromUser_ = false;
  15996. this.trackLive_();
  15997. }
  15998. /**
  15999. * handle the first play on the player, and make sure that we seek
  16000. * right to the live edge.
  16001. */
  16002. handlePlay() {
  16003. this.one(this.player_, 'timeupdate', this.seekToLiveEdge_);
  16004. }
  16005. /**
  16006. * Stop tracking, and set all internal variables to
  16007. * their initial value.
  16008. */
  16009. reset_() {
  16010. this.lastTime_ = -1;
  16011. this.pastSeekEnd_ = 0;
  16012. this.lastSeekEnd_ = -1;
  16013. this.behindLiveEdge_ = true;
  16014. this.timeupdateSeen_ = false;
  16015. this.seekedBehindLive_ = false;
  16016. this.nextSeekedFromUser_ = false;
  16017. this.clearInterval(this.trackingInterval_);
  16018. this.trackingInterval_ = null;
  16019. this.off(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  16020. this.off(this.player_, 'seeked', this.handleSeeked_);
  16021. this.off(this.player_, 'play', this.handlePlay_);
  16022. this.off(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  16023. this.off(this.player_, 'timeupdate', this.seekToLiveEdge_);
  16024. }
  16025. /**
  16026. * The next seeked event is from the user. Meaning that any seek
  16027. * > 2s behind live will be considered behind live for real and
  16028. * liveTolerance will be ignored.
  16029. */
  16030. nextSeekedFromUser() {
  16031. this.nextSeekedFromUser_ = true;
  16032. }
  16033. /**
  16034. * stop tracking live playback
  16035. */
  16036. stopTracking() {
  16037. if (!this.isTracking()) {
  16038. return;
  16039. }
  16040. this.reset_();
  16041. this.trigger('liveedgechange');
  16042. }
  16043. /**
  16044. * A helper to get the player seekable end
  16045. * so that we don't have to null check everywhere
  16046. *
  16047. * @return {number}
  16048. * The furthest seekable end or Infinity.
  16049. */
  16050. seekableEnd() {
  16051. const seekable = this.player_.seekable();
  16052. const seekableEnds = [];
  16053. let i = seekable ? seekable.length : 0;
  16054. while (i--) {
  16055. seekableEnds.push(seekable.end(i));
  16056. }
  16057. // grab the furthest seekable end after sorting, or if there are none
  16058. // default to Infinity
  16059. return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;
  16060. }
  16061. /**
  16062. * A helper to get the player seekable start
  16063. * so that we don't have to null check everywhere
  16064. *
  16065. * @return {number}
  16066. * The earliest seekable start or 0.
  16067. */
  16068. seekableStart() {
  16069. const seekable = this.player_.seekable();
  16070. const seekableStarts = [];
  16071. let i = seekable ? seekable.length : 0;
  16072. while (i--) {
  16073. seekableStarts.push(seekable.start(i));
  16074. }
  16075. // grab the first seekable start after sorting, or if there are none
  16076. // default to 0
  16077. return seekableStarts.length ? seekableStarts.sort()[0] : 0;
  16078. }
  16079. /**
  16080. * Get the live time window aka
  16081. * the amount of time between seekable start and
  16082. * live current time.
  16083. *
  16084. * @return {number}
  16085. * The amount of seconds that are seekable in
  16086. * the live video.
  16087. */
  16088. liveWindow() {
  16089. const liveCurrentTime = this.liveCurrentTime();
  16090. // if liveCurrenTime is Infinity then we don't have a liveWindow at all
  16091. if (liveCurrentTime === Infinity) {
  16092. return 0;
  16093. }
  16094. return liveCurrentTime - this.seekableStart();
  16095. }
  16096. /**
  16097. * Determines if the player is live, only checks if this component
  16098. * is tracking live playback or not
  16099. *
  16100. * @return {boolean}
  16101. * Whether liveTracker is tracking
  16102. */
  16103. isLive() {
  16104. return this.isTracking();
  16105. }
  16106. /**
  16107. * Determines if currentTime is at the live edge and won't fall behind
  16108. * on each seekableendchange
  16109. *
  16110. * @return {boolean}
  16111. * Whether playback is at the live edge
  16112. */
  16113. atLiveEdge() {
  16114. return !this.behindLiveEdge();
  16115. }
  16116. /**
  16117. * get what we expect the live current time to be
  16118. *
  16119. * @return {number}
  16120. * The expected live current time
  16121. */
  16122. liveCurrentTime() {
  16123. return this.pastSeekEnd() + this.seekableEnd();
  16124. }
  16125. /**
  16126. * The number of seconds that have occurred after seekable end
  16127. * changed. This will be reset to 0 once seekable end changes.
  16128. *
  16129. * @return {number}
  16130. * Seconds past the current seekable end
  16131. */
  16132. pastSeekEnd() {
  16133. const seekableEnd = this.seekableEnd();
  16134. if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {
  16135. this.pastSeekEnd_ = 0;
  16136. }
  16137. this.lastSeekEnd_ = seekableEnd;
  16138. return this.pastSeekEnd_;
  16139. }
  16140. /**
  16141. * If we are currently behind the live edge, aka currentTime will be
  16142. * behind on a seekableendchange
  16143. *
  16144. * @return {boolean}
  16145. * If we are behind the live edge
  16146. */
  16147. behindLiveEdge() {
  16148. return this.behindLiveEdge_;
  16149. }
  16150. /**
  16151. * Whether live tracker is currently tracking or not.
  16152. */
  16153. isTracking() {
  16154. return typeof this.trackingInterval_ === 'number';
  16155. }
  16156. /**
  16157. * Seek to the live edge if we are behind the live edge
  16158. */
  16159. seekToLiveEdge() {
  16160. this.seekedBehindLive_ = false;
  16161. if (this.atLiveEdge()) {
  16162. return;
  16163. }
  16164. this.nextSeekedFromUser_ = false;
  16165. this.player_.currentTime(this.liveCurrentTime());
  16166. }
  16167. /**
  16168. * Dispose of liveTracker
  16169. */
  16170. dispose() {
  16171. this.stopTracking();
  16172. super.dispose();
  16173. }
  16174. }
  16175. Component$1.registerComponent('LiveTracker', LiveTracker);
  16176. /**
  16177. * Displays an element over the player which contains an optional title and
  16178. * description for the current content.
  16179. *
  16180. * Much of the code for this component originated in the now obsolete
  16181. * videojs-dock plugin: https://github.com/brightcove/videojs-dock/
  16182. *
  16183. * @extends Component
  16184. */
  16185. class TitleBar extends Component$1 {
  16186. constructor(player, options) {
  16187. super(player, options);
  16188. this.on('statechanged', e => this.updateDom_());
  16189. this.updateDom_();
  16190. }
  16191. /**
  16192. * Create the `TitleBar`'s DOM element
  16193. *
  16194. * @return {Element}
  16195. * The element that was created.
  16196. */
  16197. createEl() {
  16198. this.els = {
  16199. title: createEl('div', {
  16200. className: 'vjs-title-bar-title',
  16201. id: `vjs-title-bar-title-${newGUID()}`
  16202. }),
  16203. description: createEl('div', {
  16204. className: 'vjs-title-bar-description',
  16205. id: `vjs-title-bar-description-${newGUID()}`
  16206. })
  16207. };
  16208. return createEl('div', {
  16209. className: 'vjs-title-bar'
  16210. }, {}, Object.values(this.els));
  16211. }
  16212. /**
  16213. * Updates the DOM based on the component's state object.
  16214. */
  16215. updateDom_() {
  16216. const tech = this.player_.tech_;
  16217. const techEl = tech && tech.el_;
  16218. const techAriaAttrs = {
  16219. title: 'aria-labelledby',
  16220. description: 'aria-describedby'
  16221. };
  16222. ['title', 'description'].forEach(k => {
  16223. const value = this.state[k];
  16224. const el = this.els[k];
  16225. const techAriaAttr = techAriaAttrs[k];
  16226. emptyEl(el);
  16227. if (value) {
  16228. textContent(el, value);
  16229. }
  16230. // If there is a tech element available, update its ARIA attributes
  16231. // according to whether a title and/or description have been provided.
  16232. if (techEl) {
  16233. techEl.removeAttribute(techAriaAttr);
  16234. if (value) {
  16235. techEl.setAttribute(techAriaAttr, el.id);
  16236. }
  16237. }
  16238. });
  16239. if (this.state.title || this.state.description) {
  16240. this.show();
  16241. } else {
  16242. this.hide();
  16243. }
  16244. }
  16245. /**
  16246. * Update the contents of the title bar component with new title and
  16247. * description text.
  16248. *
  16249. * If both title and description are missing, the title bar will be hidden.
  16250. *
  16251. * If either title or description are present, the title bar will be visible.
  16252. *
  16253. * NOTE: Any previously set value will be preserved. To unset a previously
  16254. * set value, you must pass an empty string or null.
  16255. *
  16256. * For example:
  16257. *
  16258. * ```
  16259. * update({title: 'foo', description: 'bar'}) // title: 'foo', description: 'bar'
  16260. * update({description: 'bar2'}) // title: 'foo', description: 'bar2'
  16261. * update({title: ''}) // title: '', description: 'bar2'
  16262. * update({title: 'foo', description: null}) // title: 'foo', description: null
  16263. * ```
  16264. *
  16265. * @param {Object} [options={}]
  16266. * An options object. When empty, the title bar will be hidden.
  16267. *
  16268. * @param {string} [options.title]
  16269. * A title to display in the title bar.
  16270. *
  16271. * @param {string} [options.description]
  16272. * A description to display in the title bar.
  16273. */
  16274. update(options) {
  16275. this.setState(options);
  16276. }
  16277. /**
  16278. * Dispose the component.
  16279. */
  16280. dispose() {
  16281. const tech = this.player_.tech_;
  16282. const techEl = tech && tech.el_;
  16283. if (techEl) {
  16284. techEl.removeAttribute('aria-labelledby');
  16285. techEl.removeAttribute('aria-describedby');
  16286. }
  16287. super.dispose();
  16288. this.els = null;
  16289. }
  16290. }
  16291. Component$1.registerComponent('TitleBar', TitleBar);
  16292. /**
  16293. * This function is used to fire a sourceset when there is something
  16294. * similar to `mediaEl.load()` being called. It will try to find the source via
  16295. * the `src` attribute and then the `<source>` elements. It will then fire `sourceset`
  16296. * with the source that was found or empty string if we cannot know. If it cannot
  16297. * find a source then `sourceset` will not be fired.
  16298. *
  16299. * @param { import('./html5').default } tech
  16300. * The tech object that sourceset was setup on
  16301. *
  16302. * @return {boolean}
  16303. * returns false if the sourceset was not fired and true otherwise.
  16304. */
  16305. const sourcesetLoad = tech => {
  16306. const el = tech.el();
  16307. // if `el.src` is set, that source will be loaded.
  16308. if (el.hasAttribute('src')) {
  16309. tech.triggerSourceset(el.src);
  16310. return true;
  16311. }
  16312. /**
  16313. * Since there isn't a src property on the media element, source elements will be used for
  16314. * implementing the source selection algorithm. This happens asynchronously and
  16315. * for most cases were there is more than one source we cannot tell what source will
  16316. * be loaded, without re-implementing the source selection algorithm. At this time we are not
  16317. * going to do that. There are three special cases that we do handle here though:
  16318. *
  16319. * 1. If there are no sources, do not fire `sourceset`.
  16320. * 2. If there is only one `<source>` with a `src` property/attribute that is our `src`
  16321. * 3. If there is more than one `<source>` but all of them have the same `src` url.
  16322. * That will be our src.
  16323. */
  16324. const sources = tech.$$('source');
  16325. const srcUrls = [];
  16326. let src = '';
  16327. // if there are no sources, do not fire sourceset
  16328. if (!sources.length) {
  16329. return false;
  16330. }
  16331. // only count valid/non-duplicate source elements
  16332. for (let i = 0; i < sources.length; i++) {
  16333. const url = sources[i].src;
  16334. if (url && srcUrls.indexOf(url) === -1) {
  16335. srcUrls.push(url);
  16336. }
  16337. }
  16338. // there were no valid sources
  16339. if (!srcUrls.length) {
  16340. return false;
  16341. }
  16342. // there is only one valid source element url
  16343. // use that
  16344. if (srcUrls.length === 1) {
  16345. src = srcUrls[0];
  16346. }
  16347. tech.triggerSourceset(src);
  16348. return true;
  16349. };
  16350. /**
  16351. * our implementation of an `innerHTML` descriptor for browsers
  16352. * that do not have one.
  16353. */
  16354. const innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {
  16355. get() {
  16356. return this.cloneNode(true).innerHTML;
  16357. },
  16358. set(v) {
  16359. // make a dummy node to use innerHTML on
  16360. const dummy = document.createElement(this.nodeName.toLowerCase());
  16361. // set innerHTML to the value provided
  16362. dummy.innerHTML = v;
  16363. // make a document fragment to hold the nodes from dummy
  16364. const docFrag = document.createDocumentFragment();
  16365. // copy all of the nodes created by the innerHTML on dummy
  16366. // to the document fragment
  16367. while (dummy.childNodes.length) {
  16368. docFrag.appendChild(dummy.childNodes[0]);
  16369. }
  16370. // remove content
  16371. this.innerText = '';
  16372. // now we add all of that html in one by appending the
  16373. // document fragment. This is how innerHTML does it.
  16374. window$1.Element.prototype.appendChild.call(this, docFrag);
  16375. // then return the result that innerHTML's setter would
  16376. return this.innerHTML;
  16377. }
  16378. });
  16379. /**
  16380. * Get a property descriptor given a list of priorities and the
  16381. * property to get.
  16382. */
  16383. const getDescriptor = (priority, prop) => {
  16384. let descriptor = {};
  16385. for (let i = 0; i < priority.length; i++) {
  16386. descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
  16387. if (descriptor && descriptor.set && descriptor.get) {
  16388. break;
  16389. }
  16390. }
  16391. descriptor.enumerable = true;
  16392. descriptor.configurable = true;
  16393. return descriptor;
  16394. };
  16395. const getInnerHTMLDescriptor = tech => getDescriptor([tech.el(), window$1.HTMLMediaElement.prototype, window$1.Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');
  16396. /**
  16397. * Patches browser internal functions so that we can tell synchronously
  16398. * if a `<source>` was appended to the media element. For some reason this
  16399. * causes a `sourceset` if the the media element is ready and has no source.
  16400. * This happens when:
  16401. * - The page has just loaded and the media element does not have a source.
  16402. * - The media element was emptied of all sources, then `load()` was called.
  16403. *
  16404. * It does this by patching the following functions/properties when they are supported:
  16405. *
  16406. * - `append()` - can be used to add a `<source>` element to the media element
  16407. * - `appendChild()` - can be used to add a `<source>` element to the media element
  16408. * - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element
  16409. * - `innerHTML` - can be used to add a `<source>` element to the media element
  16410. *
  16411. * @param {Html5} tech
  16412. * The tech object that sourceset is being setup on.
  16413. */
  16414. const firstSourceWatch = function (tech) {
  16415. const el = tech.el();
  16416. // make sure firstSourceWatch isn't setup twice.
  16417. if (el.resetSourceWatch_) {
  16418. return;
  16419. }
  16420. const old = {};
  16421. const innerDescriptor = getInnerHTMLDescriptor(tech);
  16422. const appendWrapper = appendFn => (...args) => {
  16423. const retval = appendFn.apply(el, args);
  16424. sourcesetLoad(tech);
  16425. return retval;
  16426. };
  16427. ['append', 'appendChild', 'insertAdjacentHTML'].forEach(k => {
  16428. if (!el[k]) {
  16429. return;
  16430. }
  16431. // store the old function
  16432. old[k] = el[k];
  16433. // call the old function with a sourceset if a source
  16434. // was loaded
  16435. el[k] = appendWrapper(old[k]);
  16436. });
  16437. Object.defineProperty(el, 'innerHTML', merge$1(innerDescriptor, {
  16438. set: appendWrapper(innerDescriptor.set)
  16439. }));
  16440. el.resetSourceWatch_ = () => {
  16441. el.resetSourceWatch_ = null;
  16442. Object.keys(old).forEach(k => {
  16443. el[k] = old[k];
  16444. });
  16445. Object.defineProperty(el, 'innerHTML', innerDescriptor);
  16446. };
  16447. // on the first sourceset, we need to revert our changes
  16448. tech.one('sourceset', el.resetSourceWatch_);
  16449. };
  16450. /**
  16451. * our implementation of a `src` descriptor for browsers
  16452. * that do not have one
  16453. */
  16454. const srcDescriptorPolyfill = Object.defineProperty({}, 'src', {
  16455. get() {
  16456. if (this.hasAttribute('src')) {
  16457. return getAbsoluteURL(window$1.Element.prototype.getAttribute.call(this, 'src'));
  16458. }
  16459. return '';
  16460. },
  16461. set(v) {
  16462. window$1.Element.prototype.setAttribute.call(this, 'src', v);
  16463. return v;
  16464. }
  16465. });
  16466. const getSrcDescriptor = tech => getDescriptor([tech.el(), window$1.HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');
  16467. /**
  16468. * setup `sourceset` handling on the `Html5` tech. This function
  16469. * patches the following element properties/functions:
  16470. *
  16471. * - `src` - to determine when `src` is set
  16472. * - `setAttribute()` - to determine when `src` is set
  16473. * - `load()` - this re-triggers the source selection algorithm, and can
  16474. * cause a sourceset.
  16475. *
  16476. * If there is no source when we are adding `sourceset` support or during a `load()`
  16477. * we also patch the functions listed in `firstSourceWatch`.
  16478. *
  16479. * @param {Html5} tech
  16480. * The tech to patch
  16481. */
  16482. const setupSourceset = function (tech) {
  16483. if (!tech.featuresSourceset) {
  16484. return;
  16485. }
  16486. const el = tech.el();
  16487. // make sure sourceset isn't setup twice.
  16488. if (el.resetSourceset_) {
  16489. return;
  16490. }
  16491. const srcDescriptor = getSrcDescriptor(tech);
  16492. const oldSetAttribute = el.setAttribute;
  16493. const oldLoad = el.load;
  16494. Object.defineProperty(el, 'src', merge$1(srcDescriptor, {
  16495. set: v => {
  16496. const retval = srcDescriptor.set.call(el, v);
  16497. // we use the getter here to get the actual value set on src
  16498. tech.triggerSourceset(el.src);
  16499. return retval;
  16500. }
  16501. }));
  16502. el.setAttribute = (n, v) => {
  16503. const retval = oldSetAttribute.call(el, n, v);
  16504. if (/src/i.test(n)) {
  16505. tech.triggerSourceset(el.src);
  16506. }
  16507. return retval;
  16508. };
  16509. el.load = () => {
  16510. const retval = oldLoad.call(el);
  16511. // if load was called, but there was no source to fire
  16512. // sourceset on. We have to watch for a source append
  16513. // as that can trigger a `sourceset` when the media element
  16514. // has no source
  16515. if (!sourcesetLoad(tech)) {
  16516. tech.triggerSourceset('');
  16517. firstSourceWatch(tech);
  16518. }
  16519. return retval;
  16520. };
  16521. if (el.currentSrc) {
  16522. tech.triggerSourceset(el.currentSrc);
  16523. } else if (!sourcesetLoad(tech)) {
  16524. firstSourceWatch(tech);
  16525. }
  16526. el.resetSourceset_ = () => {
  16527. el.resetSourceset_ = null;
  16528. el.load = oldLoad;
  16529. el.setAttribute = oldSetAttribute;
  16530. Object.defineProperty(el, 'src', srcDescriptor);
  16531. if (el.resetSourceWatch_) {
  16532. el.resetSourceWatch_();
  16533. }
  16534. };
  16535. };
  16536. /**
  16537. * @file html5.js
  16538. */
  16539. /**
  16540. * HTML5 Media Controller - Wrapper for HTML5 Media API
  16541. *
  16542. * @mixes Tech~SourceHandlerAdditions
  16543. * @extends Tech
  16544. */
  16545. class Html5 extends Tech {
  16546. /**
  16547. * Create an instance of this Tech.
  16548. *
  16549. * @param {Object} [options]
  16550. * The key/value store of player options.
  16551. *
  16552. * @param {Function} [ready]
  16553. * Callback function to call when the `HTML5` Tech is ready.
  16554. */
  16555. constructor(options, ready) {
  16556. super(options, ready);
  16557. const source = options.source;
  16558. let crossoriginTracks = false;
  16559. this.featuresVideoFrameCallback = this.featuresVideoFrameCallback && this.el_.tagName === 'VIDEO';
  16560. // Set the source if one is provided
  16561. // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
  16562. // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
  16563. // anyway so the error gets fired.
  16564. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
  16565. this.setSource(source);
  16566. } else {
  16567. this.handleLateInit_(this.el_);
  16568. }
  16569. // setup sourceset after late sourceset/init
  16570. if (options.enableSourceset) {
  16571. this.setupSourcesetHandling_();
  16572. }
  16573. this.isScrubbing_ = false;
  16574. if (this.el_.hasChildNodes()) {
  16575. const nodes = this.el_.childNodes;
  16576. let nodesLength = nodes.length;
  16577. const removeNodes = [];
  16578. while (nodesLength--) {
  16579. const node = nodes[nodesLength];
  16580. const nodeName = node.nodeName.toLowerCase();
  16581. if (nodeName === 'track') {
  16582. if (!this.featuresNativeTextTracks) {
  16583. // Empty video tag tracks so the built-in player doesn't use them also.
  16584. // This may not be fast enough to stop HTML5 browsers from reading the tags
  16585. // so we'll need to turn off any default tracks if we're manually doing
  16586. // captions and subtitles. videoElement.textTracks
  16587. removeNodes.push(node);
  16588. } else {
  16589. // store HTMLTrackElement and TextTrack to remote list
  16590. this.remoteTextTrackEls().addTrackElement_(node);
  16591. this.remoteTextTracks().addTrack(node.track);
  16592. this.textTracks().addTrack(node.track);
  16593. if (!crossoriginTracks && !this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {
  16594. crossoriginTracks = true;
  16595. }
  16596. }
  16597. }
  16598. }
  16599. for (let i = 0; i < removeNodes.length; i++) {
  16600. this.el_.removeChild(removeNodes[i]);
  16601. }
  16602. }
  16603. this.proxyNativeTracks_();
  16604. if (this.featuresNativeTextTracks && crossoriginTracks) {
  16605. 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.');
  16606. }
  16607. // prevent iOS Safari from disabling metadata text tracks during native playback
  16608. this.restoreMetadataTracksInIOSNativePlayer_();
  16609. // Determine if native controls should be used
  16610. // Our goal should be to get the custom controls on mobile solid everywhere
  16611. // so we can remove this all together. Right now this will block custom
  16612. // controls on touch enabled laptops like the Chrome Pixel
  16613. if ((TOUCH_ENABLED || IS_IPHONE) && options.nativeControlsForTouch === true) {
  16614. this.setControls(true);
  16615. }
  16616. // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
  16617. // into a `fullscreenchange` event
  16618. this.proxyWebkitFullscreen_();
  16619. this.triggerReady();
  16620. }
  16621. /**
  16622. * Dispose of `HTML5` media element and remove all tracks.
  16623. */
  16624. dispose() {
  16625. if (this.el_ && this.el_.resetSourceset_) {
  16626. this.el_.resetSourceset_();
  16627. }
  16628. Html5.disposeMediaElement(this.el_);
  16629. this.options_ = null;
  16630. // tech will handle clearing of the emulated track list
  16631. super.dispose();
  16632. }
  16633. /**
  16634. * Modify the media element so that we can detect when
  16635. * the source is changed. Fires `sourceset` just after the source has changed
  16636. */
  16637. setupSourcesetHandling_() {
  16638. setupSourceset(this);
  16639. }
  16640. /**
  16641. * When a captions track is enabled in the iOS Safari native player, all other
  16642. * tracks are disabled (including metadata tracks), which nulls all of their
  16643. * associated cue points. This will restore metadata tracks to their pre-fullscreen
  16644. * state in those cases so that cue points are not needlessly lost.
  16645. *
  16646. * @private
  16647. */
  16648. restoreMetadataTracksInIOSNativePlayer_() {
  16649. const textTracks = this.textTracks();
  16650. let metadataTracksPreFullscreenState;
  16651. // captures a snapshot of every metadata track's current state
  16652. const takeMetadataTrackSnapshot = () => {
  16653. metadataTracksPreFullscreenState = [];
  16654. for (let i = 0; i < textTracks.length; i++) {
  16655. const track = textTracks[i];
  16656. if (track.kind === 'metadata') {
  16657. metadataTracksPreFullscreenState.push({
  16658. track,
  16659. storedMode: track.mode
  16660. });
  16661. }
  16662. }
  16663. };
  16664. // snapshot each metadata track's initial state, and update the snapshot
  16665. // each time there is a track 'change' event
  16666. takeMetadataTrackSnapshot();
  16667. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  16668. this.on('dispose', () => textTracks.removeEventListener('change', takeMetadataTrackSnapshot));
  16669. const restoreTrackMode = () => {
  16670. for (let i = 0; i < metadataTracksPreFullscreenState.length; i++) {
  16671. const storedTrack = metadataTracksPreFullscreenState[i];
  16672. if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {
  16673. storedTrack.track.mode = storedTrack.storedMode;
  16674. }
  16675. }
  16676. // we only want this handler to be executed on the first 'change' event
  16677. textTracks.removeEventListener('change', restoreTrackMode);
  16678. };
  16679. // when we enter fullscreen playback, stop updating the snapshot and
  16680. // restore all track modes to their pre-fullscreen state
  16681. this.on('webkitbeginfullscreen', () => {
  16682. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  16683. // remove the listener before adding it just in case it wasn't previously removed
  16684. textTracks.removeEventListener('change', restoreTrackMode);
  16685. textTracks.addEventListener('change', restoreTrackMode);
  16686. });
  16687. // start updating the snapshot again after leaving fullscreen
  16688. this.on('webkitendfullscreen', () => {
  16689. // remove the listener before adding it just in case it wasn't previously removed
  16690. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  16691. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  16692. // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback
  16693. textTracks.removeEventListener('change', restoreTrackMode);
  16694. });
  16695. }
  16696. /**
  16697. * Attempt to force override of tracks for the given type
  16698. *
  16699. * @param {string} type - Track type to override, possible values include 'Audio',
  16700. * 'Video', and 'Text'.
  16701. * @param {boolean} override - If set to true native audio/video will be overridden,
  16702. * otherwise native audio/video will potentially be used.
  16703. * @private
  16704. */
  16705. overrideNative_(type, override) {
  16706. // If there is no behavioral change don't add/remove listeners
  16707. if (override !== this[`featuresNative${type}Tracks`]) {
  16708. return;
  16709. }
  16710. const lowerCaseType = type.toLowerCase();
  16711. if (this[`${lowerCaseType}TracksListeners_`]) {
  16712. Object.keys(this[`${lowerCaseType}TracksListeners_`]).forEach(eventName => {
  16713. const elTracks = this.el()[`${lowerCaseType}Tracks`];
  16714. elTracks.removeEventListener(eventName, this[`${lowerCaseType}TracksListeners_`][eventName]);
  16715. });
  16716. }
  16717. this[`featuresNative${type}Tracks`] = !override;
  16718. this[`${lowerCaseType}TracksListeners_`] = null;
  16719. this.proxyNativeTracksForType_(lowerCaseType);
  16720. }
  16721. /**
  16722. * Attempt to force override of native audio tracks.
  16723. *
  16724. * @param {boolean} override - If set to true native audio will be overridden,
  16725. * otherwise native audio will potentially be used.
  16726. */
  16727. overrideNativeAudioTracks(override) {
  16728. this.overrideNative_('Audio', override);
  16729. }
  16730. /**
  16731. * Attempt to force override of native video tracks.
  16732. *
  16733. * @param {boolean} override - If set to true native video will be overridden,
  16734. * otherwise native video will potentially be used.
  16735. */
  16736. overrideNativeVideoTracks(override) {
  16737. this.overrideNative_('Video', override);
  16738. }
  16739. /**
  16740. * Proxy native track list events for the given type to our track
  16741. * lists if the browser we are playing in supports that type of track list.
  16742. *
  16743. * @param {string} name - Track type; values include 'audio', 'video', and 'text'
  16744. * @private
  16745. */
  16746. proxyNativeTracksForType_(name) {
  16747. const props = NORMAL[name];
  16748. const elTracks = this.el()[props.getterName];
  16749. const techTracks = this[props.getterName]();
  16750. if (!this[`featuresNative${props.capitalName}Tracks`] || !elTracks || !elTracks.addEventListener) {
  16751. return;
  16752. }
  16753. const listeners = {
  16754. change: e => {
  16755. const event = {
  16756. type: 'change',
  16757. target: techTracks,
  16758. currentTarget: techTracks,
  16759. srcElement: techTracks
  16760. };
  16761. techTracks.trigger(event);
  16762. // if we are a text track change event, we should also notify the
  16763. // remote text track list. This can potentially cause a false positive
  16764. // if we were to get a change event on a non-remote track and
  16765. // we triggered the event on the remote text track list which doesn't
  16766. // contain that track. However, best practices mean looping through the
  16767. // list of tracks and searching for the appropriate mode value, so,
  16768. // this shouldn't pose an issue
  16769. if (name === 'text') {
  16770. this[REMOTE.remoteText.getterName]().trigger(event);
  16771. }
  16772. },
  16773. addtrack(e) {
  16774. techTracks.addTrack(e.track);
  16775. },
  16776. removetrack(e) {
  16777. techTracks.removeTrack(e.track);
  16778. }
  16779. };
  16780. const removeOldTracks = function () {
  16781. const removeTracks = [];
  16782. for (let i = 0; i < techTracks.length; i++) {
  16783. let found = false;
  16784. for (let j = 0; j < elTracks.length; j++) {
  16785. if (elTracks[j] === techTracks[i]) {
  16786. found = true;
  16787. break;
  16788. }
  16789. }
  16790. if (!found) {
  16791. removeTracks.push(techTracks[i]);
  16792. }
  16793. }
  16794. while (removeTracks.length) {
  16795. techTracks.removeTrack(removeTracks.shift());
  16796. }
  16797. };
  16798. this[props.getterName + 'Listeners_'] = listeners;
  16799. Object.keys(listeners).forEach(eventName => {
  16800. const listener = listeners[eventName];
  16801. elTracks.addEventListener(eventName, listener);
  16802. this.on('dispose', e => elTracks.removeEventListener(eventName, listener));
  16803. });
  16804. // Remove (native) tracks that are not used anymore
  16805. this.on('loadstart', removeOldTracks);
  16806. this.on('dispose', e => this.off('loadstart', removeOldTracks));
  16807. }
  16808. /**
  16809. * Proxy all native track list events to our track lists if the browser we are playing
  16810. * in supports that type of track list.
  16811. *
  16812. * @private
  16813. */
  16814. proxyNativeTracks_() {
  16815. NORMAL.names.forEach(name => {
  16816. this.proxyNativeTracksForType_(name);
  16817. });
  16818. }
  16819. /**
  16820. * Create the `Html5` Tech's DOM element.
  16821. *
  16822. * @return {Element}
  16823. * The element that gets created.
  16824. */
  16825. createEl() {
  16826. let el = this.options_.tag;
  16827. // Check if this browser supports moving the element into the box.
  16828. // On the iPhone video will break if you move the element,
  16829. // So we have to create a brand new element.
  16830. // If we ingested the player div, we do not need to move the media element.
  16831. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
  16832. // If the original tag is still there, clone and remove it.
  16833. if (el) {
  16834. const clone = el.cloneNode(true);
  16835. if (el.parentNode) {
  16836. el.parentNode.insertBefore(clone, el);
  16837. }
  16838. Html5.disposeMediaElement(el);
  16839. el = clone;
  16840. } else {
  16841. el = document.createElement('video');
  16842. // determine if native controls should be used
  16843. const tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
  16844. const attributes = merge$1({}, tagAttributes);
  16845. if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
  16846. delete attributes.controls;
  16847. }
  16848. setAttributes(el, Object.assign(attributes, {
  16849. id: this.options_.techId,
  16850. class: 'vjs-tech'
  16851. }));
  16852. }
  16853. el.playerId = this.options_.playerId;
  16854. }
  16855. if (typeof this.options_.preload !== 'undefined') {
  16856. setAttribute(el, 'preload', this.options_.preload);
  16857. }
  16858. if (this.options_.disablePictureInPicture !== undefined) {
  16859. el.disablePictureInPicture = this.options_.disablePictureInPicture;
  16860. }
  16861. // Update specific tag settings, in case they were overridden
  16862. // `autoplay` has to be *last* so that `muted` and `playsinline` are present
  16863. // when iOS/Safari or other browsers attempt to autoplay.
  16864. const settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];
  16865. for (let i = 0; i < settingsAttrs.length; i++) {
  16866. const attr = settingsAttrs[i];
  16867. const value = this.options_[attr];
  16868. if (typeof value !== 'undefined') {
  16869. if (value) {
  16870. setAttribute(el, attr, attr);
  16871. } else {
  16872. removeAttribute(el, attr);
  16873. }
  16874. el[attr] = value;
  16875. }
  16876. }
  16877. return el;
  16878. }
  16879. /**
  16880. * This will be triggered if the loadstart event has already fired, before videojs was
  16881. * ready. Two known examples of when this can happen are:
  16882. * 1. If we're loading the playback object after it has started loading
  16883. * 2. The media is already playing the (often with autoplay on) then
  16884. *
  16885. * This function will fire another loadstart so that videojs can catchup.
  16886. *
  16887. * @fires Tech#loadstart
  16888. *
  16889. * @return {undefined}
  16890. * returns nothing.
  16891. */
  16892. handleLateInit_(el) {
  16893. if (el.networkState === 0 || el.networkState === 3) {
  16894. // The video element hasn't started loading the source yet
  16895. // or didn't find a source
  16896. return;
  16897. }
  16898. if (el.readyState === 0) {
  16899. // NetworkState is set synchronously BUT loadstart is fired at the
  16900. // end of the current stack, usually before setInterval(fn, 0).
  16901. // So at this point we know loadstart may have already fired or is
  16902. // about to fire, and either way the player hasn't seen it yet.
  16903. // We don't want to fire loadstart prematurely here and cause a
  16904. // double loadstart so we'll wait and see if it happens between now
  16905. // and the next loop, and fire it if not.
  16906. // HOWEVER, we also want to make sure it fires before loadedmetadata
  16907. // which could also happen between now and the next loop, so we'll
  16908. // watch for that also.
  16909. let loadstartFired = false;
  16910. const setLoadstartFired = function () {
  16911. loadstartFired = true;
  16912. };
  16913. this.on('loadstart', setLoadstartFired);
  16914. const triggerLoadstart = function () {
  16915. // We did miss the original loadstart. Make sure the player
  16916. // sees loadstart before loadedmetadata
  16917. if (!loadstartFired) {
  16918. this.trigger('loadstart');
  16919. }
  16920. };
  16921. this.on('loadedmetadata', triggerLoadstart);
  16922. this.ready(function () {
  16923. this.off('loadstart', setLoadstartFired);
  16924. this.off('loadedmetadata', triggerLoadstart);
  16925. if (!loadstartFired) {
  16926. // We did miss the original native loadstart. Fire it now.
  16927. this.trigger('loadstart');
  16928. }
  16929. });
  16930. return;
  16931. }
  16932. // From here on we know that loadstart already fired and we missed it.
  16933. // The other readyState events aren't as much of a problem if we double
  16934. // them, so not going to go to as much trouble as loadstart to prevent
  16935. // that unless we find reason to.
  16936. const eventsToTrigger = ['loadstart'];
  16937. // loadedmetadata: newly equal to HAVE_METADATA (1) or greater
  16938. eventsToTrigger.push('loadedmetadata');
  16939. // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
  16940. if (el.readyState >= 2) {
  16941. eventsToTrigger.push('loadeddata');
  16942. }
  16943. // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
  16944. if (el.readyState >= 3) {
  16945. eventsToTrigger.push('canplay');
  16946. }
  16947. // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
  16948. if (el.readyState >= 4) {
  16949. eventsToTrigger.push('canplaythrough');
  16950. }
  16951. // We still need to give the player time to add event listeners
  16952. this.ready(function () {
  16953. eventsToTrigger.forEach(function (type) {
  16954. this.trigger(type);
  16955. }, this);
  16956. });
  16957. }
  16958. /**
  16959. * Set whether we are scrubbing or not.
  16960. * This is used to decide whether we should use `fastSeek` or not.
  16961. * `fastSeek` is used to provide trick play on Safari browsers.
  16962. *
  16963. * @param {boolean} isScrubbing
  16964. * - true for we are currently scrubbing
  16965. * - false for we are no longer scrubbing
  16966. */
  16967. setScrubbing(isScrubbing) {
  16968. this.isScrubbing_ = isScrubbing;
  16969. }
  16970. /**
  16971. * Get whether we are scrubbing or not.
  16972. *
  16973. * @return {boolean} isScrubbing
  16974. * - true for we are currently scrubbing
  16975. * - false for we are no longer scrubbing
  16976. */
  16977. scrubbing() {
  16978. return this.isScrubbing_;
  16979. }
  16980. /**
  16981. * Set current time for the `HTML5` tech.
  16982. *
  16983. * @param {number} seconds
  16984. * Set the current time of the media to this.
  16985. */
  16986. setCurrentTime(seconds) {
  16987. try {
  16988. if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {
  16989. this.el_.fastSeek(seconds);
  16990. } else {
  16991. this.el_.currentTime = seconds;
  16992. }
  16993. } catch (e) {
  16994. log$1(e, 'Video is not ready. (Video.js)');
  16995. // this.warning(VideoJS.warnings.videoNotReady);
  16996. }
  16997. }
  16998. /**
  16999. * Get the current duration of the HTML5 media element.
  17000. *
  17001. * @return {number}
  17002. * The duration of the media or 0 if there is no duration.
  17003. */
  17004. duration() {
  17005. // Android Chrome will report duration as Infinity for VOD HLS until after
  17006. // playback has started, which triggers the live display erroneously.
  17007. // Return NaN if playback has not started and trigger a durationupdate once
  17008. // the duration can be reliably known.
  17009. if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
  17010. // Wait for the first `timeupdate` with currentTime > 0 - there may be
  17011. // several with 0
  17012. const checkProgress = () => {
  17013. if (this.el_.currentTime > 0) {
  17014. // Trigger durationchange for genuinely live video
  17015. if (this.el_.duration === Infinity) {
  17016. this.trigger('durationchange');
  17017. }
  17018. this.off('timeupdate', checkProgress);
  17019. }
  17020. };
  17021. this.on('timeupdate', checkProgress);
  17022. return NaN;
  17023. }
  17024. return this.el_.duration || NaN;
  17025. }
  17026. /**
  17027. * Get the current width of the HTML5 media element.
  17028. *
  17029. * @return {number}
  17030. * The width of the HTML5 media element.
  17031. */
  17032. width() {
  17033. return this.el_.offsetWidth;
  17034. }
  17035. /**
  17036. * Get the current height of the HTML5 media element.
  17037. *
  17038. * @return {number}
  17039. * The height of the HTML5 media element.
  17040. */
  17041. height() {
  17042. return this.el_.offsetHeight;
  17043. }
  17044. /**
  17045. * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into
  17046. * `fullscreenchange` event.
  17047. *
  17048. * @private
  17049. * @fires fullscreenchange
  17050. * @listens webkitendfullscreen
  17051. * @listens webkitbeginfullscreen
  17052. * @listens webkitbeginfullscreen
  17053. */
  17054. proxyWebkitFullscreen_() {
  17055. if (!('webkitDisplayingFullscreen' in this.el_)) {
  17056. return;
  17057. }
  17058. const endFn = function () {
  17059. this.trigger('fullscreenchange', {
  17060. isFullscreen: false
  17061. });
  17062. // Safari will sometimes set controls on the videoelement when existing fullscreen.
  17063. if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {
  17064. this.el_.controls = false;
  17065. }
  17066. };
  17067. const beginFn = function () {
  17068. if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {
  17069. this.one('webkitendfullscreen', endFn);
  17070. this.trigger('fullscreenchange', {
  17071. isFullscreen: true,
  17072. // set a flag in case another tech triggers fullscreenchange
  17073. nativeIOSFullscreen: true
  17074. });
  17075. }
  17076. };
  17077. this.on('webkitbeginfullscreen', beginFn);
  17078. this.on('dispose', () => {
  17079. this.off('webkitbeginfullscreen', beginFn);
  17080. this.off('webkitendfullscreen', endFn);
  17081. });
  17082. }
  17083. /**
  17084. * Check if fullscreen is supported on the video el.
  17085. *
  17086. * @return {boolean}
  17087. * - True if fullscreen is supported.
  17088. * - False if fullscreen is not supported.
  17089. */
  17090. supportsFullScreen() {
  17091. return typeof this.el_.webkitEnterFullScreen === 'function';
  17092. }
  17093. /**
  17094. * Request that the `HTML5` Tech enter fullscreen.
  17095. */
  17096. enterFullScreen() {
  17097. const video = this.el_;
  17098. if (video.paused && video.networkState <= video.HAVE_METADATA) {
  17099. // attempt to prime the video element for programmatic access
  17100. // this isn't necessary on the desktop but shouldn't hurt
  17101. silencePromise(this.el_.play());
  17102. // playing and pausing synchronously during the transition to fullscreen
  17103. // can get iOS ~6.1 devices into a play/pause loop
  17104. this.setTimeout(function () {
  17105. video.pause();
  17106. try {
  17107. video.webkitEnterFullScreen();
  17108. } catch (e) {
  17109. this.trigger('fullscreenerror', e);
  17110. }
  17111. }, 0);
  17112. } else {
  17113. try {
  17114. video.webkitEnterFullScreen();
  17115. } catch (e) {
  17116. this.trigger('fullscreenerror', e);
  17117. }
  17118. }
  17119. }
  17120. /**
  17121. * Request that the `HTML5` Tech exit fullscreen.
  17122. */
  17123. exitFullScreen() {
  17124. if (!this.el_.webkitDisplayingFullscreen) {
  17125. this.trigger('fullscreenerror', new Error('The video is not fullscreen'));
  17126. return;
  17127. }
  17128. this.el_.webkitExitFullScreen();
  17129. }
  17130. /**
  17131. * Create a floating video window always on top of other windows so that users may
  17132. * continue consuming media while they interact with other content sites, or
  17133. * applications on their device.
  17134. *
  17135. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  17136. *
  17137. * @return {Promise}
  17138. * A promise with a Picture-in-Picture window.
  17139. */
  17140. requestPictureInPicture() {
  17141. return this.el_.requestPictureInPicture();
  17142. }
  17143. /**
  17144. * Native requestVideoFrameCallback if supported by browser/tech, or fallback
  17145. * Don't use rVCF on Safari when DRM is playing, as it doesn't fire
  17146. * Needs to be checked later than the constructor
  17147. * This will be a false positive for clear sources loaded after a Fairplay source
  17148. *
  17149. * @param {function} cb function to call
  17150. * @return {number} id of request
  17151. */
  17152. requestVideoFrameCallback(cb) {
  17153. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  17154. return this.el_.requestVideoFrameCallback(cb);
  17155. }
  17156. return super.requestVideoFrameCallback(cb);
  17157. }
  17158. /**
  17159. * Native or fallback requestVideoFrameCallback
  17160. *
  17161. * @param {number} id request id to cancel
  17162. */
  17163. cancelVideoFrameCallback(id) {
  17164. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  17165. this.el_.cancelVideoFrameCallback(id);
  17166. } else {
  17167. super.cancelVideoFrameCallback(id);
  17168. }
  17169. }
  17170. /**
  17171. * A getter/setter for the `Html5` Tech's source object.
  17172. * > Note: Please use {@link Html5#setSource}
  17173. *
  17174. * @param {Tech~SourceObject} [src]
  17175. * The source object you want to set on the `HTML5` techs element.
  17176. *
  17177. * @return {Tech~SourceObject|undefined}
  17178. * - The current source object when a source is not passed in.
  17179. * - undefined when setting
  17180. *
  17181. * @deprecated Since version 5.
  17182. */
  17183. src(src) {
  17184. if (src === undefined) {
  17185. return this.el_.src;
  17186. }
  17187. // Setting src through `src` instead of `setSrc` will be deprecated
  17188. this.setSrc(src);
  17189. }
  17190. /**
  17191. * Reset the tech by removing all sources and then calling
  17192. * {@link Html5.resetMediaElement}.
  17193. */
  17194. reset() {
  17195. Html5.resetMediaElement(this.el_);
  17196. }
  17197. /**
  17198. * Get the current source on the `HTML5` Tech. Falls back to returning the source from
  17199. * the HTML5 media element.
  17200. *
  17201. * @return {Tech~SourceObject}
  17202. * The current source object from the HTML5 tech. With a fallback to the
  17203. * elements source.
  17204. */
  17205. currentSrc() {
  17206. if (this.currentSource_) {
  17207. return this.currentSource_.src;
  17208. }
  17209. return this.el_.currentSrc;
  17210. }
  17211. /**
  17212. * Set controls attribute for the HTML5 media Element.
  17213. *
  17214. * @param {string} val
  17215. * Value to set the controls attribute to
  17216. */
  17217. setControls(val) {
  17218. this.el_.controls = !!val;
  17219. }
  17220. /**
  17221. * Create and returns a remote {@link TextTrack} object.
  17222. *
  17223. * @param {string} kind
  17224. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  17225. *
  17226. * @param {string} [label]
  17227. * Label to identify the text track
  17228. *
  17229. * @param {string} [language]
  17230. * Two letter language abbreviation
  17231. *
  17232. * @return {TextTrack}
  17233. * The TextTrack that gets created.
  17234. */
  17235. addTextTrack(kind, label, language) {
  17236. if (!this.featuresNativeTextTracks) {
  17237. return super.addTextTrack(kind, label, language);
  17238. }
  17239. return this.el_.addTextTrack(kind, label, language);
  17240. }
  17241. /**
  17242. * Creates either native TextTrack or an emulated TextTrack depending
  17243. * on the value of `featuresNativeTextTracks`
  17244. *
  17245. * @param {Object} options
  17246. * The object should contain the options to initialize the TextTrack with.
  17247. *
  17248. * @param {string} [options.kind]
  17249. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  17250. *
  17251. * @param {string} [options.label]
  17252. * Label to identify the text track
  17253. *
  17254. * @param {string} [options.language]
  17255. * Two letter language abbreviation.
  17256. *
  17257. * @param {boolean} [options.default]
  17258. * Default this track to on.
  17259. *
  17260. * @param {string} [options.id]
  17261. * The internal id to assign this track.
  17262. *
  17263. * @param {string} [options.src]
  17264. * A source url for the track.
  17265. *
  17266. * @return {HTMLTrackElement}
  17267. * The track element that gets created.
  17268. */
  17269. createRemoteTextTrack(options) {
  17270. if (!this.featuresNativeTextTracks) {
  17271. return super.createRemoteTextTrack(options);
  17272. }
  17273. const htmlTrackElement = document.createElement('track');
  17274. if (options.kind) {
  17275. htmlTrackElement.kind = options.kind;
  17276. }
  17277. if (options.label) {
  17278. htmlTrackElement.label = options.label;
  17279. }
  17280. if (options.language || options.srclang) {
  17281. htmlTrackElement.srclang = options.language || options.srclang;
  17282. }
  17283. if (options.default) {
  17284. htmlTrackElement.default = options.default;
  17285. }
  17286. if (options.id) {
  17287. htmlTrackElement.id = options.id;
  17288. }
  17289. if (options.src) {
  17290. htmlTrackElement.src = options.src;
  17291. }
  17292. return htmlTrackElement;
  17293. }
  17294. /**
  17295. * Creates a remote text track object and returns an html track element.
  17296. *
  17297. * @param {Object} options The object should contain values for
  17298. * kind, language, label, and src (location of the WebVTT file)
  17299. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack
  17300. * will not be removed from the TextTrackList and HtmlTrackElementList
  17301. * after a source change
  17302. * @return {HTMLTrackElement} An Html Track Element.
  17303. * This can be an emulated {@link HTMLTrackElement} or a native one.
  17304. *
  17305. */
  17306. addRemoteTextTrack(options, manualCleanup) {
  17307. const htmlTrackElement = super.addRemoteTextTrack(options, manualCleanup);
  17308. if (this.featuresNativeTextTracks) {
  17309. this.el().appendChild(htmlTrackElement);
  17310. }
  17311. return htmlTrackElement;
  17312. }
  17313. /**
  17314. * Remove remote `TextTrack` from `TextTrackList` object
  17315. *
  17316. * @param {TextTrack} track
  17317. * `TextTrack` object to remove
  17318. */
  17319. removeRemoteTextTrack(track) {
  17320. super.removeRemoteTextTrack(track);
  17321. if (this.featuresNativeTextTracks) {
  17322. const tracks = this.$$('track');
  17323. let i = tracks.length;
  17324. while (i--) {
  17325. if (track === tracks[i] || track === tracks[i].track) {
  17326. this.el().removeChild(tracks[i]);
  17327. }
  17328. }
  17329. }
  17330. }
  17331. /**
  17332. * Gets available media playback quality metrics as specified by the W3C's Media
  17333. * Playback Quality API.
  17334. *
  17335. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  17336. *
  17337. * @return {Object}
  17338. * An object with supported media playback quality metrics
  17339. */
  17340. getVideoPlaybackQuality() {
  17341. if (typeof this.el().getVideoPlaybackQuality === 'function') {
  17342. return this.el().getVideoPlaybackQuality();
  17343. }
  17344. const videoPlaybackQuality = {};
  17345. if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {
  17346. videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
  17347. videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
  17348. }
  17349. if (window$1.performance) {
  17350. videoPlaybackQuality.creationTime = window$1.performance.now();
  17351. }
  17352. return videoPlaybackQuality;
  17353. }
  17354. }
  17355. /* HTML5 Support Testing ---------------------------------------------------- */
  17356. /**
  17357. * Element for testing browser HTML5 media capabilities
  17358. *
  17359. * @type {Element}
  17360. * @constant
  17361. * @private
  17362. */
  17363. defineLazyProperty(Html5, 'TEST_VID', function () {
  17364. if (!isReal()) {
  17365. return;
  17366. }
  17367. const video = document.createElement('video');
  17368. const track = document.createElement('track');
  17369. track.kind = 'captions';
  17370. track.srclang = 'en';
  17371. track.label = 'English';
  17372. video.appendChild(track);
  17373. return video;
  17374. });
  17375. /**
  17376. * Check if HTML5 media is supported by this browser/device.
  17377. *
  17378. * @return {boolean}
  17379. * - True if HTML5 media is supported.
  17380. * - False if HTML5 media is not supported.
  17381. */
  17382. Html5.isSupported = function () {
  17383. // IE with no Media Player is a LIAR! (#984)
  17384. try {
  17385. Html5.TEST_VID.volume = 0.5;
  17386. } catch (e) {
  17387. return false;
  17388. }
  17389. return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
  17390. };
  17391. /**
  17392. * Check if the tech can support the given type
  17393. *
  17394. * @param {string} type
  17395. * The mimetype to check
  17396. * @return {string} 'probably', 'maybe', or '' (empty string)
  17397. */
  17398. Html5.canPlayType = function (type) {
  17399. return Html5.TEST_VID.canPlayType(type);
  17400. };
  17401. /**
  17402. * Check if the tech can support the given source
  17403. *
  17404. * @param {Object} srcObj
  17405. * The source object
  17406. * @param {Object} options
  17407. * The options passed to the tech
  17408. * @return {string} 'probably', 'maybe', or '' (empty string)
  17409. */
  17410. Html5.canPlaySource = function (srcObj, options) {
  17411. return Html5.canPlayType(srcObj.type);
  17412. };
  17413. /**
  17414. * Check if the volume can be changed in this browser/device.
  17415. * Volume cannot be changed in a lot of mobile devices.
  17416. * Specifically, it can't be changed from 1 on iOS.
  17417. *
  17418. * @return {boolean}
  17419. * - True if volume can be controlled
  17420. * - False otherwise
  17421. */
  17422. Html5.canControlVolume = function () {
  17423. // IE will error if Windows Media Player not installed #3315
  17424. try {
  17425. const volume = Html5.TEST_VID.volume;
  17426. Html5.TEST_VID.volume = volume / 2 + 0.1;
  17427. const canControl = volume !== Html5.TEST_VID.volume;
  17428. // With the introduction of iOS 15, there are cases where the volume is read as
  17429. // changed but reverts back to its original state at the start of the next tick.
  17430. // To determine whether volume can be controlled on iOS,
  17431. // a timeout is set and the volume is checked asynchronously.
  17432. // Since `features` doesn't currently work asynchronously, the value is manually set.
  17433. if (canControl && IS_IOS) {
  17434. window$1.setTimeout(() => {
  17435. if (Html5 && Html5.prototype) {
  17436. Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;
  17437. }
  17438. });
  17439. // default iOS to false, which will be updated in the timeout above.
  17440. return false;
  17441. }
  17442. return canControl;
  17443. } catch (e) {
  17444. return false;
  17445. }
  17446. };
  17447. /**
  17448. * Check if the volume can be muted in this browser/device.
  17449. * Some devices, e.g. iOS, don't allow changing volume
  17450. * but permits muting/unmuting.
  17451. *
  17452. * @return {boolean}
  17453. * - True if volume can be muted
  17454. * - False otherwise
  17455. */
  17456. Html5.canMuteVolume = function () {
  17457. try {
  17458. const muted = Html5.TEST_VID.muted;
  17459. // in some versions of iOS muted property doesn't always
  17460. // work, so we want to set both property and attribute
  17461. Html5.TEST_VID.muted = !muted;
  17462. if (Html5.TEST_VID.muted) {
  17463. setAttribute(Html5.TEST_VID, 'muted', 'muted');
  17464. } else {
  17465. removeAttribute(Html5.TEST_VID, 'muted', 'muted');
  17466. }
  17467. return muted !== Html5.TEST_VID.muted;
  17468. } catch (e) {
  17469. return false;
  17470. }
  17471. };
  17472. /**
  17473. * Check if the playback rate can be changed in this browser/device.
  17474. *
  17475. * @return {boolean}
  17476. * - True if playback rate can be controlled
  17477. * - False otherwise
  17478. */
  17479. Html5.canControlPlaybackRate = function () {
  17480. // Playback rate API is implemented in Android Chrome, but doesn't do anything
  17481. // https://github.com/videojs/video.js/issues/3180
  17482. if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
  17483. return false;
  17484. }
  17485. // IE will error if Windows Media Player not installed #3315
  17486. try {
  17487. const playbackRate = Html5.TEST_VID.playbackRate;
  17488. Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
  17489. return playbackRate !== Html5.TEST_VID.playbackRate;
  17490. } catch (e) {
  17491. return false;
  17492. }
  17493. };
  17494. /**
  17495. * Check if we can override a video/audio elements attributes, with
  17496. * Object.defineProperty.
  17497. *
  17498. * @return {boolean}
  17499. * - True if builtin attributes can be overridden
  17500. * - False otherwise
  17501. */
  17502. Html5.canOverrideAttributes = function () {
  17503. // if we cannot overwrite the src/innerHTML property, there is no support
  17504. // iOS 7 safari for instance cannot do this.
  17505. try {
  17506. const noop = () => {};
  17507. Object.defineProperty(document.createElement('video'), 'src', {
  17508. get: noop,
  17509. set: noop
  17510. });
  17511. Object.defineProperty(document.createElement('audio'), 'src', {
  17512. get: noop,
  17513. set: noop
  17514. });
  17515. Object.defineProperty(document.createElement('video'), 'innerHTML', {
  17516. get: noop,
  17517. set: noop
  17518. });
  17519. Object.defineProperty(document.createElement('audio'), 'innerHTML', {
  17520. get: noop,
  17521. set: noop
  17522. });
  17523. } catch (e) {
  17524. return false;
  17525. }
  17526. return true;
  17527. };
  17528. /**
  17529. * Check to see if native `TextTrack`s are supported by this browser/device.
  17530. *
  17531. * @return {boolean}
  17532. * - True if native `TextTrack`s are supported.
  17533. * - False otherwise
  17534. */
  17535. Html5.supportsNativeTextTracks = function () {
  17536. return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
  17537. };
  17538. /**
  17539. * Check to see if native `VideoTrack`s are supported by this browser/device
  17540. *
  17541. * @return {boolean}
  17542. * - True if native `VideoTrack`s are supported.
  17543. * - False otherwise
  17544. */
  17545. Html5.supportsNativeVideoTracks = function () {
  17546. return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
  17547. };
  17548. /**
  17549. * Check to see if native `AudioTrack`s are supported by this browser/device
  17550. *
  17551. * @return {boolean}
  17552. * - True if native `AudioTrack`s are supported.
  17553. * - False otherwise
  17554. */
  17555. Html5.supportsNativeAudioTracks = function () {
  17556. return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
  17557. };
  17558. /**
  17559. * An array of events available on the Html5 tech.
  17560. *
  17561. * @private
  17562. * @type {Array}
  17563. */
  17564. 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'];
  17565. /**
  17566. * Boolean indicating whether the `Tech` supports volume control.
  17567. *
  17568. * @type {boolean}
  17569. * @default {@link Html5.canControlVolume}
  17570. */
  17571. /**
  17572. * Boolean indicating whether the `Tech` supports muting volume.
  17573. *
  17574. * @type {boolean}
  17575. * @default {@link Html5.canMuteVolume}
  17576. */
  17577. /**
  17578. * Boolean indicating whether the `Tech` supports changing the speed at which the media
  17579. * plays. Examples:
  17580. * - Set player to play 2x (twice) as fast
  17581. * - Set player to play 0.5x (half) as fast
  17582. *
  17583. * @type {boolean}
  17584. * @default {@link Html5.canControlPlaybackRate}
  17585. */
  17586. /**
  17587. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  17588. *
  17589. * @type {boolean}
  17590. * @default
  17591. */
  17592. /**
  17593. * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.
  17594. *
  17595. * @type {boolean}
  17596. * @default {@link Html5.supportsNativeTextTracks}
  17597. */
  17598. /**
  17599. * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.
  17600. *
  17601. * @type {boolean}
  17602. * @default {@link Html5.supportsNativeVideoTracks}
  17603. */
  17604. /**
  17605. * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.
  17606. *
  17607. * @type {boolean}
  17608. * @default {@link Html5.supportsNativeAudioTracks}
  17609. */
  17610. [['featuresMuteControl', 'canMuteVolume'], ['featuresPlaybackRate', 'canControlPlaybackRate'], ['featuresSourceset', 'canOverrideAttributes'], ['featuresNativeTextTracks', 'supportsNativeTextTracks'], ['featuresNativeVideoTracks', 'supportsNativeVideoTracks'], ['featuresNativeAudioTracks', 'supportsNativeAudioTracks']].forEach(function ([key, fn]) {
  17611. defineLazyProperty(Html5.prototype, key, () => Html5[fn](), true);
  17612. });
  17613. Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
  17614. /**
  17615. * Boolean indicating whether the `HTML5` tech currently supports the media element
  17616. * moving in the DOM. iOS breaks if you move the media element, so this is set this to
  17617. * false there. Everywhere else this should be true.
  17618. *
  17619. * @type {boolean}
  17620. * @default
  17621. */
  17622. Html5.prototype.movingMediaElementInDOM = !IS_IOS;
  17623. // TODO: Previous comment: No longer appears to be used. Can probably be removed.
  17624. // Is this true?
  17625. /**
  17626. * Boolean indicating whether the `HTML5` tech currently supports automatic media resize
  17627. * when going into fullscreen.
  17628. *
  17629. * @type {boolean}
  17630. * @default
  17631. */
  17632. Html5.prototype.featuresFullscreenResize = true;
  17633. /**
  17634. * Boolean indicating whether the `HTML5` tech currently supports the progress event.
  17635. * If this is false, manual `progress` events will be triggered instead.
  17636. *
  17637. * @type {boolean}
  17638. * @default
  17639. */
  17640. Html5.prototype.featuresProgressEvents = true;
  17641. /**
  17642. * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.
  17643. * If this is false, manual `timeupdate` events will be triggered instead.
  17644. *
  17645. * @default
  17646. */
  17647. Html5.prototype.featuresTimeupdateEvents = true;
  17648. /**
  17649. * Whether the HTML5 el supports `requestVideoFrameCallback`
  17650. *
  17651. * @type {boolean}
  17652. */
  17653. Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback);
  17654. Html5.disposeMediaElement = function (el) {
  17655. if (!el) {
  17656. return;
  17657. }
  17658. if (el.parentNode) {
  17659. el.parentNode.removeChild(el);
  17660. }
  17661. // remove any child track or source nodes to prevent their loading
  17662. while (el.hasChildNodes()) {
  17663. el.removeChild(el.firstChild);
  17664. }
  17665. // remove any src reference. not setting `src=''` because that causes a warning
  17666. // in firefox
  17667. el.removeAttribute('src');
  17668. // force the media element to update its loading state by calling load()
  17669. // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
  17670. if (typeof el.load === 'function') {
  17671. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  17672. (function () {
  17673. try {
  17674. el.load();
  17675. } catch (e) {
  17676. // not supported
  17677. }
  17678. })();
  17679. }
  17680. };
  17681. Html5.resetMediaElement = function (el) {
  17682. if (!el) {
  17683. return;
  17684. }
  17685. const sources = el.querySelectorAll('source');
  17686. let i = sources.length;
  17687. while (i--) {
  17688. el.removeChild(sources[i]);
  17689. }
  17690. // remove any src reference.
  17691. // not setting `src=''` because that throws an error
  17692. el.removeAttribute('src');
  17693. if (typeof el.load === 'function') {
  17694. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  17695. (function () {
  17696. try {
  17697. el.load();
  17698. } catch (e) {
  17699. // satisfy linter
  17700. }
  17701. })();
  17702. }
  17703. };
  17704. /* Native HTML5 element property wrapping ----------------------------------- */
  17705. // Wrap native boolean attributes with getters that check both property and attribute
  17706. // The list is as followed:
  17707. // muted, defaultMuted, autoplay, controls, loop, playsinline
  17708. [
  17709. /**
  17710. * Get the value of `muted` from the media element. `muted` indicates
  17711. * that the volume for the media should be set to silent. This does not actually change
  17712. * the `volume` attribute.
  17713. *
  17714. * @method Html5#muted
  17715. * @return {boolean}
  17716. * - True if the value of `volume` should be ignored and the audio set to silent.
  17717. * - False if the value of `volume` should be used.
  17718. *
  17719. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  17720. */
  17721. 'muted',
  17722. /**
  17723. * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
  17724. * whether the media should start muted or not. Only changes the default state of the
  17725. * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
  17726. * current state.
  17727. *
  17728. * @method Html5#defaultMuted
  17729. * @return {boolean}
  17730. * - The value of `defaultMuted` from the media element.
  17731. * - True indicates that the media should start muted.
  17732. * - False indicates that the media should not start muted
  17733. *
  17734. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  17735. */
  17736. 'defaultMuted',
  17737. /**
  17738. * Get the value of `autoplay` from the media element. `autoplay` indicates
  17739. * that the media should start to play as soon as the page is ready.
  17740. *
  17741. * @method Html5#autoplay
  17742. * @return {boolean}
  17743. * - The value of `autoplay` from the media element.
  17744. * - True indicates that the media should start as soon as the page loads.
  17745. * - False indicates that the media should not start as soon as the page loads.
  17746. *
  17747. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  17748. */
  17749. 'autoplay',
  17750. /**
  17751. * Get the value of `controls` from the media element. `controls` indicates
  17752. * whether the native media controls should be shown or hidden.
  17753. *
  17754. * @method Html5#controls
  17755. * @return {boolean}
  17756. * - The value of `controls` from the media element.
  17757. * - True indicates that native controls should be showing.
  17758. * - False indicates that native controls should be hidden.
  17759. *
  17760. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
  17761. */
  17762. 'controls',
  17763. /**
  17764. * Get the value of `loop` from the media element. `loop` indicates
  17765. * that the media should return to the start of the media and continue playing once
  17766. * it reaches the end.
  17767. *
  17768. * @method Html5#loop
  17769. * @return {boolean}
  17770. * - The value of `loop` from the media element.
  17771. * - True indicates that playback should seek back to start once
  17772. * the end of a media is reached.
  17773. * - False indicates that playback should not loop back to the start when the
  17774. * end of the media is reached.
  17775. *
  17776. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  17777. */
  17778. 'loop',
  17779. /**
  17780. * Get the value of `playsinline` from the media element. `playsinline` indicates
  17781. * to the browser that non-fullscreen playback is preferred when fullscreen
  17782. * playback is the native default, such as in iOS Safari.
  17783. *
  17784. * @method Html5#playsinline
  17785. * @return {boolean}
  17786. * - The value of `playsinline` from the media element.
  17787. * - True indicates that the media should play inline.
  17788. * - False indicates that the media should not play inline.
  17789. *
  17790. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  17791. */
  17792. 'playsinline'].forEach(function (prop) {
  17793. Html5.prototype[prop] = function () {
  17794. return this.el_[prop] || this.el_.hasAttribute(prop);
  17795. };
  17796. });
  17797. // Wrap native boolean attributes with setters that set both property and attribute
  17798. // The list is as followed:
  17799. // setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline
  17800. // setControls is special-cased above
  17801. [
  17802. /**
  17803. * Set the value of `muted` on the media element. `muted` indicates that the current
  17804. * audio level should be silent.
  17805. *
  17806. * @method Html5#setMuted
  17807. * @param {boolean} muted
  17808. * - True if the audio should be set to silent
  17809. * - False otherwise
  17810. *
  17811. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  17812. */
  17813. 'muted',
  17814. /**
  17815. * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
  17816. * audio level should be silent, but will only effect the muted level on initial playback..
  17817. *
  17818. * @method Html5.prototype.setDefaultMuted
  17819. * @param {boolean} defaultMuted
  17820. * - True if the audio should be set to silent
  17821. * - False otherwise
  17822. *
  17823. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  17824. */
  17825. 'defaultMuted',
  17826. /**
  17827. * Set the value of `autoplay` on the media element. `autoplay` indicates
  17828. * that the media should start to play as soon as the page is ready.
  17829. *
  17830. * @method Html5#setAutoplay
  17831. * @param {boolean} autoplay
  17832. * - True indicates that the media should start as soon as the page loads.
  17833. * - False indicates that the media should not start as soon as the page loads.
  17834. *
  17835. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  17836. */
  17837. 'autoplay',
  17838. /**
  17839. * Set the value of `loop` on the media element. `loop` indicates
  17840. * that the media should return to the start of the media and continue playing once
  17841. * it reaches the end.
  17842. *
  17843. * @method Html5#setLoop
  17844. * @param {boolean} loop
  17845. * - True indicates that playback should seek back to start once
  17846. * the end of a media is reached.
  17847. * - False indicates that playback should not loop back to the start when the
  17848. * end of the media is reached.
  17849. *
  17850. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  17851. */
  17852. 'loop',
  17853. /**
  17854. * Set the value of `playsinline` from the media element. `playsinline` indicates
  17855. * to the browser that non-fullscreen playback is preferred when fullscreen
  17856. * playback is the native default, such as in iOS Safari.
  17857. *
  17858. * @method Html5#setPlaysinline
  17859. * @param {boolean} playsinline
  17860. * - True indicates that the media should play inline.
  17861. * - False indicates that the media should not play inline.
  17862. *
  17863. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  17864. */
  17865. 'playsinline'].forEach(function (prop) {
  17866. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  17867. this.el_[prop] = v;
  17868. if (v) {
  17869. this.el_.setAttribute(prop, prop);
  17870. } else {
  17871. this.el_.removeAttribute(prop);
  17872. }
  17873. };
  17874. });
  17875. // Wrap native properties with a getter
  17876. // The list is as followed
  17877. // paused, currentTime, buffered, volume, poster, preload, error, seeking
  17878. // seekable, ended, playbackRate, defaultPlaybackRate, disablePictureInPicture
  17879. // played, networkState, readyState, videoWidth, videoHeight, crossOrigin
  17880. [
  17881. /**
  17882. * Get the value of `paused` from the media element. `paused` indicates whether the media element
  17883. * is currently paused or not.
  17884. *
  17885. * @method Html5#paused
  17886. * @return {boolean}
  17887. * The value of `paused` from the media element.
  17888. *
  17889. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
  17890. */
  17891. 'paused',
  17892. /**
  17893. * Get the value of `currentTime` from the media element. `currentTime` indicates
  17894. * the current second that the media is at in playback.
  17895. *
  17896. * @method Html5#currentTime
  17897. * @return {number}
  17898. * The value of `currentTime` from the media element.
  17899. *
  17900. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
  17901. */
  17902. 'currentTime',
  17903. /**
  17904. * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
  17905. * object that represents the parts of the media that are already downloaded and
  17906. * available for playback.
  17907. *
  17908. * @method Html5#buffered
  17909. * @return {TimeRange}
  17910. * The value of `buffered` from the media element.
  17911. *
  17912. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
  17913. */
  17914. 'buffered',
  17915. /**
  17916. * Get the value of `volume` from the media element. `volume` indicates
  17917. * the current playback volume of audio for a media. `volume` will be a value from 0
  17918. * (silent) to 1 (loudest and default).
  17919. *
  17920. * @method Html5#volume
  17921. * @return {number}
  17922. * The value of `volume` from the media element. Value will be between 0-1.
  17923. *
  17924. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  17925. */
  17926. 'volume',
  17927. /**
  17928. * Get the value of `poster` from the media element. `poster` indicates
  17929. * that the url of an image file that can/will be shown when no media data is available.
  17930. *
  17931. * @method Html5#poster
  17932. * @return {string}
  17933. * The value of `poster` from the media element. Value will be a url to an
  17934. * image.
  17935. *
  17936. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
  17937. */
  17938. 'poster',
  17939. /**
  17940. * Get the value of `preload` from the media element. `preload` indicates
  17941. * what should download before the media is interacted with. It can have the following
  17942. * values:
  17943. * - none: nothing should be downloaded
  17944. * - metadata: poster and the first few frames of the media may be downloaded to get
  17945. * media dimensions and other metadata
  17946. * - auto: allow the media and metadata for the media to be downloaded before
  17947. * interaction
  17948. *
  17949. * @method Html5#preload
  17950. * @return {string}
  17951. * The value of `preload` from the media element. Will be 'none', 'metadata',
  17952. * or 'auto'.
  17953. *
  17954. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  17955. */
  17956. 'preload',
  17957. /**
  17958. * Get the value of the `error` from the media element. `error` indicates any
  17959. * MediaError that may have occurred during playback. If error returns null there is no
  17960. * current error.
  17961. *
  17962. * @method Html5#error
  17963. * @return {MediaError|null}
  17964. * The value of `error` from the media element. Will be `MediaError` if there
  17965. * is a current error and null otherwise.
  17966. *
  17967. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
  17968. */
  17969. 'error',
  17970. /**
  17971. * Get the value of `seeking` from the media element. `seeking` indicates whether the
  17972. * media is currently seeking to a new position or not.
  17973. *
  17974. * @method Html5#seeking
  17975. * @return {boolean}
  17976. * - The value of `seeking` from the media element.
  17977. * - True indicates that the media is currently seeking to a new position.
  17978. * - False indicates that the media is not seeking to a new position at this time.
  17979. *
  17980. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
  17981. */
  17982. 'seeking',
  17983. /**
  17984. * Get the value of `seekable` from the media element. `seekable` returns a
  17985. * `TimeRange` object indicating ranges of time that can currently be `seeked` to.
  17986. *
  17987. * @method Html5#seekable
  17988. * @return {TimeRange}
  17989. * The value of `seekable` from the media element. A `TimeRange` object
  17990. * indicating the current ranges of time that can be seeked to.
  17991. *
  17992. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
  17993. */
  17994. 'seekable',
  17995. /**
  17996. * Get the value of `ended` from the media element. `ended` indicates whether
  17997. * the media has reached the end or not.
  17998. *
  17999. * @method Html5#ended
  18000. * @return {boolean}
  18001. * - The value of `ended` from the media element.
  18002. * - True indicates that the media has ended.
  18003. * - False indicates that the media has not ended.
  18004. *
  18005. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
  18006. */
  18007. 'ended',
  18008. /**
  18009. * Get the value of `playbackRate` from the media element. `playbackRate` indicates
  18010. * the rate at which the media is currently playing back. Examples:
  18011. * - if playbackRate is set to 2, media will play twice as fast.
  18012. * - if playbackRate is set to 0.5, media will play half as fast.
  18013. *
  18014. * @method Html5#playbackRate
  18015. * @return {number}
  18016. * The value of `playbackRate` from the media element. A number indicating
  18017. * the current playback speed of the media, where 1 is normal speed.
  18018. *
  18019. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18020. */
  18021. 'playbackRate',
  18022. /**
  18023. * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
  18024. * the rate at which the media is currently playing back. This value will not indicate the current
  18025. * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
  18026. *
  18027. * Examples:
  18028. * - if defaultPlaybackRate is set to 2, media will play twice as fast.
  18029. * - if defaultPlaybackRate is set to 0.5, media will play half as fast.
  18030. *
  18031. * @method Html5.prototype.defaultPlaybackRate
  18032. * @return {number}
  18033. * The value of `defaultPlaybackRate` from the media element. A number indicating
  18034. * the current playback speed of the media, where 1 is normal speed.
  18035. *
  18036. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18037. */
  18038. 'defaultPlaybackRate',
  18039. /**
  18040. * Get the value of 'disablePictureInPicture' from the video element.
  18041. *
  18042. * @method Html5#disablePictureInPicture
  18043. * @return {boolean} value
  18044. * - The value of `disablePictureInPicture` from the video element.
  18045. * - True indicates that the video can't be played in Picture-In-Picture mode
  18046. * - False indicates that the video can be played in Picture-In-Picture mode
  18047. *
  18048. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  18049. */
  18050. 'disablePictureInPicture',
  18051. /**
  18052. * Get the value of `played` from the media element. `played` returns a `TimeRange`
  18053. * object representing points in the media timeline that have been played.
  18054. *
  18055. * @method Html5#played
  18056. * @return {TimeRange}
  18057. * The value of `played` from the media element. A `TimeRange` object indicating
  18058. * the ranges of time that have been played.
  18059. *
  18060. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
  18061. */
  18062. 'played',
  18063. /**
  18064. * Get the value of `networkState` from the media element. `networkState` indicates
  18065. * the current network state. It returns an enumeration from the following list:
  18066. * - 0: NETWORK_EMPTY
  18067. * - 1: NETWORK_IDLE
  18068. * - 2: NETWORK_LOADING
  18069. * - 3: NETWORK_NO_SOURCE
  18070. *
  18071. * @method Html5#networkState
  18072. * @return {number}
  18073. * The value of `networkState` from the media element. This will be a number
  18074. * from the list in the description.
  18075. *
  18076. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
  18077. */
  18078. 'networkState',
  18079. /**
  18080. * Get the value of `readyState` from the media element. `readyState` indicates
  18081. * the current state of the media element. It returns an enumeration from the
  18082. * following list:
  18083. * - 0: HAVE_NOTHING
  18084. * - 1: HAVE_METADATA
  18085. * - 2: HAVE_CURRENT_DATA
  18086. * - 3: HAVE_FUTURE_DATA
  18087. * - 4: HAVE_ENOUGH_DATA
  18088. *
  18089. * @method Html5#readyState
  18090. * @return {number}
  18091. * The value of `readyState` from the media element. This will be a number
  18092. * from the list in the description.
  18093. *
  18094. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
  18095. */
  18096. 'readyState',
  18097. /**
  18098. * Get the value of `videoWidth` from the video element. `videoWidth` indicates
  18099. * the current width of the video in css pixels.
  18100. *
  18101. * @method Html5#videoWidth
  18102. * @return {number}
  18103. * The value of `videoWidth` from the video element. This will be a number
  18104. * in css pixels.
  18105. *
  18106. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  18107. */
  18108. 'videoWidth',
  18109. /**
  18110. * Get the value of `videoHeight` from the video element. `videoHeight` indicates
  18111. * the current height of the video in css pixels.
  18112. *
  18113. * @method Html5#videoHeight
  18114. * @return {number}
  18115. * The value of `videoHeight` from the video element. This will be a number
  18116. * in css pixels.
  18117. *
  18118. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  18119. */
  18120. 'videoHeight',
  18121. /**
  18122. * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates
  18123. * to the browser that should sent the cookies along with the requests for the
  18124. * different assets/playlists
  18125. *
  18126. * @method Html5#crossOrigin
  18127. * @return {string}
  18128. * - anonymous indicates that the media should not sent cookies.
  18129. * - use-credentials indicates that the media should sent cookies along the requests.
  18130. *
  18131. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  18132. */
  18133. 'crossOrigin'].forEach(function (prop) {
  18134. Html5.prototype[prop] = function () {
  18135. return this.el_[prop];
  18136. };
  18137. });
  18138. // Wrap native properties with a setter in this format:
  18139. // set + toTitleCase(name)
  18140. // The list is as follows:
  18141. // setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate,
  18142. // setDisablePictureInPicture, setCrossOrigin
  18143. [
  18144. /**
  18145. * Set the value of `volume` on the media element. `volume` indicates the current
  18146. * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
  18147. * so on.
  18148. *
  18149. * @method Html5#setVolume
  18150. * @param {number} percentAsDecimal
  18151. * The volume percent as a decimal. Valid range is from 0-1.
  18152. *
  18153. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  18154. */
  18155. 'volume',
  18156. /**
  18157. * Set the value of `src` on the media element. `src` indicates the current
  18158. * {@link Tech~SourceObject} for the media.
  18159. *
  18160. * @method Html5#setSrc
  18161. * @param {Tech~SourceObject} src
  18162. * The source object to set as the current source.
  18163. *
  18164. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
  18165. */
  18166. 'src',
  18167. /**
  18168. * Set the value of `poster` on the media element. `poster` is the url to
  18169. * an image file that can/will be shown when no media data is available.
  18170. *
  18171. * @method Html5#setPoster
  18172. * @param {string} poster
  18173. * The url to an image that should be used as the `poster` for the media
  18174. * element.
  18175. *
  18176. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
  18177. */
  18178. 'poster',
  18179. /**
  18180. * Set the value of `preload` on the media element. `preload` indicates
  18181. * what should download before the media is interacted with. It can have the following
  18182. * values:
  18183. * - none: nothing should be downloaded
  18184. * - metadata: poster and the first few frames of the media may be downloaded to get
  18185. * media dimensions and other metadata
  18186. * - auto: allow the media and metadata for the media to be downloaded before
  18187. * interaction
  18188. *
  18189. * @method Html5#setPreload
  18190. * @param {string} preload
  18191. * The value of `preload` to set on the media element. Must be 'none', 'metadata',
  18192. * or 'auto'.
  18193. *
  18194. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  18195. */
  18196. 'preload',
  18197. /**
  18198. * Set the value of `playbackRate` on the media element. `playbackRate` indicates
  18199. * the rate at which the media should play back. Examples:
  18200. * - if playbackRate is set to 2, media will play twice as fast.
  18201. * - if playbackRate is set to 0.5, media will play half as fast.
  18202. *
  18203. * @method Html5#setPlaybackRate
  18204. * @return {number}
  18205. * The value of `playbackRate` from the media element. A number indicating
  18206. * the current playback speed of the media, where 1 is normal speed.
  18207. *
  18208. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18209. */
  18210. 'playbackRate',
  18211. /**
  18212. * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
  18213. * the rate at which the media should play back upon initial startup. Changing this value
  18214. * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
  18215. *
  18216. * Example Values:
  18217. * - if playbackRate is set to 2, media will play twice as fast.
  18218. * - if playbackRate is set to 0.5, media will play half as fast.
  18219. *
  18220. * @method Html5.prototype.setDefaultPlaybackRate
  18221. * @return {number}
  18222. * The value of `defaultPlaybackRate` from the media element. A number indicating
  18223. * the current playback speed of the media, where 1 is normal speed.
  18224. *
  18225. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
  18226. */
  18227. 'defaultPlaybackRate',
  18228. /**
  18229. * Prevents the browser from suggesting a Picture-in-Picture context menu
  18230. * or to request Picture-in-Picture automatically in some cases.
  18231. *
  18232. * @method Html5#setDisablePictureInPicture
  18233. * @param {boolean} value
  18234. * The true value will disable Picture-in-Picture mode.
  18235. *
  18236. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  18237. */
  18238. 'disablePictureInPicture',
  18239. /**
  18240. * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates
  18241. * to the browser that should sent the cookies along with the requests for the
  18242. * different assets/playlists
  18243. *
  18244. * @method Html5#setCrossOrigin
  18245. * @param {string} crossOrigin
  18246. * - anonymous indicates that the media should not sent cookies.
  18247. * - use-credentials indicates that the media should sent cookies along the requests.
  18248. *
  18249. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  18250. */
  18251. 'crossOrigin'].forEach(function (prop) {
  18252. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  18253. this.el_[prop] = v;
  18254. };
  18255. });
  18256. // wrap native functions with a function
  18257. // The list is as follows:
  18258. // pause, load, play
  18259. [
  18260. /**
  18261. * A wrapper around the media elements `pause` function. This will call the `HTML5`
  18262. * media elements `pause` function.
  18263. *
  18264. * @method Html5#pause
  18265. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
  18266. */
  18267. 'pause',
  18268. /**
  18269. * A wrapper around the media elements `load` function. This will call the `HTML5`s
  18270. * media element `load` function.
  18271. *
  18272. * @method Html5#load
  18273. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
  18274. */
  18275. 'load',
  18276. /**
  18277. * A wrapper around the media elements `play` function. This will call the `HTML5`s
  18278. * media element `play` function.
  18279. *
  18280. * @method Html5#play
  18281. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
  18282. */
  18283. 'play'].forEach(function (prop) {
  18284. Html5.prototype[prop] = function () {
  18285. return this.el_[prop]();
  18286. };
  18287. });
  18288. Tech.withSourceHandlers(Html5);
  18289. /**
  18290. * Native source handler for Html5, simply passes the source to the media element.
  18291. *
  18292. * @property {Tech~SourceObject} source
  18293. * The source object
  18294. *
  18295. * @property {Html5} tech
  18296. * The instance of the HTML5 tech.
  18297. */
  18298. Html5.nativeSourceHandler = {};
  18299. /**
  18300. * Check if the media element can play the given mime type.
  18301. *
  18302. * @param {string} type
  18303. * The mimetype to check
  18304. *
  18305. * @return {string}
  18306. * 'probably', 'maybe', or '' (empty string)
  18307. */
  18308. Html5.nativeSourceHandler.canPlayType = function (type) {
  18309. // IE without MediaPlayer throws an error (#519)
  18310. try {
  18311. return Html5.TEST_VID.canPlayType(type);
  18312. } catch (e) {
  18313. return '';
  18314. }
  18315. };
  18316. /**
  18317. * Check if the media element can handle a source natively.
  18318. *
  18319. * @param {Tech~SourceObject} source
  18320. * The source object
  18321. *
  18322. * @param {Object} [options]
  18323. * Options to be passed to the tech.
  18324. *
  18325. * @return {string}
  18326. * 'probably', 'maybe', or '' (empty string).
  18327. */
  18328. Html5.nativeSourceHandler.canHandleSource = function (source, options) {
  18329. // If a type was provided we should rely on that
  18330. if (source.type) {
  18331. return Html5.nativeSourceHandler.canPlayType(source.type);
  18332. // If no type, fall back to checking 'video/[EXTENSION]'
  18333. } else if (source.src) {
  18334. const ext = getFileExtension(source.src);
  18335. return Html5.nativeSourceHandler.canPlayType(`video/${ext}`);
  18336. }
  18337. return '';
  18338. };
  18339. /**
  18340. * Pass the source to the native media element.
  18341. *
  18342. * @param {Tech~SourceObject} source
  18343. * The source object
  18344. *
  18345. * @param {Html5} tech
  18346. * The instance of the Html5 tech
  18347. *
  18348. * @param {Object} [options]
  18349. * The options to pass to the source
  18350. */
  18351. Html5.nativeSourceHandler.handleSource = function (source, tech, options) {
  18352. tech.setSrc(source.src);
  18353. };
  18354. /**
  18355. * A noop for the native dispose function, as cleanup is not needed.
  18356. */
  18357. Html5.nativeSourceHandler.dispose = function () {};
  18358. // Register the native source handler
  18359. Html5.registerSourceHandler(Html5.nativeSourceHandler);
  18360. Tech.registerTech('Html5', Html5);
  18361. /**
  18362. * @file player.js
  18363. */
  18364. // The following tech events are simply re-triggered
  18365. // on the player when they happen
  18366. const TECH_EVENTS_RETRIGGER = [
  18367. /**
  18368. * Fired while the user agent is downloading media data.
  18369. *
  18370. * @event Player#progress
  18371. * @type {Event}
  18372. */
  18373. /**
  18374. * Retrigger the `progress` event that was triggered by the {@link Tech}.
  18375. *
  18376. * @private
  18377. * @method Player#handleTechProgress_
  18378. * @fires Player#progress
  18379. * @listens Tech#progress
  18380. */
  18381. 'progress',
  18382. /**
  18383. * Fires when the loading of an audio/video is aborted.
  18384. *
  18385. * @event Player#abort
  18386. * @type {Event}
  18387. */
  18388. /**
  18389. * Retrigger the `abort` event that was triggered by the {@link Tech}.
  18390. *
  18391. * @private
  18392. * @method Player#handleTechAbort_
  18393. * @fires Player#abort
  18394. * @listens Tech#abort
  18395. */
  18396. 'abort',
  18397. /**
  18398. * Fires when the browser is intentionally not getting media data.
  18399. *
  18400. * @event Player#suspend
  18401. * @type {Event}
  18402. */
  18403. /**
  18404. * Retrigger the `suspend` event that was triggered by the {@link Tech}.
  18405. *
  18406. * @private
  18407. * @method Player#handleTechSuspend_
  18408. * @fires Player#suspend
  18409. * @listens Tech#suspend
  18410. */
  18411. 'suspend',
  18412. /**
  18413. * Fires when the current playlist is empty.
  18414. *
  18415. * @event Player#emptied
  18416. * @type {Event}
  18417. */
  18418. /**
  18419. * Retrigger the `emptied` event that was triggered by the {@link Tech}.
  18420. *
  18421. * @private
  18422. * @method Player#handleTechEmptied_
  18423. * @fires Player#emptied
  18424. * @listens Tech#emptied
  18425. */
  18426. 'emptied',
  18427. /**
  18428. * Fires when the browser is trying to get media data, but data is not available.
  18429. *
  18430. * @event Player#stalled
  18431. * @type {Event}
  18432. */
  18433. /**
  18434. * Retrigger the `stalled` event that was triggered by the {@link Tech}.
  18435. *
  18436. * @private
  18437. * @method Player#handleTechStalled_
  18438. * @fires Player#stalled
  18439. * @listens Tech#stalled
  18440. */
  18441. 'stalled',
  18442. /**
  18443. * Fires when the browser has loaded meta data for the audio/video.
  18444. *
  18445. * @event Player#loadedmetadata
  18446. * @type {Event}
  18447. */
  18448. /**
  18449. * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
  18450. *
  18451. * @private
  18452. * @method Player#handleTechLoadedmetadata_
  18453. * @fires Player#loadedmetadata
  18454. * @listens Tech#loadedmetadata
  18455. */
  18456. 'loadedmetadata',
  18457. /**
  18458. * Fires when the browser has loaded the current frame of the audio/video.
  18459. *
  18460. * @event Player#loadeddata
  18461. * @type {event}
  18462. */
  18463. /**
  18464. * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
  18465. *
  18466. * @private
  18467. * @method Player#handleTechLoaddeddata_
  18468. * @fires Player#loadeddata
  18469. * @listens Tech#loadeddata
  18470. */
  18471. 'loadeddata',
  18472. /**
  18473. * Fires when the current playback position has changed.
  18474. *
  18475. * @event Player#timeupdate
  18476. * @type {event}
  18477. */
  18478. /**
  18479. * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
  18480. *
  18481. * @private
  18482. * @method Player#handleTechTimeUpdate_
  18483. * @fires Player#timeupdate
  18484. * @listens Tech#timeupdate
  18485. */
  18486. 'timeupdate',
  18487. /**
  18488. * Fires when the video's intrinsic dimensions change
  18489. *
  18490. * @event Player#resize
  18491. * @type {event}
  18492. */
  18493. /**
  18494. * Retrigger the `resize` event that was triggered by the {@link Tech}.
  18495. *
  18496. * @private
  18497. * @method Player#handleTechResize_
  18498. * @fires Player#resize
  18499. * @listens Tech#resize
  18500. */
  18501. 'resize',
  18502. /**
  18503. * Fires when the volume has been changed
  18504. *
  18505. * @event Player#volumechange
  18506. * @type {event}
  18507. */
  18508. /**
  18509. * Retrigger the `volumechange` event that was triggered by the {@link Tech}.
  18510. *
  18511. * @private
  18512. * @method Player#handleTechVolumechange_
  18513. * @fires Player#volumechange
  18514. * @listens Tech#volumechange
  18515. */
  18516. 'volumechange',
  18517. /**
  18518. * Fires when the text track has been changed
  18519. *
  18520. * @event Player#texttrackchange
  18521. * @type {event}
  18522. */
  18523. /**
  18524. * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
  18525. *
  18526. * @private
  18527. * @method Player#handleTechTexttrackchange_
  18528. * @fires Player#texttrackchange
  18529. * @listens Tech#texttrackchange
  18530. */
  18531. 'texttrackchange'];
  18532. // events to queue when playback rate is zero
  18533. // this is a hash for the sole purpose of mapping non-camel-cased event names
  18534. // to camel-cased function names
  18535. const TECH_EVENTS_QUEUE = {
  18536. canplay: 'CanPlay',
  18537. canplaythrough: 'CanPlayThrough',
  18538. playing: 'Playing',
  18539. seeked: 'Seeked'
  18540. };
  18541. const BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
  18542. const BREAKPOINT_CLASSES = {};
  18543. // grep: vjs-layout-tiny
  18544. // grep: vjs-layout-x-small
  18545. // grep: vjs-layout-small
  18546. // grep: vjs-layout-medium
  18547. // grep: vjs-layout-large
  18548. // grep: vjs-layout-x-large
  18549. // grep: vjs-layout-huge
  18550. BREAKPOINT_ORDER.forEach(k => {
  18551. const v = k.charAt(0) === 'x' ? `x-${k.substring(1)}` : k;
  18552. BREAKPOINT_CLASSES[k] = `vjs-layout-${v}`;
  18553. });
  18554. const DEFAULT_BREAKPOINTS = {
  18555. tiny: 210,
  18556. xsmall: 320,
  18557. small: 425,
  18558. medium: 768,
  18559. large: 1440,
  18560. xlarge: 2560,
  18561. huge: Infinity
  18562. };
  18563. /**
  18564. * An instance of the `Player` class is created when any of the Video.js setup methods
  18565. * are used to initialize a video.
  18566. *
  18567. * After an instance has been created it can be accessed globally in three ways:
  18568. * 1. By calling `videojs.getPlayer('example_video_1');`
  18569. * 2. By calling `videojs('example_video_1');` (not recomended)
  18570. * 2. By using it directly via `videojs.players.example_video_1;`
  18571. *
  18572. * @extends Component
  18573. * @global
  18574. */
  18575. class Player extends Component$1 {
  18576. /**
  18577. * Create an instance of this class.
  18578. *
  18579. * @param {Element} tag
  18580. * The original video DOM element used for configuring options.
  18581. *
  18582. * @param {Object} [options]
  18583. * Object of option names and values.
  18584. *
  18585. * @param {Function} [ready]
  18586. * Ready callback function.
  18587. */
  18588. constructor(tag, options, ready) {
  18589. // Make sure tag ID exists
  18590. tag.id = tag.id || options.id || `vjs_video_${newGUID()}`;
  18591. // Set Options
  18592. // The options argument overrides options set in the video tag
  18593. // which overrides globally set options.
  18594. // This latter part coincides with the load order
  18595. // (tag must exist before Player)
  18596. options = Object.assign(Player.getTagSettings(tag), options);
  18597. // Delay the initialization of children because we need to set up
  18598. // player properties first, and can't use `this` before `super()`
  18599. options.initChildren = false;
  18600. // Same with creating the element
  18601. options.createEl = false;
  18602. // don't auto mixin the evented mixin
  18603. options.evented = false;
  18604. // we don't want the player to report touch activity on itself
  18605. // see enableTouchActivity in Component
  18606. options.reportTouchActivity = false;
  18607. // If language is not set, get the closest lang attribute
  18608. if (!options.language) {
  18609. const closest = tag.closest('[lang]');
  18610. if (closest) {
  18611. options.language = closest.getAttribute('lang');
  18612. }
  18613. }
  18614. // Run base component initializing with new options
  18615. super(null, options, ready);
  18616. // Create bound methods for document listeners.
  18617. this.boundDocumentFullscreenChange_ = e => this.documentFullscreenChange_(e);
  18618. this.boundFullWindowOnEscKey_ = e => this.fullWindowOnEscKey(e);
  18619. this.boundUpdateStyleEl_ = e => this.updateStyleEl_(e);
  18620. this.boundApplyInitTime_ = e => this.applyInitTime_(e);
  18621. this.boundUpdateCurrentBreakpoint_ = e => this.updateCurrentBreakpoint_(e);
  18622. this.boundHandleTechClick_ = e => this.handleTechClick_(e);
  18623. this.boundHandleTechDoubleClick_ = e => this.handleTechDoubleClick_(e);
  18624. this.boundHandleTechTouchStart_ = e => this.handleTechTouchStart_(e);
  18625. this.boundHandleTechTouchMove_ = e => this.handleTechTouchMove_(e);
  18626. this.boundHandleTechTouchEnd_ = e => this.handleTechTouchEnd_(e);
  18627. this.boundHandleTechTap_ = e => this.handleTechTap_(e);
  18628. // default isFullscreen_ to false
  18629. this.isFullscreen_ = false;
  18630. // create logger
  18631. this.log = createLogger(this.id_);
  18632. // Hold our own reference to fullscreen api so it can be mocked in tests
  18633. this.fsApi_ = FullscreenApi;
  18634. // Tracks when a tech changes the poster
  18635. this.isPosterFromTech_ = false;
  18636. // Holds callback info that gets queued when playback rate is zero
  18637. // and a seek is happening
  18638. this.queuedCallbacks_ = [];
  18639. // Turn off API access because we're loading a new tech that might load asynchronously
  18640. this.isReady_ = false;
  18641. // Init state hasStarted_
  18642. this.hasStarted_ = false;
  18643. // Init state userActive_
  18644. this.userActive_ = false;
  18645. // Init debugEnabled_
  18646. this.debugEnabled_ = false;
  18647. // Init state audioOnlyMode_
  18648. this.audioOnlyMode_ = false;
  18649. // Init state audioPosterMode_
  18650. this.audioPosterMode_ = false;
  18651. // Init state audioOnlyCache_
  18652. this.audioOnlyCache_ = {
  18653. playerHeight: null,
  18654. hiddenChildren: []
  18655. };
  18656. // if the global option object was accidentally blown away by
  18657. // someone, bail early with an informative error
  18658. if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) {
  18659. throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
  18660. }
  18661. // Store the original tag used to set options
  18662. this.tag = tag;
  18663. // Store the tag attributes used to restore html5 element
  18664. this.tagAttributes = tag && getAttributes(tag);
  18665. // Update current language
  18666. this.language(this.options_.language);
  18667. // Update Supported Languages
  18668. if (options.languages) {
  18669. // Normalise player option languages to lowercase
  18670. const languagesToLower = {};
  18671. Object.getOwnPropertyNames(options.languages).forEach(function (name) {
  18672. languagesToLower[name.toLowerCase()] = options.languages[name];
  18673. });
  18674. this.languages_ = languagesToLower;
  18675. } else {
  18676. this.languages_ = Player.prototype.options_.languages;
  18677. }
  18678. this.resetCache_();
  18679. // Set poster
  18680. this.poster_ = options.poster || '';
  18681. // Set controls
  18682. this.controls_ = !!options.controls;
  18683. // Original tag settings stored in options
  18684. // now remove immediately so native controls don't flash.
  18685. // May be turned back on by HTML5 tech if nativeControlsForTouch is true
  18686. tag.controls = false;
  18687. tag.removeAttribute('controls');
  18688. this.changingSrc_ = false;
  18689. this.playCallbacks_ = [];
  18690. this.playTerminatedQueue_ = [];
  18691. // the attribute overrides the option
  18692. if (tag.hasAttribute('autoplay')) {
  18693. this.autoplay(true);
  18694. } else {
  18695. // otherwise use the setter to validate and
  18696. // set the correct value.
  18697. this.autoplay(this.options_.autoplay);
  18698. }
  18699. // check plugins
  18700. if (options.plugins) {
  18701. Object.keys(options.plugins).forEach(name => {
  18702. if (typeof this[name] !== 'function') {
  18703. throw new Error(`plugin "${name}" does not exist`);
  18704. }
  18705. });
  18706. }
  18707. /*
  18708. * Store the internal state of scrubbing
  18709. *
  18710. * @private
  18711. * @return {Boolean} True if the user is scrubbing
  18712. */
  18713. this.scrubbing_ = false;
  18714. this.el_ = this.createEl();
  18715. // Make this an evented object and use `el_` as its event bus.
  18716. evented(this, {
  18717. eventBusKey: 'el_'
  18718. });
  18719. // listen to document and player fullscreenchange handlers so we receive those events
  18720. // before a user can receive them so we can update isFullscreen appropriately.
  18721. // make sure that we listen to fullscreenchange events before everything else to make sure that
  18722. // our isFullscreen method is updated properly for internal components as well as external.
  18723. if (this.fsApi_.requestFullscreen) {
  18724. on(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  18725. this.on(this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  18726. }
  18727. if (this.fluid_) {
  18728. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  18729. }
  18730. // We also want to pass the original player options to each component and plugin
  18731. // as well so they don't need to reach back into the player for options later.
  18732. // We also need to do another copy of this.options_ so we don't end up with
  18733. // an infinite loop.
  18734. const playerOptionsCopy = merge$1(this.options_);
  18735. // Load plugins
  18736. if (options.plugins) {
  18737. Object.keys(options.plugins).forEach(name => {
  18738. this[name](options.plugins[name]);
  18739. });
  18740. }
  18741. // Enable debug mode to fire debugon event for all plugins.
  18742. if (options.debug) {
  18743. this.debug(true);
  18744. }
  18745. this.options_.playerOptions = playerOptionsCopy;
  18746. this.middleware_ = [];
  18747. this.playbackRates(options.playbackRates);
  18748. this.initChildren();
  18749. // Set isAudio based on whether or not an audio tag was used
  18750. this.isAudio(tag.nodeName.toLowerCase() === 'audio');
  18751. // Update controls className. Can't do this when the controls are initially
  18752. // set because the element doesn't exist yet.
  18753. if (this.controls()) {
  18754. this.addClass('vjs-controls-enabled');
  18755. } else {
  18756. this.addClass('vjs-controls-disabled');
  18757. }
  18758. // Set ARIA label and region role depending on player type
  18759. this.el_.setAttribute('role', 'region');
  18760. if (this.isAudio()) {
  18761. this.el_.setAttribute('aria-label', this.localize('Audio Player'));
  18762. } else {
  18763. this.el_.setAttribute('aria-label', this.localize('Video Player'));
  18764. }
  18765. if (this.isAudio()) {
  18766. this.addClass('vjs-audio');
  18767. }
  18768. // TODO: Make this smarter. Toggle user state between touching/mousing
  18769. // using events, since devices can have both touch and mouse events.
  18770. // TODO: Make this check be performed again when the window switches between monitors
  18771. // (See https://github.com/videojs/video.js/issues/5683)
  18772. if (TOUCH_ENABLED) {
  18773. this.addClass('vjs-touch-enabled');
  18774. }
  18775. // iOS Safari has broken hover handling
  18776. if (!IS_IOS) {
  18777. this.addClass('vjs-workinghover');
  18778. }
  18779. // Make player easily findable by ID
  18780. Player.players[this.id_] = this;
  18781. // Add a major version class to aid css in plugins
  18782. const majorVersion = version$6.split('.')[0];
  18783. this.addClass(`vjs-v${majorVersion}`);
  18784. // When the player is first initialized, trigger activity so components
  18785. // like the control bar show themselves if needed
  18786. this.userActive(true);
  18787. this.reportUserActivity();
  18788. this.one('play', e => this.listenForUserActivity_(e));
  18789. this.on('keydown', e => this.handleKeyDown(e));
  18790. this.on('languagechange', e => this.handleLanguagechange(e));
  18791. this.breakpoints(this.options_.breakpoints);
  18792. this.responsive(this.options_.responsive);
  18793. // Calling both the audio mode methods after the player is fully
  18794. // setup to be able to listen to the events triggered by them
  18795. this.on('ready', () => {
  18796. // Calling the audioPosterMode method first so that
  18797. // the audioOnlyMode can take precedence when both options are set to true
  18798. this.audioPosterMode(this.options_.audioPosterMode);
  18799. this.audioOnlyMode(this.options_.audioOnlyMode);
  18800. });
  18801. }
  18802. /**
  18803. * Destroys the video player and does any necessary cleanup.
  18804. *
  18805. * This is especially helpful if you are dynamically adding and removing videos
  18806. * to/from the DOM.
  18807. *
  18808. * @fires Player#dispose
  18809. */
  18810. dispose() {
  18811. /**
  18812. * Called when the player is being disposed of.
  18813. *
  18814. * @event Player#dispose
  18815. * @type {Event}
  18816. */
  18817. this.trigger('dispose');
  18818. // prevent dispose from being called twice
  18819. this.off('dispose');
  18820. // Make sure all player-specific document listeners are unbound. This is
  18821. off(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  18822. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  18823. if (this.styleEl_ && this.styleEl_.parentNode) {
  18824. this.styleEl_.parentNode.removeChild(this.styleEl_);
  18825. this.styleEl_ = null;
  18826. }
  18827. // Kill reference to this player
  18828. Player.players[this.id_] = null;
  18829. if (this.tag && this.tag.player) {
  18830. this.tag.player = null;
  18831. }
  18832. if (this.el_ && this.el_.player) {
  18833. this.el_.player = null;
  18834. }
  18835. if (this.tech_) {
  18836. this.tech_.dispose();
  18837. this.isPosterFromTech_ = false;
  18838. this.poster_ = '';
  18839. }
  18840. if (this.playerElIngest_) {
  18841. this.playerElIngest_ = null;
  18842. }
  18843. if (this.tag) {
  18844. this.tag = null;
  18845. }
  18846. clearCacheForPlayer(this);
  18847. // remove all event handlers for track lists
  18848. // all tracks and track listeners are removed on
  18849. // tech dispose
  18850. ALL.names.forEach(name => {
  18851. const props = ALL[name];
  18852. const list = this[props.getterName]();
  18853. // if it is not a native list
  18854. // we have to manually remove event listeners
  18855. if (list && list.off) {
  18856. list.off();
  18857. }
  18858. });
  18859. // the actual .el_ is removed here, or replaced if
  18860. super.dispose({
  18861. restoreEl: this.options_.restoreEl
  18862. });
  18863. }
  18864. /**
  18865. * Create the `Player`'s DOM element.
  18866. *
  18867. * @return {Element}
  18868. * The DOM element that gets created.
  18869. */
  18870. createEl() {
  18871. let tag = this.tag;
  18872. let el;
  18873. let playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
  18874. const divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
  18875. if (playerElIngest) {
  18876. el = this.el_ = tag.parentNode;
  18877. } else if (!divEmbed) {
  18878. el = this.el_ = super.createEl('div');
  18879. }
  18880. // Copy over all the attributes from the tag, including ID and class
  18881. // ID will now reference player box, not the video tag
  18882. const attrs = getAttributes(tag);
  18883. if (divEmbed) {
  18884. el = this.el_ = tag;
  18885. tag = this.tag = document.createElement('video');
  18886. while (el.children.length) {
  18887. tag.appendChild(el.firstChild);
  18888. }
  18889. if (!hasClass(el, 'video-js')) {
  18890. addClass(el, 'video-js');
  18891. }
  18892. el.appendChild(tag);
  18893. playerElIngest = this.playerElIngest_ = el;
  18894. // move properties over from our custom `video-js` element
  18895. // to our new `video` element. This will move things like
  18896. // `src` or `controls` that were set via js before the player
  18897. // was initialized.
  18898. Object.keys(el).forEach(k => {
  18899. try {
  18900. tag[k] = el[k];
  18901. } catch (e) {
  18902. // we got a a property like outerHTML which we can't actually copy, ignore it
  18903. }
  18904. });
  18905. }
  18906. // set tabindex to -1 to remove the video element from the focus order
  18907. tag.setAttribute('tabindex', '-1');
  18908. attrs.tabindex = '-1';
  18909. // Workaround for #4583 on Chrome (on Windows) with JAWS.
  18910. // See https://github.com/FreedomScientific/VFO-standards-support/issues/78
  18911. // Note that we can't detect if JAWS is being used, but this ARIA attribute
  18912. // doesn't change behavior of Chrome if JAWS is not being used
  18913. if (IS_CHROME && IS_WINDOWS) {
  18914. tag.setAttribute('role', 'application');
  18915. attrs.role = 'application';
  18916. }
  18917. // Remove width/height attrs from tag so CSS can make it 100% width/height
  18918. tag.removeAttribute('width');
  18919. tag.removeAttribute('height');
  18920. if ('width' in attrs) {
  18921. delete attrs.width;
  18922. }
  18923. if ('height' in attrs) {
  18924. delete attrs.height;
  18925. }
  18926. Object.getOwnPropertyNames(attrs).forEach(function (attr) {
  18927. // don't copy over the class attribute to the player element when we're in a div embed
  18928. // the class is already set up properly in the divEmbed case
  18929. // and we want to make sure that the `video-js` class doesn't get lost
  18930. if (!(divEmbed && attr === 'class')) {
  18931. el.setAttribute(attr, attrs[attr]);
  18932. }
  18933. if (divEmbed) {
  18934. tag.setAttribute(attr, attrs[attr]);
  18935. }
  18936. });
  18937. // Update tag id/class for use as HTML5 playback tech
  18938. // Might think we should do this after embedding in container so .vjs-tech class
  18939. // doesn't flash 100% width/height, but class only applies with .video-js parent
  18940. tag.playerId = tag.id;
  18941. tag.id += '_html5_api';
  18942. tag.className = 'vjs-tech';
  18943. // Make player findable on elements
  18944. tag.player = el.player = this;
  18945. // Default state of video is paused
  18946. this.addClass('vjs-paused');
  18947. // Add a style element in the player that we'll use to set the width/height
  18948. // of the player in a way that's still overridable by CSS, just like the
  18949. // video element
  18950. if (window$1.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
  18951. this.styleEl_ = createStyleElement('vjs-styles-dimensions');
  18952. const defaultsStyleEl = $('.vjs-styles-defaults');
  18953. const head = $('head');
  18954. head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
  18955. }
  18956. this.fill_ = false;
  18957. this.fluid_ = false;
  18958. // Pass in the width/height/aspectRatio options which will update the style el
  18959. this.width(this.options_.width);
  18960. this.height(this.options_.height);
  18961. this.fill(this.options_.fill);
  18962. this.fluid(this.options_.fluid);
  18963. this.aspectRatio(this.options_.aspectRatio);
  18964. // support both crossOrigin and crossorigin to reduce confusion and issues around the name
  18965. this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin);
  18966. // Hide any links within the video/audio tag,
  18967. // because IE doesn't hide them completely from screen readers.
  18968. const links = tag.getElementsByTagName('a');
  18969. for (let i = 0; i < links.length; i++) {
  18970. const linkEl = links.item(i);
  18971. addClass(linkEl, 'vjs-hidden');
  18972. linkEl.setAttribute('hidden', 'hidden');
  18973. }
  18974. // insertElFirst seems to cause the networkState to flicker from 3 to 2, so
  18975. // keep track of the original for later so we can know if the source originally failed
  18976. tag.initNetworkState_ = tag.networkState;
  18977. // Wrap video tag in div (el/box) container
  18978. if (tag.parentNode && !playerElIngest) {
  18979. tag.parentNode.insertBefore(el, tag);
  18980. }
  18981. // insert the tag as the first child of the player element
  18982. // then manually add it to the children array so that this.addChild
  18983. // will work properly for other components
  18984. //
  18985. // Breaks iPhone, fixed in HTML5 setup.
  18986. prependTo(tag, el);
  18987. this.children_.unshift(tag);
  18988. // Set lang attr on player to ensure CSS :lang() in consistent with player
  18989. // if it's been set to something different to the doc
  18990. this.el_.setAttribute('lang', this.language_);
  18991. this.el_.setAttribute('translate', 'no');
  18992. this.el_ = el;
  18993. return el;
  18994. }
  18995. /**
  18996. * Get or set the `Player`'s crossOrigin option. For the HTML5 player, this
  18997. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  18998. * behavior.
  18999. *
  19000. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  19001. *
  19002. * @param {string|null} [value]
  19003. * The value to set the `Player`'s crossOrigin to. If an argument is
  19004. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  19005. *
  19006. * @return {string|null|undefined}
  19007. * - The current crossOrigin value of the `Player` when getting.
  19008. * - undefined when setting
  19009. */
  19010. crossOrigin(value) {
  19011. // `null` can be set to unset a value
  19012. if (typeof value === 'undefined') {
  19013. return this.techGet_('crossOrigin');
  19014. }
  19015. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  19016. log$1.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  19017. return;
  19018. }
  19019. this.techCall_('setCrossOrigin', value);
  19020. if (this.posterImage) {
  19021. this.posterImage.crossOrigin(value);
  19022. }
  19023. return;
  19024. }
  19025. /**
  19026. * A getter/setter for the `Player`'s width. Returns the player's configured value.
  19027. * To get the current width use `currentWidth()`.
  19028. *
  19029. * @param {number} [value]
  19030. * The value to set the `Player`'s width to.
  19031. *
  19032. * @return {number}
  19033. * The current width of the `Player` when getting.
  19034. */
  19035. width(value) {
  19036. return this.dimension('width', value);
  19037. }
  19038. /**
  19039. * A getter/setter for the `Player`'s height. Returns the player's configured value.
  19040. * To get the current height use `currentheight()`.
  19041. *
  19042. * @param {number} [value]
  19043. * The value to set the `Player`'s height to.
  19044. *
  19045. * @return {number}
  19046. * The current height of the `Player` when getting.
  19047. */
  19048. height(value) {
  19049. return this.dimension('height', value);
  19050. }
  19051. /**
  19052. * A getter/setter for the `Player`'s width & height.
  19053. *
  19054. * @param {string} dimension
  19055. * This string can be:
  19056. * - 'width'
  19057. * - 'height'
  19058. *
  19059. * @param {number} [value]
  19060. * Value for dimension specified in the first argument.
  19061. *
  19062. * @return {number}
  19063. * The dimension arguments value when getting (width/height).
  19064. */
  19065. dimension(dimension, value) {
  19066. const privDimension = dimension + '_';
  19067. if (value === undefined) {
  19068. return this[privDimension] || 0;
  19069. }
  19070. if (value === '' || value === 'auto') {
  19071. // If an empty string is given, reset the dimension to be automatic
  19072. this[privDimension] = undefined;
  19073. this.updateStyleEl_();
  19074. return;
  19075. }
  19076. const parsedVal = parseFloat(value);
  19077. if (isNaN(parsedVal)) {
  19078. log$1.error(`Improper value "${value}" supplied for for ${dimension}`);
  19079. return;
  19080. }
  19081. this[privDimension] = parsedVal;
  19082. this.updateStyleEl_();
  19083. }
  19084. /**
  19085. * A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
  19086. *
  19087. * Turning this on will turn off fill mode.
  19088. *
  19089. * @param {boolean} [bool]
  19090. * - A value of true adds the class.
  19091. * - A value of false removes the class.
  19092. * - No value will be a getter.
  19093. *
  19094. * @return {boolean|undefined}
  19095. * - The value of fluid when getting.
  19096. * - `undefined` when setting.
  19097. */
  19098. fluid(bool) {
  19099. if (bool === undefined) {
  19100. return !!this.fluid_;
  19101. }
  19102. this.fluid_ = !!bool;
  19103. if (isEvented(this)) {
  19104. this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  19105. }
  19106. if (bool) {
  19107. this.addClass('vjs-fluid');
  19108. this.fill(false);
  19109. addEventedCallback(this, () => {
  19110. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  19111. });
  19112. } else {
  19113. this.removeClass('vjs-fluid');
  19114. }
  19115. this.updateStyleEl_();
  19116. }
  19117. /**
  19118. * A getter/setter/toggler for the vjs-fill `className` on the `Player`.
  19119. *
  19120. * Turning this on will turn off fluid mode.
  19121. *
  19122. * @param {boolean} [bool]
  19123. * - A value of true adds the class.
  19124. * - A value of false removes the class.
  19125. * - No value will be a getter.
  19126. *
  19127. * @return {boolean|undefined}
  19128. * - The value of fluid when getting.
  19129. * - `undefined` when setting.
  19130. */
  19131. fill(bool) {
  19132. if (bool === undefined) {
  19133. return !!this.fill_;
  19134. }
  19135. this.fill_ = !!bool;
  19136. if (bool) {
  19137. this.addClass('vjs-fill');
  19138. this.fluid(false);
  19139. } else {
  19140. this.removeClass('vjs-fill');
  19141. }
  19142. }
  19143. /**
  19144. * Get/Set the aspect ratio
  19145. *
  19146. * @param {string} [ratio]
  19147. * Aspect ratio for player
  19148. *
  19149. * @return {string|undefined}
  19150. * returns the current aspect ratio when getting
  19151. */
  19152. /**
  19153. * A getter/setter for the `Player`'s aspect ratio.
  19154. *
  19155. * @param {string} [ratio]
  19156. * The value to set the `Player`'s aspect ratio to.
  19157. *
  19158. * @return {string|undefined}
  19159. * - The current aspect ratio of the `Player` when getting.
  19160. * - undefined when setting
  19161. */
  19162. aspectRatio(ratio) {
  19163. if (ratio === undefined) {
  19164. return this.aspectRatio_;
  19165. }
  19166. // Check for width:height format
  19167. if (!/^\d+\:\d+$/.test(ratio)) {
  19168. throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
  19169. }
  19170. this.aspectRatio_ = ratio;
  19171. // We're assuming if you set an aspect ratio you want fluid mode,
  19172. // because in fixed mode you could calculate width and height yourself.
  19173. this.fluid(true);
  19174. this.updateStyleEl_();
  19175. }
  19176. /**
  19177. * Update styles of the `Player` element (height, width and aspect ratio).
  19178. *
  19179. * @private
  19180. * @listens Tech#loadedmetadata
  19181. */
  19182. updateStyleEl_() {
  19183. if (window$1.VIDEOJS_NO_DYNAMIC_STYLE === true) {
  19184. const width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
  19185. const height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
  19186. const techEl = this.tech_ && this.tech_.el();
  19187. if (techEl) {
  19188. if (width >= 0) {
  19189. techEl.width = width;
  19190. }
  19191. if (height >= 0) {
  19192. techEl.height = height;
  19193. }
  19194. }
  19195. return;
  19196. }
  19197. let width;
  19198. let height;
  19199. let aspectRatio;
  19200. let idClass;
  19201. // The aspect ratio is either used directly or to calculate width and height.
  19202. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
  19203. // Use any aspectRatio that's been specifically set
  19204. aspectRatio = this.aspectRatio_;
  19205. } else if (this.videoWidth() > 0) {
  19206. // Otherwise try to get the aspect ratio from the video metadata
  19207. aspectRatio = this.videoWidth() + ':' + this.videoHeight();
  19208. } else {
  19209. // Or use a default. The video element's is 2:1, but 16:9 is more common.
  19210. aspectRatio = '16:9';
  19211. }
  19212. // Get the ratio as a decimal we can use to calculate dimensions
  19213. const ratioParts = aspectRatio.split(':');
  19214. const ratioMultiplier = ratioParts[1] / ratioParts[0];
  19215. if (this.width_ !== undefined) {
  19216. // Use any width that's been specifically set
  19217. width = this.width_;
  19218. } else if (this.height_ !== undefined) {
  19219. // Or calculate the width from the aspect ratio if a height has been set
  19220. width = this.height_ / ratioMultiplier;
  19221. } else {
  19222. // Or use the video's metadata, or use the video el's default of 300
  19223. width = this.videoWidth() || 300;
  19224. }
  19225. if (this.height_ !== undefined) {
  19226. // Use any height that's been specifically set
  19227. height = this.height_;
  19228. } else {
  19229. // Otherwise calculate the height from the ratio and the width
  19230. height = width * ratioMultiplier;
  19231. }
  19232. // Ensure the CSS class is valid by starting with an alpha character
  19233. if (/^[^a-zA-Z]/.test(this.id())) {
  19234. idClass = 'dimensions-' + this.id();
  19235. } else {
  19236. idClass = this.id() + '-dimensions';
  19237. }
  19238. // Ensure the right class is still on the player for the style element
  19239. this.addClass(idClass);
  19240. setTextContent(this.styleEl_, `
  19241. .${idClass} {
  19242. width: ${width}px;
  19243. height: ${height}px;
  19244. }
  19245. .${idClass}.vjs-fluid:not(.vjs-audio-only-mode) {
  19246. padding-top: ${ratioMultiplier * 100}%;
  19247. }
  19248. `);
  19249. }
  19250. /**
  19251. * Load/Create an instance of playback {@link Tech} including element
  19252. * and API methods. Then append the `Tech` element in `Player` as a child.
  19253. *
  19254. * @param {string} techName
  19255. * name of the playback technology
  19256. *
  19257. * @param {string} source
  19258. * video source
  19259. *
  19260. * @private
  19261. */
  19262. loadTech_(techName, source) {
  19263. // Pause and remove current playback technology
  19264. if (this.tech_) {
  19265. this.unloadTech_();
  19266. }
  19267. const titleTechName = toTitleCase$1(techName);
  19268. const camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1);
  19269. // get rid of the HTML5 video tag as soon as we are using another tech
  19270. if (titleTechName !== 'Html5' && this.tag) {
  19271. Tech.getTech('Html5').disposeMediaElement(this.tag);
  19272. this.tag.player = null;
  19273. this.tag = null;
  19274. }
  19275. this.techName_ = titleTechName;
  19276. // Turn off API access because we're loading a new tech that might load asynchronously
  19277. this.isReady_ = false;
  19278. let autoplay = this.autoplay();
  19279. // if autoplay is a string (or `true` with normalizeAutoplay: true) we pass false to the tech
  19280. // because the player is going to handle autoplay on `loadstart`
  19281. if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeAutoplay) {
  19282. autoplay = false;
  19283. }
  19284. // Grab tech-specific options from player options and add source and parent element to use.
  19285. const techOptions = {
  19286. source,
  19287. autoplay,
  19288. 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
  19289. 'playerId': this.id(),
  19290. 'techId': `${this.id()}_${camelTechName}_api`,
  19291. 'playsinline': this.options_.playsinline,
  19292. 'preload': this.options_.preload,
  19293. 'loop': this.options_.loop,
  19294. 'disablePictureInPicture': this.options_.disablePictureInPicture,
  19295. 'muted': this.options_.muted,
  19296. 'poster': this.poster(),
  19297. 'language': this.language(),
  19298. 'playerElIngest': this.playerElIngest_ || false,
  19299. 'vtt.js': this.options_['vtt.js'],
  19300. 'canOverridePoster': !!this.options_.techCanOverridePoster,
  19301. 'enableSourceset': this.options_.enableSourceset
  19302. };
  19303. ALL.names.forEach(name => {
  19304. const props = ALL[name];
  19305. techOptions[props.getterName] = this[props.privateName];
  19306. });
  19307. Object.assign(techOptions, this.options_[titleTechName]);
  19308. Object.assign(techOptions, this.options_[camelTechName]);
  19309. Object.assign(techOptions, this.options_[techName.toLowerCase()]);
  19310. if (this.tag) {
  19311. techOptions.tag = this.tag;
  19312. }
  19313. if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
  19314. techOptions.startTime = this.cache_.currentTime;
  19315. }
  19316. // Initialize tech instance
  19317. const TechClass = Tech.getTech(techName);
  19318. if (!TechClass) {
  19319. throw new Error(`No Tech named '${titleTechName}' exists! '${titleTechName}' should be registered using videojs.registerTech()'`);
  19320. }
  19321. this.tech_ = new TechClass(techOptions);
  19322. // player.triggerReady is always async, so don't need this to be async
  19323. this.tech_.ready(bind_(this, this.handleTechReady_), true);
  19324. textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
  19325. // Listen to all HTML5-defined events and trigger them on the player
  19326. TECH_EVENTS_RETRIGGER.forEach(event => {
  19327. this.on(this.tech_, event, e => this[`handleTech${toTitleCase$1(event)}_`](e));
  19328. });
  19329. Object.keys(TECH_EVENTS_QUEUE).forEach(event => {
  19330. this.on(this.tech_, event, eventObj => {
  19331. if (this.tech_.playbackRate() === 0 && this.tech_.seeking()) {
  19332. this.queuedCallbacks_.push({
  19333. callback: this[`handleTech${TECH_EVENTS_QUEUE[event]}_`].bind(this),
  19334. event: eventObj
  19335. });
  19336. return;
  19337. }
  19338. this[`handleTech${TECH_EVENTS_QUEUE[event]}_`](eventObj);
  19339. });
  19340. });
  19341. this.on(this.tech_, 'loadstart', e => this.handleTechLoadStart_(e));
  19342. this.on(this.tech_, 'sourceset', e => this.handleTechSourceset_(e));
  19343. this.on(this.tech_, 'waiting', e => this.handleTechWaiting_(e));
  19344. this.on(this.tech_, 'ended', e => this.handleTechEnded_(e));
  19345. this.on(this.tech_, 'seeking', e => this.handleTechSeeking_(e));
  19346. this.on(this.tech_, 'play', e => this.handleTechPlay_(e));
  19347. this.on(this.tech_, 'pause', e => this.handleTechPause_(e));
  19348. this.on(this.tech_, 'durationchange', e => this.handleTechDurationChange_(e));
  19349. this.on(this.tech_, 'fullscreenchange', (e, data) => this.handleTechFullscreenChange_(e, data));
  19350. this.on(this.tech_, 'fullscreenerror', (e, err) => this.handleTechFullscreenError_(e, err));
  19351. this.on(this.tech_, 'enterpictureinpicture', e => this.handleTechEnterPictureInPicture_(e));
  19352. this.on(this.tech_, 'leavepictureinpicture', e => this.handleTechLeavePictureInPicture_(e));
  19353. this.on(this.tech_, 'error', e => this.handleTechError_(e));
  19354. this.on(this.tech_, 'posterchange', e => this.handleTechPosterChange_(e));
  19355. this.on(this.tech_, 'textdata', e => this.handleTechTextData_(e));
  19356. this.on(this.tech_, 'ratechange', e => this.handleTechRateChange_(e));
  19357. this.on(this.tech_, 'loadedmetadata', this.boundUpdateStyleEl_);
  19358. this.usingNativeControls(this.techGet_('controls'));
  19359. if (this.controls() && !this.usingNativeControls()) {
  19360. this.addTechControlsListeners_();
  19361. }
  19362. // Add the tech element in the DOM if it was not already there
  19363. // Make sure to not insert the original video element if using Html5
  19364. if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {
  19365. prependTo(this.tech_.el(), this.el());
  19366. }
  19367. // Get rid of the original video tag reference after the first tech is loaded
  19368. if (this.tag) {
  19369. this.tag.player = null;
  19370. this.tag = null;
  19371. }
  19372. }
  19373. /**
  19374. * Unload and dispose of the current playback {@link Tech}.
  19375. *
  19376. * @private
  19377. */
  19378. unloadTech_() {
  19379. // Save the current text tracks so that we can reuse the same text tracks with the next tech
  19380. ALL.names.forEach(name => {
  19381. const props = ALL[name];
  19382. this[props.privateName] = this[props.getterName]();
  19383. });
  19384. this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
  19385. this.isReady_ = false;
  19386. this.tech_.dispose();
  19387. this.tech_ = false;
  19388. if (this.isPosterFromTech_) {
  19389. this.poster_ = '';
  19390. this.trigger('posterchange');
  19391. }
  19392. this.isPosterFromTech_ = false;
  19393. }
  19394. /**
  19395. * Return a reference to the current {@link Tech}.
  19396. * It will print a warning by default about the danger of using the tech directly
  19397. * but any argument that is passed in will silence the warning.
  19398. *
  19399. * @param {*} [safety]
  19400. * Anything passed in to silence the warning
  19401. *
  19402. * @return {Tech}
  19403. * The Tech
  19404. */
  19405. tech(safety) {
  19406. if (safety === undefined) {
  19407. 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');
  19408. }
  19409. return this.tech_;
  19410. }
  19411. /**
  19412. * Set up click and touch listeners for the playback element
  19413. *
  19414. * - On desktops: a click on the video itself will toggle playback
  19415. * - On mobile devices: a click on the video toggles controls
  19416. * which is done by toggling the user state between active and
  19417. * inactive
  19418. * - A tap can signal that a user has become active or has become inactive
  19419. * e.g. a quick tap on an iPhone movie should reveal the controls. Another
  19420. * quick tap should hide them again (signaling the user is in an inactive
  19421. * viewing state)
  19422. * - In addition to this, we still want the user to be considered inactive after
  19423. * a few seconds of inactivity.
  19424. *
  19425. * > Note: the only part of iOS interaction we can't mimic with this setup
  19426. * is a touch and hold on the video element counting as activity in order to
  19427. * keep the controls showing, but that shouldn't be an issue. A touch and hold
  19428. * on any controls will still keep the user active
  19429. *
  19430. * @private
  19431. */
  19432. addTechControlsListeners_() {
  19433. // Make sure to remove all the previous listeners in case we are called multiple times.
  19434. this.removeTechControlsListeners_();
  19435. this.on(this.tech_, 'click', this.boundHandleTechClick_);
  19436. this.on(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  19437. // If the controls were hidden we don't want that to change without a tap event
  19438. // so we'll check if the controls were already showing before reporting user
  19439. // activity
  19440. this.on(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  19441. this.on(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  19442. this.on(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  19443. // The tap listener needs to come after the touchend listener because the tap
  19444. // listener cancels out any reportedUserActivity when setting userActive(false)
  19445. this.on(this.tech_, 'tap', this.boundHandleTechTap_);
  19446. }
  19447. /**
  19448. * Remove the listeners used for click and tap controls. This is needed for
  19449. * toggling to controls disabled, where a tap/touch should do nothing.
  19450. *
  19451. * @private
  19452. */
  19453. removeTechControlsListeners_() {
  19454. // We don't want to just use `this.off()` because there might be other needed
  19455. // listeners added by techs that extend this.
  19456. this.off(this.tech_, 'tap', this.boundHandleTechTap_);
  19457. this.off(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  19458. this.off(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  19459. this.off(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  19460. this.off(this.tech_, 'click', this.boundHandleTechClick_);
  19461. this.off(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  19462. }
  19463. /**
  19464. * Player waits for the tech to be ready
  19465. *
  19466. * @private
  19467. */
  19468. handleTechReady_() {
  19469. this.triggerReady();
  19470. // Keep the same volume as before
  19471. if (this.cache_.volume) {
  19472. this.techCall_('setVolume', this.cache_.volume);
  19473. }
  19474. // Look if the tech found a higher resolution poster while loading
  19475. this.handleTechPosterChange_();
  19476. // Update the duration if available
  19477. this.handleTechDurationChange_();
  19478. }
  19479. /**
  19480. * Retrigger the `loadstart` event that was triggered by the {@link Tech}.
  19481. *
  19482. * @fires Player#loadstart
  19483. * @listens Tech#loadstart
  19484. * @private
  19485. */
  19486. handleTechLoadStart_() {
  19487. // TODO: Update to use `emptied` event instead. See #1277.
  19488. this.removeClass('vjs-ended', 'vjs-seeking');
  19489. // reset the error state
  19490. this.error(null);
  19491. // Update the duration
  19492. this.handleTechDurationChange_();
  19493. if (!this.paused()) {
  19494. /**
  19495. * Fired when the user agent begins looking for media data
  19496. *
  19497. * @event Player#loadstart
  19498. * @type {Event}
  19499. */
  19500. this.trigger('loadstart');
  19501. } else {
  19502. // reset the hasStarted state
  19503. this.hasStarted(false);
  19504. this.trigger('loadstart');
  19505. }
  19506. // autoplay happens after loadstart for the browser,
  19507. // so we mimic that behavior
  19508. this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? 'play' : this.autoplay());
  19509. }
  19510. /**
  19511. * Handle autoplay string values, rather than the typical boolean
  19512. * values that should be handled by the tech. Note that this is not
  19513. * part of any specification. Valid values and what they do can be
  19514. * found on the autoplay getter at Player#autoplay()
  19515. */
  19516. manualAutoplay_(type) {
  19517. if (!this.tech_ || typeof type !== 'string') {
  19518. return;
  19519. }
  19520. // Save original muted() value, set muted to true, and attempt to play().
  19521. // On promise rejection, restore muted from saved value
  19522. const resolveMuted = () => {
  19523. const previouslyMuted = this.muted();
  19524. this.muted(true);
  19525. const restoreMuted = () => {
  19526. this.muted(previouslyMuted);
  19527. };
  19528. // restore muted on play terminatation
  19529. this.playTerminatedQueue_.push(restoreMuted);
  19530. const mutedPromise = this.play();
  19531. if (!isPromise(mutedPromise)) {
  19532. return;
  19533. }
  19534. return mutedPromise.catch(err => {
  19535. restoreMuted();
  19536. throw new Error(`Rejection at manualAutoplay. Restoring muted value. ${err ? err : ''}`);
  19537. });
  19538. };
  19539. let promise;
  19540. // if muted defaults to true
  19541. // the only thing we can do is call play
  19542. if (type === 'any' && !this.muted()) {
  19543. promise = this.play();
  19544. if (isPromise(promise)) {
  19545. promise = promise.catch(resolveMuted);
  19546. }
  19547. } else if (type === 'muted' && !this.muted()) {
  19548. promise = resolveMuted();
  19549. } else {
  19550. promise = this.play();
  19551. }
  19552. if (!isPromise(promise)) {
  19553. return;
  19554. }
  19555. return promise.then(() => {
  19556. this.trigger({
  19557. type: 'autoplay-success',
  19558. autoplay: type
  19559. });
  19560. }).catch(() => {
  19561. this.trigger({
  19562. type: 'autoplay-failure',
  19563. autoplay: type
  19564. });
  19565. });
  19566. }
  19567. /**
  19568. * Update the internal source caches so that we return the correct source from
  19569. * `src()`, `currentSource()`, and `currentSources()`.
  19570. *
  19571. * > Note: `currentSources` will not be updated if the source that is passed in exists
  19572. * in the current `currentSources` cache.
  19573. *
  19574. *
  19575. * @param {Tech~SourceObject} srcObj
  19576. * A string or object source to update our caches to.
  19577. */
  19578. updateSourceCaches_(srcObj = '') {
  19579. let src = srcObj;
  19580. let type = '';
  19581. if (typeof src !== 'string') {
  19582. src = srcObj.src;
  19583. type = srcObj.type;
  19584. }
  19585. // make sure all the caches are set to default values
  19586. // to prevent null checking
  19587. this.cache_.source = this.cache_.source || {};
  19588. this.cache_.sources = this.cache_.sources || [];
  19589. // try to get the type of the src that was passed in
  19590. if (src && !type) {
  19591. type = findMimetype(this, src);
  19592. }
  19593. // update `currentSource` cache always
  19594. this.cache_.source = merge$1({}, srcObj, {
  19595. src,
  19596. type
  19597. });
  19598. const matchingSources = this.cache_.sources.filter(s => s.src && s.src === src);
  19599. const sourceElSources = [];
  19600. const sourceEls = this.$$('source');
  19601. const matchingSourceEls = [];
  19602. for (let i = 0; i < sourceEls.length; i++) {
  19603. const sourceObj = getAttributes(sourceEls[i]);
  19604. sourceElSources.push(sourceObj);
  19605. if (sourceObj.src && sourceObj.src === src) {
  19606. matchingSourceEls.push(sourceObj.src);
  19607. }
  19608. }
  19609. // if we have matching source els but not matching sources
  19610. // the current source cache is not up to date
  19611. if (matchingSourceEls.length && !matchingSources.length) {
  19612. this.cache_.sources = sourceElSources;
  19613. // if we don't have matching source or source els set the
  19614. // sources cache to the `currentSource` cache
  19615. } else if (!matchingSources.length) {
  19616. this.cache_.sources = [this.cache_.source];
  19617. }
  19618. // update the tech `src` cache
  19619. this.cache_.src = src;
  19620. }
  19621. /**
  19622. * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}
  19623. * causing the media element to reload.
  19624. *
  19625. * It will fire for the initial source and each subsequent source.
  19626. * This event is a custom event from Video.js and is triggered by the {@link Tech}.
  19627. *
  19628. * The event object for this event contains a `src` property that will contain the source
  19629. * that was available when the event was triggered. This is generally only necessary if Video.js
  19630. * is switching techs while the source was being changed.
  19631. *
  19632. * It is also fired when `load` is called on the player (or media element)
  19633. * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
  19634. * says that the resource selection algorithm needs to be aborted and restarted.
  19635. * In this case, it is very likely that the `src` property will be set to the
  19636. * empty string `""` to indicate we do not know what the source will be but
  19637. * that it is changing.
  19638. *
  19639. * *This event is currently still experimental and may change in minor releases.*
  19640. * __To use this, pass `enableSourceset` option to the player.__
  19641. *
  19642. * @event Player#sourceset
  19643. * @type {Event}
  19644. * @prop {string} src
  19645. * The source url available when the `sourceset` was triggered.
  19646. * It will be an empty string if we cannot know what the source is
  19647. * but know that the source will change.
  19648. */
  19649. /**
  19650. * Retrigger the `sourceset` event that was triggered by the {@link Tech}.
  19651. *
  19652. * @fires Player#sourceset
  19653. * @listens Tech#sourceset
  19654. * @private
  19655. */
  19656. handleTechSourceset_(event) {
  19657. // only update the source cache when the source
  19658. // was not updated using the player api
  19659. if (!this.changingSrc_) {
  19660. let updateSourceCaches = src => this.updateSourceCaches_(src);
  19661. const playerSrc = this.currentSource().src;
  19662. const eventSrc = event.src;
  19663. // if we have a playerSrc that is not a blob, and a tech src that is a blob
  19664. if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
  19665. // if both the tech source and the player source were updated we assume
  19666. // something like @videojs/http-streaming did the sourceset and skip updating the source cache.
  19667. if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
  19668. updateSourceCaches = () => {};
  19669. }
  19670. }
  19671. // update the source to the initial source right away
  19672. // in some cases this will be empty string
  19673. updateSourceCaches(eventSrc);
  19674. // if the `sourceset` `src` was an empty string
  19675. // wait for a `loadstart` to update the cache to `currentSrc`.
  19676. // If a sourceset happens before a `loadstart`, we reset the state
  19677. if (!event.src) {
  19678. this.tech_.any(['sourceset', 'loadstart'], e => {
  19679. // if a sourceset happens before a `loadstart` there
  19680. // is nothing to do as this `handleTechSourceset_`
  19681. // will be called again and this will be handled there.
  19682. if (e.type === 'sourceset') {
  19683. return;
  19684. }
  19685. const techSrc = this.techGet('currentSrc');
  19686. this.lastSource_.tech = techSrc;
  19687. this.updateSourceCaches_(techSrc);
  19688. });
  19689. }
  19690. }
  19691. this.lastSource_ = {
  19692. player: this.currentSource().src,
  19693. tech: event.src
  19694. };
  19695. this.trigger({
  19696. src: event.src,
  19697. type: 'sourceset'
  19698. });
  19699. }
  19700. /**
  19701. * Add/remove the vjs-has-started class
  19702. *
  19703. *
  19704. * @param {boolean} request
  19705. * - true: adds the class
  19706. * - false: remove the class
  19707. *
  19708. * @return {boolean}
  19709. * the boolean value of hasStarted_
  19710. */
  19711. hasStarted(request) {
  19712. if (request === undefined) {
  19713. // act as getter, if we have no request to change
  19714. return this.hasStarted_;
  19715. }
  19716. if (request === this.hasStarted_) {
  19717. return;
  19718. }
  19719. this.hasStarted_ = request;
  19720. if (this.hasStarted_) {
  19721. this.addClass('vjs-has-started');
  19722. } else {
  19723. this.removeClass('vjs-has-started');
  19724. }
  19725. }
  19726. /**
  19727. * Fired whenever the media begins or resumes playback
  19728. *
  19729. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
  19730. * @fires Player#play
  19731. * @listens Tech#play
  19732. * @private
  19733. */
  19734. handleTechPlay_() {
  19735. this.removeClass('vjs-ended', 'vjs-paused');
  19736. this.addClass('vjs-playing');
  19737. // hide the poster when the user hits play
  19738. this.hasStarted(true);
  19739. /**
  19740. * Triggered whenever an {@link Tech#play} event happens. Indicates that
  19741. * playback has started or resumed.
  19742. *
  19743. * @event Player#play
  19744. * @type {Event}
  19745. */
  19746. this.trigger('play');
  19747. }
  19748. /**
  19749. * Retrigger the `ratechange` event that was triggered by the {@link Tech}.
  19750. *
  19751. * If there were any events queued while the playback rate was zero, fire
  19752. * those events now.
  19753. *
  19754. * @private
  19755. * @method Player#handleTechRateChange_
  19756. * @fires Player#ratechange
  19757. * @listens Tech#ratechange
  19758. */
  19759. handleTechRateChange_() {
  19760. if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
  19761. this.queuedCallbacks_.forEach(queued => queued.callback(queued.event));
  19762. this.queuedCallbacks_ = [];
  19763. }
  19764. this.cache_.lastPlaybackRate = this.tech_.playbackRate();
  19765. /**
  19766. * Fires when the playing speed of the audio/video is changed
  19767. *
  19768. * @event Player#ratechange
  19769. * @type {event}
  19770. */
  19771. this.trigger('ratechange');
  19772. }
  19773. /**
  19774. * Retrigger the `waiting` event that was triggered by the {@link Tech}.
  19775. *
  19776. * @fires Player#waiting
  19777. * @listens Tech#waiting
  19778. * @private
  19779. */
  19780. handleTechWaiting_() {
  19781. this.addClass('vjs-waiting');
  19782. /**
  19783. * A readyState change on the DOM element has caused playback to stop.
  19784. *
  19785. * @event Player#waiting
  19786. * @type {Event}
  19787. */
  19788. this.trigger('waiting');
  19789. // Browsers may emit a timeupdate event after a waiting event. In order to prevent
  19790. // premature removal of the waiting class, wait for the time to change.
  19791. const timeWhenWaiting = this.currentTime();
  19792. const timeUpdateListener = () => {
  19793. if (timeWhenWaiting !== this.currentTime()) {
  19794. this.removeClass('vjs-waiting');
  19795. this.off('timeupdate', timeUpdateListener);
  19796. }
  19797. };
  19798. this.on('timeupdate', timeUpdateListener);
  19799. }
  19800. /**
  19801. * Retrigger the `canplay` event that was triggered by the {@link Tech}.
  19802. * > Note: This is not consistent between browsers. See #1351
  19803. *
  19804. * @fires Player#canplay
  19805. * @listens Tech#canplay
  19806. * @private
  19807. */
  19808. handleTechCanPlay_() {
  19809. this.removeClass('vjs-waiting');
  19810. /**
  19811. * The media has a readyState of HAVE_FUTURE_DATA or greater.
  19812. *
  19813. * @event Player#canplay
  19814. * @type {Event}
  19815. */
  19816. this.trigger('canplay');
  19817. }
  19818. /**
  19819. * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.
  19820. *
  19821. * @fires Player#canplaythrough
  19822. * @listens Tech#canplaythrough
  19823. * @private
  19824. */
  19825. handleTechCanPlayThrough_() {
  19826. this.removeClass('vjs-waiting');
  19827. /**
  19828. * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the
  19829. * entire media file can be played without buffering.
  19830. *
  19831. * @event Player#canplaythrough
  19832. * @type {Event}
  19833. */
  19834. this.trigger('canplaythrough');
  19835. }
  19836. /**
  19837. * Retrigger the `playing` event that was triggered by the {@link Tech}.
  19838. *
  19839. * @fires Player#playing
  19840. * @listens Tech#playing
  19841. * @private
  19842. */
  19843. handleTechPlaying_() {
  19844. this.removeClass('vjs-waiting');
  19845. /**
  19846. * The media is no longer blocked from playback, and has started playing.
  19847. *
  19848. * @event Player#playing
  19849. * @type {Event}
  19850. */
  19851. this.trigger('playing');
  19852. }
  19853. /**
  19854. * Retrigger the `seeking` event that was triggered by the {@link Tech}.
  19855. *
  19856. * @fires Player#seeking
  19857. * @listens Tech#seeking
  19858. * @private
  19859. */
  19860. handleTechSeeking_() {
  19861. this.addClass('vjs-seeking');
  19862. /**
  19863. * Fired whenever the player is jumping to a new time
  19864. *
  19865. * @event Player#seeking
  19866. * @type {Event}
  19867. */
  19868. this.trigger('seeking');
  19869. }
  19870. /**
  19871. * Retrigger the `seeked` event that was triggered by the {@link Tech}.
  19872. *
  19873. * @fires Player#seeked
  19874. * @listens Tech#seeked
  19875. * @private
  19876. */
  19877. handleTechSeeked_() {
  19878. this.removeClass('vjs-seeking', 'vjs-ended');
  19879. /**
  19880. * Fired when the player has finished jumping to a new time
  19881. *
  19882. * @event Player#seeked
  19883. * @type {Event}
  19884. */
  19885. this.trigger('seeked');
  19886. }
  19887. /**
  19888. * Retrigger the `pause` event that was triggered by the {@link Tech}.
  19889. *
  19890. * @fires Player#pause
  19891. * @listens Tech#pause
  19892. * @private
  19893. */
  19894. handleTechPause_() {
  19895. this.removeClass('vjs-playing');
  19896. this.addClass('vjs-paused');
  19897. /**
  19898. * Fired whenever the media has been paused
  19899. *
  19900. * @event Player#pause
  19901. * @type {Event}
  19902. */
  19903. this.trigger('pause');
  19904. }
  19905. /**
  19906. * Retrigger the `ended` event that was triggered by the {@link Tech}.
  19907. *
  19908. * @fires Player#ended
  19909. * @listens Tech#ended
  19910. * @private
  19911. */
  19912. handleTechEnded_() {
  19913. this.addClass('vjs-ended');
  19914. this.removeClass('vjs-waiting');
  19915. if (this.options_.loop) {
  19916. this.currentTime(0);
  19917. this.play();
  19918. } else if (!this.paused()) {
  19919. this.pause();
  19920. }
  19921. /**
  19922. * Fired when the end of the media resource is reached (currentTime == duration)
  19923. *
  19924. * @event Player#ended
  19925. * @type {Event}
  19926. */
  19927. this.trigger('ended');
  19928. }
  19929. /**
  19930. * Fired when the duration of the media resource is first known or changed
  19931. *
  19932. * @listens Tech#durationchange
  19933. * @private
  19934. */
  19935. handleTechDurationChange_() {
  19936. this.duration(this.techGet_('duration'));
  19937. }
  19938. /**
  19939. * Handle a click on the media element to play/pause
  19940. *
  19941. * @param {Event} event
  19942. * the event that caused this function to trigger
  19943. *
  19944. * @listens Tech#click
  19945. * @private
  19946. */
  19947. handleTechClick_(event) {
  19948. // When controls are disabled a click should not toggle playback because
  19949. // the click is considered a control
  19950. if (!this.controls_) {
  19951. return;
  19952. }
  19953. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.click === undefined || this.options_.userActions.click !== false) {
  19954. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.click === 'function') {
  19955. this.options_.userActions.click.call(this, event);
  19956. } else if (this.paused()) {
  19957. silencePromise(this.play());
  19958. } else {
  19959. this.pause();
  19960. }
  19961. }
  19962. }
  19963. /**
  19964. * Handle a double-click on the media element to enter/exit fullscreen
  19965. *
  19966. * @param {Event} event
  19967. * the event that caused this function to trigger
  19968. *
  19969. * @listens Tech#dblclick
  19970. * @private
  19971. */
  19972. handleTechDoubleClick_(event) {
  19973. if (!this.controls_) {
  19974. return;
  19975. }
  19976. // we do not want to toggle fullscreen state
  19977. // when double-clicking inside a control bar or a modal
  19978. const inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), el => el.contains(event.target));
  19979. if (!inAllowedEls) {
  19980. /*
  19981. * options.userActions.doubleClick
  19982. *
  19983. * If `undefined` or `true`, double-click toggles fullscreen if controls are present
  19984. * Set to `false` to disable double-click handling
  19985. * Set to a function to substitute an external double-click handler
  19986. */
  19987. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) {
  19988. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') {
  19989. this.options_.userActions.doubleClick.call(this, event);
  19990. } else if (this.isFullscreen()) {
  19991. this.exitFullscreen();
  19992. } else {
  19993. this.requestFullscreen();
  19994. }
  19995. }
  19996. }
  19997. }
  19998. /**
  19999. * Handle a tap on the media element. It will toggle the user
  20000. * activity state, which hides and shows the controls.
  20001. *
  20002. * @listens Tech#tap
  20003. * @private
  20004. */
  20005. handleTechTap_() {
  20006. this.userActive(!this.userActive());
  20007. }
  20008. /**
  20009. * Handle touch to start
  20010. *
  20011. * @listens Tech#touchstart
  20012. * @private
  20013. */
  20014. handleTechTouchStart_() {
  20015. this.userWasActive = this.userActive();
  20016. }
  20017. /**
  20018. * Handle touch to move
  20019. *
  20020. * @listens Tech#touchmove
  20021. * @private
  20022. */
  20023. handleTechTouchMove_() {
  20024. if (this.userWasActive) {
  20025. this.reportUserActivity();
  20026. }
  20027. }
  20028. /**
  20029. * Handle touch to end
  20030. *
  20031. * @param {Event} event
  20032. * the touchend event that triggered
  20033. * this function
  20034. *
  20035. * @listens Tech#touchend
  20036. * @private
  20037. */
  20038. handleTechTouchEnd_(event) {
  20039. // Stop the mouse events from also happening
  20040. if (event.cancelable) {
  20041. event.preventDefault();
  20042. }
  20043. }
  20044. /**
  20045. * @private
  20046. */
  20047. toggleFullscreenClass_() {
  20048. if (this.isFullscreen()) {
  20049. this.addClass('vjs-fullscreen');
  20050. } else {
  20051. this.removeClass('vjs-fullscreen');
  20052. }
  20053. }
  20054. /**
  20055. * when the document fschange event triggers it calls this
  20056. */
  20057. documentFullscreenChange_(e) {
  20058. const targetPlayer = e.target.player;
  20059. // if another player was fullscreen
  20060. // do a null check for targetPlayer because older firefox's would put document as e.target
  20061. if (targetPlayer && targetPlayer !== this) {
  20062. return;
  20063. }
  20064. const el = this.el();
  20065. let isFs = document[this.fsApi_.fullscreenElement] === el;
  20066. if (!isFs && el.matches) {
  20067. isFs = el.matches(':' + this.fsApi_.fullscreen);
  20068. } else if (!isFs && el.msMatchesSelector) {
  20069. isFs = el.msMatchesSelector(':' + this.fsApi_.fullscreen);
  20070. }
  20071. this.isFullscreen(isFs);
  20072. }
  20073. /**
  20074. * Handle Tech Fullscreen Change
  20075. *
  20076. * @param {Event} event
  20077. * the fullscreenchange event that triggered this function
  20078. *
  20079. * @param {Object} data
  20080. * the data that was sent with the event
  20081. *
  20082. * @private
  20083. * @listens Tech#fullscreenchange
  20084. * @fires Player#fullscreenchange
  20085. */
  20086. handleTechFullscreenChange_(event, data) {
  20087. if (data) {
  20088. if (data.nativeIOSFullscreen) {
  20089. this.addClass('vjs-ios-native-fs');
  20090. this.tech_.one('webkitendfullscreen', () => {
  20091. this.removeClass('vjs-ios-native-fs');
  20092. });
  20093. }
  20094. this.isFullscreen(data.isFullscreen);
  20095. }
  20096. }
  20097. handleTechFullscreenError_(event, err) {
  20098. this.trigger('fullscreenerror', err);
  20099. }
  20100. /**
  20101. * @private
  20102. */
  20103. togglePictureInPictureClass_() {
  20104. if (this.isInPictureInPicture()) {
  20105. this.addClass('vjs-picture-in-picture');
  20106. } else {
  20107. this.removeClass('vjs-picture-in-picture');
  20108. }
  20109. }
  20110. /**
  20111. * Handle Tech Enter Picture-in-Picture.
  20112. *
  20113. * @param {Event} event
  20114. * the enterpictureinpicture event that triggered this function
  20115. *
  20116. * @private
  20117. * @listens Tech#enterpictureinpicture
  20118. */
  20119. handleTechEnterPictureInPicture_(event) {
  20120. this.isInPictureInPicture(true);
  20121. }
  20122. /**
  20123. * Handle Tech Leave Picture-in-Picture.
  20124. *
  20125. * @param {Event} event
  20126. * the leavepictureinpicture event that triggered this function
  20127. *
  20128. * @private
  20129. * @listens Tech#leavepictureinpicture
  20130. */
  20131. handleTechLeavePictureInPicture_(event) {
  20132. this.isInPictureInPicture(false);
  20133. }
  20134. /**
  20135. * Fires when an error occurred during the loading of an audio/video.
  20136. *
  20137. * @private
  20138. * @listens Tech#error
  20139. */
  20140. handleTechError_() {
  20141. const error = this.tech_.error();
  20142. this.error(error);
  20143. }
  20144. /**
  20145. * Retrigger the `textdata` event that was triggered by the {@link Tech}.
  20146. *
  20147. * @fires Player#textdata
  20148. * @listens Tech#textdata
  20149. * @private
  20150. */
  20151. handleTechTextData_() {
  20152. let data = null;
  20153. if (arguments.length > 1) {
  20154. data = arguments[1];
  20155. }
  20156. /**
  20157. * Fires when we get a textdata event from tech
  20158. *
  20159. * @event Player#textdata
  20160. * @type {Event}
  20161. */
  20162. this.trigger('textdata', data);
  20163. }
  20164. /**
  20165. * Get object for cached values.
  20166. *
  20167. * @return {Object}
  20168. * get the current object cache
  20169. */
  20170. getCache() {
  20171. return this.cache_;
  20172. }
  20173. /**
  20174. * Resets the internal cache object.
  20175. *
  20176. * Using this function outside the player constructor or reset method may
  20177. * have unintended side-effects.
  20178. *
  20179. * @private
  20180. */
  20181. resetCache_() {
  20182. this.cache_ = {
  20183. // Right now, the currentTime is not _really_ cached because it is always
  20184. // retrieved from the tech (see: currentTime). However, for completeness,
  20185. // we set it to zero here to ensure that if we do start actually caching
  20186. // it, we reset it along with everything else.
  20187. currentTime: 0,
  20188. initTime: 0,
  20189. inactivityTimeout: this.options_.inactivityTimeout,
  20190. duration: NaN,
  20191. lastVolume: 1,
  20192. lastPlaybackRate: this.defaultPlaybackRate(),
  20193. media: null,
  20194. src: '',
  20195. source: {},
  20196. sources: [],
  20197. playbackRates: [],
  20198. volume: 1
  20199. };
  20200. }
  20201. /**
  20202. * Pass values to the playback tech
  20203. *
  20204. * @param {string} [method]
  20205. * the method to call
  20206. *
  20207. * @param {Object} arg
  20208. * the argument to pass
  20209. *
  20210. * @private
  20211. */
  20212. techCall_(method, arg) {
  20213. // If it's not ready yet, call method when it is
  20214. this.ready(function () {
  20215. if (method in allowedSetters) {
  20216. return set(this.middleware_, this.tech_, method, arg);
  20217. } else if (method in allowedMediators) {
  20218. return mediate(this.middleware_, this.tech_, method, arg);
  20219. }
  20220. try {
  20221. if (this.tech_) {
  20222. this.tech_[method](arg);
  20223. }
  20224. } catch (e) {
  20225. log$1(e);
  20226. throw e;
  20227. }
  20228. }, true);
  20229. }
  20230. /**
  20231. * Mediate attempt to call playback tech method
  20232. * and return the value of the method called.
  20233. *
  20234. * @param {string} method
  20235. * Tech method
  20236. *
  20237. * @return {*}
  20238. * Value returned by the tech method called, undefined if tech
  20239. * is not ready or tech method is not present
  20240. *
  20241. * @private
  20242. */
  20243. techGet_(method) {
  20244. if (!this.tech_ || !this.tech_.isReady_) {
  20245. return;
  20246. }
  20247. if (method in allowedGetters) {
  20248. return get(this.middleware_, this.tech_, method);
  20249. } else if (method in allowedMediators) {
  20250. return mediate(this.middleware_, this.tech_, method);
  20251. }
  20252. // Log error when playback tech object is present but method
  20253. // is undefined or unavailable
  20254. try {
  20255. return this.tech_[method]();
  20256. } catch (e) {
  20257. // When building additional tech libs, an expected method may not be defined yet
  20258. if (this.tech_[method] === undefined) {
  20259. log$1(`Video.js: ${method} method not defined for ${this.techName_} playback technology.`, e);
  20260. throw e;
  20261. }
  20262. // When a method isn't available on the object it throws a TypeError
  20263. if (e.name === 'TypeError') {
  20264. log$1(`Video.js: ${method} unavailable on ${this.techName_} playback technology element.`, e);
  20265. this.tech_.isReady_ = false;
  20266. throw e;
  20267. }
  20268. // If error unknown, just log and throw
  20269. log$1(e);
  20270. throw e;
  20271. }
  20272. }
  20273. /**
  20274. * Attempt to begin playback at the first opportunity.
  20275. *
  20276. * @return {Promise|undefined}
  20277. * Returns a promise if the browser supports Promises (or one
  20278. * was passed in as an option). This promise will be resolved on
  20279. * the return value of play. If this is undefined it will fulfill the
  20280. * promise chain otherwise the promise chain will be fulfilled when
  20281. * the promise from play is fulfilled.
  20282. */
  20283. play() {
  20284. return new Promise(resolve => {
  20285. this.play_(resolve);
  20286. });
  20287. }
  20288. /**
  20289. * The actual logic for play, takes a callback that will be resolved on the
  20290. * return value of play. This allows us to resolve to the play promise if there
  20291. * is one on modern browsers.
  20292. *
  20293. * @private
  20294. * @param {Function} [callback]
  20295. * The callback that should be called when the techs play is actually called
  20296. */
  20297. play_(callback = silencePromise) {
  20298. this.playCallbacks_.push(callback);
  20299. const isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));
  20300. const isSafariOrIOS = Boolean(IS_ANY_SAFARI || IS_IOS);
  20301. // treat calls to play_ somewhat like the `one` event function
  20302. if (this.waitToPlay_) {
  20303. this.off(['ready', 'loadstart'], this.waitToPlay_);
  20304. this.waitToPlay_ = null;
  20305. }
  20306. // if the player/tech is not ready or the src itself is not ready
  20307. // queue up a call to play on `ready` or `loadstart`
  20308. if (!this.isReady_ || !isSrcReady) {
  20309. this.waitToPlay_ = e => {
  20310. this.play_();
  20311. };
  20312. this.one(['ready', 'loadstart'], this.waitToPlay_);
  20313. // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod
  20314. // in that case, we need to prime the video element by calling load so it'll be ready in time
  20315. if (!isSrcReady && isSafariOrIOS) {
  20316. this.load();
  20317. }
  20318. return;
  20319. }
  20320. // If the player/tech is ready and we have a source, we can attempt playback.
  20321. const val = this.techGet_('play');
  20322. // For native playback, reset the progress bar if we get a play call from a replay.
  20323. const isNativeReplay = isSafariOrIOS && this.hasClass('vjs-ended');
  20324. if (isNativeReplay) {
  20325. this.resetProgressBar_();
  20326. }
  20327. // play was terminated if the returned value is null
  20328. if (val === null) {
  20329. this.runPlayTerminatedQueue_();
  20330. } else {
  20331. this.runPlayCallbacks_(val);
  20332. }
  20333. }
  20334. /**
  20335. * These functions will be run when if play is terminated. If play
  20336. * runPlayCallbacks_ is run these function will not be run. This allows us
  20337. * to differentiate between a terminated play and an actual call to play.
  20338. */
  20339. runPlayTerminatedQueue_() {
  20340. const queue = this.playTerminatedQueue_.slice(0);
  20341. this.playTerminatedQueue_ = [];
  20342. queue.forEach(function (q) {
  20343. q();
  20344. });
  20345. }
  20346. /**
  20347. * When a callback to play is delayed we have to run these
  20348. * callbacks when play is actually called on the tech. This function
  20349. * runs the callbacks that were delayed and accepts the return value
  20350. * from the tech.
  20351. *
  20352. * @param {undefined|Promise} val
  20353. * The return value from the tech.
  20354. */
  20355. runPlayCallbacks_(val) {
  20356. const callbacks = this.playCallbacks_.slice(0);
  20357. this.playCallbacks_ = [];
  20358. // clear play terminatedQueue since we finished a real play
  20359. this.playTerminatedQueue_ = [];
  20360. callbacks.forEach(function (cb) {
  20361. cb(val);
  20362. });
  20363. }
  20364. /**
  20365. * Pause the video playback
  20366. *
  20367. * @return {Player}
  20368. * A reference to the player object this function was called on
  20369. */
  20370. pause() {
  20371. this.techCall_('pause');
  20372. }
  20373. /**
  20374. * Check if the player is paused or has yet to play
  20375. *
  20376. * @return {boolean}
  20377. * - false: if the media is currently playing
  20378. * - true: if media is not currently playing
  20379. */
  20380. paused() {
  20381. // The initial state of paused should be true (in Safari it's actually false)
  20382. return this.techGet_('paused') === false ? false : true;
  20383. }
  20384. /**
  20385. * Get a TimeRange object representing the current ranges of time that the user
  20386. * has played.
  20387. *
  20388. * @return { import('./utils/time').TimeRange }
  20389. * A time range object that represents all the increments of time that have
  20390. * been played.
  20391. */
  20392. played() {
  20393. return this.techGet_('played') || createTimeRanges$1(0, 0);
  20394. }
  20395. /**
  20396. * Returns whether or not the user is "scrubbing". Scrubbing is
  20397. * when the user has clicked the progress bar handle and is
  20398. * dragging it along the progress bar.
  20399. *
  20400. * @param {boolean} [isScrubbing]
  20401. * whether the user is or is not scrubbing
  20402. *
  20403. * @return {boolean}
  20404. * The value of scrubbing when getting
  20405. */
  20406. scrubbing(isScrubbing) {
  20407. if (typeof isScrubbing === 'undefined') {
  20408. return this.scrubbing_;
  20409. }
  20410. this.scrubbing_ = !!isScrubbing;
  20411. this.techCall_('setScrubbing', this.scrubbing_);
  20412. if (isScrubbing) {
  20413. this.addClass('vjs-scrubbing');
  20414. } else {
  20415. this.removeClass('vjs-scrubbing');
  20416. }
  20417. }
  20418. /**
  20419. * Get or set the current time (in seconds)
  20420. *
  20421. * @param {number|string} [seconds]
  20422. * The time to seek to in seconds
  20423. *
  20424. * @return {number}
  20425. * - the current time in seconds when getting
  20426. */
  20427. currentTime(seconds) {
  20428. if (typeof seconds !== 'undefined') {
  20429. if (seconds < 0) {
  20430. seconds = 0;
  20431. }
  20432. if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {
  20433. this.cache_.initTime = seconds;
  20434. this.off('canplay', this.boundApplyInitTime_);
  20435. this.one('canplay', this.boundApplyInitTime_);
  20436. return;
  20437. }
  20438. this.techCall_('setCurrentTime', seconds);
  20439. this.cache_.initTime = 0;
  20440. return;
  20441. }
  20442. // cache last currentTime and return. default to 0 seconds
  20443. //
  20444. // Caching the currentTime is meant to prevent a massive amount of reads on the tech's
  20445. // currentTime when scrubbing, but may not provide much performance benefit after all.
  20446. // Should be tested. Also something has to read the actual current time or the cache will
  20447. // never get updated.
  20448. this.cache_.currentTime = this.techGet_('currentTime') || 0;
  20449. return this.cache_.currentTime;
  20450. }
  20451. /**
  20452. * Apply the value of initTime stored in cache as currentTime.
  20453. *
  20454. * @private
  20455. */
  20456. applyInitTime_() {
  20457. this.currentTime(this.cache_.initTime);
  20458. }
  20459. /**
  20460. * Normally gets the length in time of the video in seconds;
  20461. * in all but the rarest use cases an argument will NOT be passed to the method
  20462. *
  20463. * > **NOTE**: The video must have started loading before the duration can be
  20464. * known, and depending on preload behaviour may not be known until the video starts
  20465. * playing.
  20466. *
  20467. * @fires Player#durationchange
  20468. *
  20469. * @param {number} [seconds]
  20470. * The duration of the video to set in seconds
  20471. *
  20472. * @return {number}
  20473. * - The duration of the video in seconds when getting
  20474. */
  20475. duration(seconds) {
  20476. if (seconds === undefined) {
  20477. // return NaN if the duration is not known
  20478. return this.cache_.duration !== undefined ? this.cache_.duration : NaN;
  20479. }
  20480. seconds = parseFloat(seconds);
  20481. // Standardize on Infinity for signaling video is live
  20482. if (seconds < 0) {
  20483. seconds = Infinity;
  20484. }
  20485. if (seconds !== this.cache_.duration) {
  20486. // Cache the last set value for optimized scrubbing
  20487. this.cache_.duration = seconds;
  20488. if (seconds === Infinity) {
  20489. this.addClass('vjs-live');
  20490. } else {
  20491. this.removeClass('vjs-live');
  20492. }
  20493. if (!isNaN(seconds)) {
  20494. // Do not fire durationchange unless the duration value is known.
  20495. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  20496. /**
  20497. * @event Player#durationchange
  20498. * @type {Event}
  20499. */
  20500. this.trigger('durationchange');
  20501. }
  20502. }
  20503. }
  20504. /**
  20505. * Calculates how much time is left in the video. Not part
  20506. * of the native video API.
  20507. *
  20508. * @return {number}
  20509. * The time remaining in seconds
  20510. */
  20511. remainingTime() {
  20512. return this.duration() - this.currentTime();
  20513. }
  20514. /**
  20515. * A remaining time function that is intended to be used when
  20516. * the time is to be displayed directly to the user.
  20517. *
  20518. * @return {number}
  20519. * The rounded time remaining in seconds
  20520. */
  20521. remainingTimeDisplay() {
  20522. return Math.floor(this.duration()) - Math.floor(this.currentTime());
  20523. }
  20524. //
  20525. // Kind of like an array of portions of the video that have been downloaded.
  20526. /**
  20527. * Get a TimeRange object with an array of the times of the video
  20528. * that have been downloaded. If you just want the percent of the
  20529. * video that's been downloaded, use bufferedPercent.
  20530. *
  20531. * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
  20532. *
  20533. * @return { import('./utils/time').TimeRange }
  20534. * A mock {@link TimeRanges} object (following HTML spec)
  20535. */
  20536. buffered() {
  20537. let buffered = this.techGet_('buffered');
  20538. if (!buffered || !buffered.length) {
  20539. buffered = createTimeRanges$1(0, 0);
  20540. }
  20541. return buffered;
  20542. }
  20543. /**
  20544. * Get the percent (as a decimal) of the video that's been downloaded.
  20545. * This method is not a part of the native HTML video API.
  20546. *
  20547. * @return {number}
  20548. * A decimal between 0 and 1 representing the percent
  20549. * that is buffered 0 being 0% and 1 being 100%
  20550. */
  20551. bufferedPercent() {
  20552. return bufferedPercent(this.buffered(), this.duration());
  20553. }
  20554. /**
  20555. * Get the ending time of the last buffered time range
  20556. * This is used in the progress bar to encapsulate all time ranges.
  20557. *
  20558. * @return {number}
  20559. * The end of the last buffered time range
  20560. */
  20561. bufferedEnd() {
  20562. const buffered = this.buffered();
  20563. const duration = this.duration();
  20564. let end = buffered.end(buffered.length - 1);
  20565. if (end > duration) {
  20566. end = duration;
  20567. }
  20568. return end;
  20569. }
  20570. /**
  20571. * Get or set the current volume of the media
  20572. *
  20573. * @param {number} [percentAsDecimal]
  20574. * The new volume as a decimal percent:
  20575. * - 0 is muted/0%/off
  20576. * - 1.0 is 100%/full
  20577. * - 0.5 is half volume or 50%
  20578. *
  20579. * @return {number}
  20580. * The current volume as a percent when getting
  20581. */
  20582. volume(percentAsDecimal) {
  20583. let vol;
  20584. if (percentAsDecimal !== undefined) {
  20585. // Force value to between 0 and 1
  20586. vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal)));
  20587. this.cache_.volume = vol;
  20588. this.techCall_('setVolume', vol);
  20589. if (vol > 0) {
  20590. this.lastVolume_(vol);
  20591. }
  20592. return;
  20593. }
  20594. // Default to 1 when returning current volume.
  20595. vol = parseFloat(this.techGet_('volume'));
  20596. return isNaN(vol) ? 1 : vol;
  20597. }
  20598. /**
  20599. * Get the current muted state, or turn mute on or off
  20600. *
  20601. * @param {boolean} [muted]
  20602. * - true to mute
  20603. * - false to unmute
  20604. *
  20605. * @return {boolean}
  20606. * - true if mute is on and getting
  20607. * - false if mute is off and getting
  20608. */
  20609. muted(muted) {
  20610. if (muted !== undefined) {
  20611. this.techCall_('setMuted', muted);
  20612. return;
  20613. }
  20614. return this.techGet_('muted') || false;
  20615. }
  20616. /**
  20617. * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted
  20618. * indicates the state of muted on initial playback.
  20619. *
  20620. * ```js
  20621. * var myPlayer = videojs('some-player-id');
  20622. *
  20623. * myPlayer.src("http://www.example.com/path/to/video.mp4");
  20624. *
  20625. * // get, should be false
  20626. * console.log(myPlayer.defaultMuted());
  20627. * // set to true
  20628. * myPlayer.defaultMuted(true);
  20629. * // get should be true
  20630. * console.log(myPlayer.defaultMuted());
  20631. * ```
  20632. *
  20633. * @param {boolean} [defaultMuted]
  20634. * - true to mute
  20635. * - false to unmute
  20636. *
  20637. * @return {boolean|Player}
  20638. * - true if defaultMuted is on and getting
  20639. * - false if defaultMuted is off and getting
  20640. * - A reference to the current player when setting
  20641. */
  20642. defaultMuted(defaultMuted) {
  20643. if (defaultMuted !== undefined) {
  20644. return this.techCall_('setDefaultMuted', defaultMuted);
  20645. }
  20646. return this.techGet_('defaultMuted') || false;
  20647. }
  20648. /**
  20649. * Get the last volume, or set it
  20650. *
  20651. * @param {number} [percentAsDecimal]
  20652. * The new last volume as a decimal percent:
  20653. * - 0 is muted/0%/off
  20654. * - 1.0 is 100%/full
  20655. * - 0.5 is half volume or 50%
  20656. *
  20657. * @return {number}
  20658. * the current value of lastVolume as a percent when getting
  20659. *
  20660. * @private
  20661. */
  20662. lastVolume_(percentAsDecimal) {
  20663. if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {
  20664. this.cache_.lastVolume = percentAsDecimal;
  20665. return;
  20666. }
  20667. return this.cache_.lastVolume;
  20668. }
  20669. /**
  20670. * Check if current tech can support native fullscreen
  20671. * (e.g. with built in controls like iOS)
  20672. *
  20673. * @return {boolean}
  20674. * if native fullscreen is supported
  20675. */
  20676. supportsFullScreen() {
  20677. return this.techGet_('supportsFullScreen') || false;
  20678. }
  20679. /**
  20680. * Check if the player is in fullscreen mode or tell the player that it
  20681. * is or is not in fullscreen mode.
  20682. *
  20683. * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
  20684. * property and instead document.fullscreenElement is used. But isFullscreen is
  20685. * still a valuable property for internal player workings.
  20686. *
  20687. * @param {boolean} [isFS]
  20688. * Set the players current fullscreen state
  20689. *
  20690. * @return {boolean}
  20691. * - true if fullscreen is on and getting
  20692. * - false if fullscreen is off and getting
  20693. */
  20694. isFullscreen(isFS) {
  20695. if (isFS !== undefined) {
  20696. const oldValue = this.isFullscreen_;
  20697. this.isFullscreen_ = Boolean(isFS);
  20698. // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange
  20699. // this is the only place where we trigger fullscreenchange events for older browsers
  20700. // fullWindow mode is treated as a prefixed event and will get a fullscreenchange event as well
  20701. if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {
  20702. /**
  20703. * @event Player#fullscreenchange
  20704. * @type {Event}
  20705. */
  20706. this.trigger('fullscreenchange');
  20707. }
  20708. this.toggleFullscreenClass_();
  20709. return;
  20710. }
  20711. return this.isFullscreen_;
  20712. }
  20713. /**
  20714. * Increase the size of the video to full screen
  20715. * In some browsers, full screen is not supported natively, so it enters
  20716. * "full window mode", where the video fills the browser window.
  20717. * In browsers and devices that support native full screen, sometimes the
  20718. * browser's default controls will be shown, and not the Video.js custom skin.
  20719. * This includes most mobile devices (iOS, Android) and older versions of
  20720. * Safari.
  20721. *
  20722. * @param {Object} [fullscreenOptions]
  20723. * Override the player fullscreen options
  20724. *
  20725. * @fires Player#fullscreenchange
  20726. */
  20727. requestFullscreen(fullscreenOptions) {
  20728. if (this.isInPictureInPicture()) {
  20729. this.exitPictureInPicture();
  20730. }
  20731. const self = this;
  20732. return new Promise((resolve, reject) => {
  20733. function offHandler() {
  20734. self.off('fullscreenerror', errorHandler);
  20735. self.off('fullscreenchange', changeHandler);
  20736. }
  20737. function changeHandler() {
  20738. offHandler();
  20739. resolve();
  20740. }
  20741. function errorHandler(e, err) {
  20742. offHandler();
  20743. reject(err);
  20744. }
  20745. self.one('fullscreenchange', changeHandler);
  20746. self.one('fullscreenerror', errorHandler);
  20747. const promise = self.requestFullscreenHelper_(fullscreenOptions);
  20748. if (promise) {
  20749. promise.then(offHandler, offHandler);
  20750. promise.then(resolve, reject);
  20751. }
  20752. });
  20753. }
  20754. requestFullscreenHelper_(fullscreenOptions) {
  20755. let fsOptions;
  20756. // Only pass fullscreen options to requestFullscreen in spec-compliant browsers.
  20757. // Use defaults or player configured option unless passed directly to this method.
  20758. if (!this.fsApi_.prefixed) {
  20759. fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
  20760. if (fullscreenOptions !== undefined) {
  20761. fsOptions = fullscreenOptions;
  20762. }
  20763. }
  20764. // This method works as follows:
  20765. // 1. if a fullscreen api is available, use it
  20766. // 1. call requestFullscreen with potential options
  20767. // 2. if we got a promise from above, use it to update isFullscreen()
  20768. // 2. otherwise, if the tech supports fullscreen, call `enterFullScreen` on it.
  20769. // This is particularly used for iPhone, older iPads, and non-safari browser on iOS.
  20770. // 3. otherwise, use "fullWindow" mode
  20771. if (this.fsApi_.requestFullscreen) {
  20772. const promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);
  20773. // Even on browsers with promise support this may not return a promise
  20774. if (promise) {
  20775. promise.then(() => this.isFullscreen(true), () => this.isFullscreen(false));
  20776. }
  20777. return promise;
  20778. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  20779. // we can't take the video.js controls fullscreen but we can go fullscreen
  20780. // with native controls
  20781. this.techCall_('enterFullScreen');
  20782. } else {
  20783. // fullscreen isn't supported so we'll just stretch the video element to
  20784. // fill the viewport
  20785. this.enterFullWindow();
  20786. }
  20787. }
  20788. /**
  20789. * Return the video to its normal size after having been in full screen mode
  20790. *
  20791. * @fires Player#fullscreenchange
  20792. */
  20793. exitFullscreen() {
  20794. const self = this;
  20795. return new Promise((resolve, reject) => {
  20796. function offHandler() {
  20797. self.off('fullscreenerror', errorHandler);
  20798. self.off('fullscreenchange', changeHandler);
  20799. }
  20800. function changeHandler() {
  20801. offHandler();
  20802. resolve();
  20803. }
  20804. function errorHandler(e, err) {
  20805. offHandler();
  20806. reject(err);
  20807. }
  20808. self.one('fullscreenchange', changeHandler);
  20809. self.one('fullscreenerror', errorHandler);
  20810. const promise = self.exitFullscreenHelper_();
  20811. if (promise) {
  20812. promise.then(offHandler, offHandler);
  20813. // map the promise to our resolve/reject methods
  20814. promise.then(resolve, reject);
  20815. }
  20816. });
  20817. }
  20818. exitFullscreenHelper_() {
  20819. if (this.fsApi_.requestFullscreen) {
  20820. const promise = document[this.fsApi_.exitFullscreen]();
  20821. // Even on browsers with promise support this may not return a promise
  20822. if (promise) {
  20823. // we're splitting the promise here, so, we want to catch the
  20824. // potential error so that this chain doesn't have unhandled errors
  20825. silencePromise(promise.then(() => this.isFullscreen(false)));
  20826. }
  20827. return promise;
  20828. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  20829. this.techCall_('exitFullScreen');
  20830. } else {
  20831. this.exitFullWindow();
  20832. }
  20833. }
  20834. /**
  20835. * When fullscreen isn't supported we can stretch the
  20836. * video container to as wide as the browser will let us.
  20837. *
  20838. * @fires Player#enterFullWindow
  20839. */
  20840. enterFullWindow() {
  20841. this.isFullscreen(true);
  20842. this.isFullWindow = true;
  20843. // Storing original doc overflow value to return to when fullscreen is off
  20844. this.docOrigOverflow = document.documentElement.style.overflow;
  20845. // Add listener for esc key to exit fullscreen
  20846. on(document, 'keydown', this.boundFullWindowOnEscKey_);
  20847. // Hide any scroll bars
  20848. document.documentElement.style.overflow = 'hidden';
  20849. // Apply fullscreen styles
  20850. addClass(document.body, 'vjs-full-window');
  20851. /**
  20852. * @event Player#enterFullWindow
  20853. * @type {Event}
  20854. */
  20855. this.trigger('enterFullWindow');
  20856. }
  20857. /**
  20858. * Check for call to either exit full window or
  20859. * full screen on ESC key
  20860. *
  20861. * @param {string} event
  20862. * Event to check for key press
  20863. */
  20864. fullWindowOnEscKey(event) {
  20865. if (keycode.isEventKey(event, 'Esc')) {
  20866. if (this.isFullscreen() === true) {
  20867. if (!this.isFullWindow) {
  20868. this.exitFullscreen();
  20869. } else {
  20870. this.exitFullWindow();
  20871. }
  20872. }
  20873. }
  20874. }
  20875. /**
  20876. * Exit full window
  20877. *
  20878. * @fires Player#exitFullWindow
  20879. */
  20880. exitFullWindow() {
  20881. this.isFullscreen(false);
  20882. this.isFullWindow = false;
  20883. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  20884. // Unhide scroll bars.
  20885. document.documentElement.style.overflow = this.docOrigOverflow;
  20886. // Remove fullscreen styles
  20887. removeClass(document.body, 'vjs-full-window');
  20888. // Resize the box, controller, and poster to original sizes
  20889. // this.positionAll();
  20890. /**
  20891. * @event Player#exitFullWindow
  20892. * @type {Event}
  20893. */
  20894. this.trigger('exitFullWindow');
  20895. }
  20896. /**
  20897. * Disable Picture-in-Picture mode.
  20898. *
  20899. * @param {boolean} value
  20900. * - true will disable Picture-in-Picture mode
  20901. * - false will enable Picture-in-Picture mode
  20902. */
  20903. disablePictureInPicture(value) {
  20904. if (value === undefined) {
  20905. return this.techGet_('disablePictureInPicture');
  20906. }
  20907. this.techCall_('setDisablePictureInPicture', value);
  20908. this.options_.disablePictureInPicture = value;
  20909. this.trigger('disablepictureinpicturechanged');
  20910. }
  20911. /**
  20912. * Check if the player is in Picture-in-Picture mode or tell the player that it
  20913. * is or is not in Picture-in-Picture mode.
  20914. *
  20915. * @param {boolean} [isPiP]
  20916. * Set the players current Picture-in-Picture state
  20917. *
  20918. * @return {boolean}
  20919. * - true if Picture-in-Picture is on and getting
  20920. * - false if Picture-in-Picture is off and getting
  20921. */
  20922. isInPictureInPicture(isPiP) {
  20923. if (isPiP !== undefined) {
  20924. this.isInPictureInPicture_ = !!isPiP;
  20925. this.togglePictureInPictureClass_();
  20926. return;
  20927. }
  20928. return !!this.isInPictureInPicture_;
  20929. }
  20930. /**
  20931. * Create a floating video window always on top of other windows so that users may
  20932. * continue consuming media while they interact with other content sites, or
  20933. * applications on their device.
  20934. *
  20935. * This can use document picture-in-picture or element picture in picture
  20936. *
  20937. * Set `enableDocumentPictureInPicture` to `true` to use docPiP on a supported browser
  20938. * Else set `disablePictureInPicture` to `false` to disable elPiP on a supported browser
  20939. *
  20940. *
  20941. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/}
  20942. * @see [Spec]{@link https://wicg.github.io/document-picture-in-picture/}
  20943. *
  20944. * @fires Player#enterpictureinpicture
  20945. *
  20946. * @return {Promise}
  20947. * A promise with a Picture-in-Picture window.
  20948. */
  20949. requestPictureInPicture() {
  20950. if (this.options_.enableDocumentPictureInPicture && window$1.documentPictureInPicture) {
  20951. const pipContainer = document.createElement(this.el().tagName);
  20952. pipContainer.classList = this.el().classList;
  20953. pipContainer.classList.add('vjs-pip-container');
  20954. if (this.posterImage) {
  20955. pipContainer.appendChild(this.posterImage.el().cloneNode(true));
  20956. }
  20957. if (this.titleBar) {
  20958. pipContainer.appendChild(this.titleBar.el().cloneNode(true));
  20959. }
  20960. pipContainer.appendChild(createEl('p', {
  20961. className: 'vjs-pip-text'
  20962. }, {}, this.localize('Playing in picture-in-picture')));
  20963. return window$1.documentPictureInPicture.requestWindow({
  20964. // The aspect ratio won't be correct, Chrome bug https://crbug.com/1407629
  20965. initialAspectRatio: this.videoWidth() / this.videoHeight(),
  20966. copyStyleSheets: true
  20967. }).then(pipWindow => {
  20968. this.el_.parentNode.insertBefore(pipContainer, this.el_);
  20969. pipWindow.document.body.append(this.el_);
  20970. pipWindow.document.body.classList.add('vjs-pip-window');
  20971. this.player_.isInPictureInPicture(true);
  20972. this.player_.trigger('enterpictureinpicture');
  20973. // Listen for the PiP closing event to move the video back.
  20974. pipWindow.addEventListener('unload', event => {
  20975. const pipVideo = event.target.querySelector('.video-js');
  20976. pipContainer.replaceWith(pipVideo);
  20977. this.player_.isInPictureInPicture(false);
  20978. this.player_.trigger('leavepictureinpicture');
  20979. });
  20980. return pipWindow;
  20981. });
  20982. }
  20983. if ('pictureInPictureEnabled' in document && this.disablePictureInPicture() === false) {
  20984. /**
  20985. * This event fires when the player enters picture in picture mode
  20986. *
  20987. * @event Player#enterpictureinpicture
  20988. * @type {Event}
  20989. */
  20990. return this.techGet_('requestPictureInPicture');
  20991. }
  20992. return Promise.reject('No PiP mode is available');
  20993. }
  20994. /**
  20995. * Exit Picture-in-Picture mode.
  20996. *
  20997. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  20998. *
  20999. * @fires Player#leavepictureinpicture
  21000. *
  21001. * @return {Promise}
  21002. * A promise.
  21003. */
  21004. exitPictureInPicture() {
  21005. if (window$1.documentPictureInPicture && window$1.documentPictureInPicture.window) {
  21006. // With documentPictureInPicture, Player#leavepictureinpicture is fired in the unload handler
  21007. window$1.documentPictureInPicture.window.close();
  21008. return Promise.resolve();
  21009. }
  21010. if ('pictureInPictureEnabled' in document) {
  21011. /**
  21012. * This event fires when the player leaves picture in picture mode
  21013. *
  21014. * @event Player#leavepictureinpicture
  21015. * @type {Event}
  21016. */
  21017. return document.exitPictureInPicture();
  21018. }
  21019. }
  21020. /**
  21021. * Called when this Player has focus and a key gets pressed down, or when
  21022. * any Component of this player receives a key press that it doesn't handle.
  21023. * This allows player-wide hotkeys (either as defined below, or optionally
  21024. * by an external function).
  21025. *
  21026. * @param {Event} event
  21027. * The `keydown` event that caused this function to be called.
  21028. *
  21029. * @listens keydown
  21030. */
  21031. handleKeyDown(event) {
  21032. const {
  21033. userActions
  21034. } = this.options_;
  21035. // Bail out if hotkeys are not configured.
  21036. if (!userActions || !userActions.hotkeys) {
  21037. return;
  21038. }
  21039. // Function that determines whether or not to exclude an element from
  21040. // hotkeys handling.
  21041. const excludeElement = el => {
  21042. const tagName = el.tagName.toLowerCase();
  21043. // The first and easiest test is for `contenteditable` elements.
  21044. if (el.isContentEditable) {
  21045. return true;
  21046. }
  21047. // Inputs matching these types will still trigger hotkey handling as
  21048. // they are not text inputs.
  21049. const allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];
  21050. if (tagName === 'input') {
  21051. return allowedInputTypes.indexOf(el.type) === -1;
  21052. }
  21053. // The final test is by tag name. These tags will be excluded entirely.
  21054. const excludedTags = ['textarea'];
  21055. return excludedTags.indexOf(tagName) !== -1;
  21056. };
  21057. // Bail out if the user is focused on an interactive form element.
  21058. if (excludeElement(this.el_.ownerDocument.activeElement)) {
  21059. return;
  21060. }
  21061. if (typeof userActions.hotkeys === 'function') {
  21062. userActions.hotkeys.call(this, event);
  21063. } else {
  21064. this.handleHotkeys(event);
  21065. }
  21066. }
  21067. /**
  21068. * Called when this Player receives a hotkey keydown event.
  21069. * Supported player-wide hotkeys are:
  21070. *
  21071. * f - toggle fullscreen
  21072. * m - toggle mute
  21073. * k or Space - toggle play/pause
  21074. *
  21075. * @param {Event} event
  21076. * The `keydown` event that caused this function to be called.
  21077. */
  21078. handleHotkeys(event) {
  21079. const hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {};
  21080. // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set
  21081. const {
  21082. fullscreenKey = keydownEvent => keycode.isEventKey(keydownEvent, 'f'),
  21083. muteKey = keydownEvent => keycode.isEventKey(keydownEvent, 'm'),
  21084. playPauseKey = keydownEvent => keycode.isEventKey(keydownEvent, 'k') || keycode.isEventKey(keydownEvent, 'Space')
  21085. } = hotkeys;
  21086. if (fullscreenKey.call(this, event)) {
  21087. event.preventDefault();
  21088. event.stopPropagation();
  21089. const FSToggle = Component$1.getComponent('FullscreenToggle');
  21090. if (document[this.fsApi_.fullscreenEnabled] !== false) {
  21091. FSToggle.prototype.handleClick.call(this, event);
  21092. }
  21093. } else if (muteKey.call(this, event)) {
  21094. event.preventDefault();
  21095. event.stopPropagation();
  21096. const MuteToggle = Component$1.getComponent('MuteToggle');
  21097. MuteToggle.prototype.handleClick.call(this, event);
  21098. } else if (playPauseKey.call(this, event)) {
  21099. event.preventDefault();
  21100. event.stopPropagation();
  21101. const PlayToggle = Component$1.getComponent('PlayToggle');
  21102. PlayToggle.prototype.handleClick.call(this, event);
  21103. }
  21104. }
  21105. /**
  21106. * Check whether the player can play a given mimetype
  21107. *
  21108. * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype
  21109. *
  21110. * @param {string} type
  21111. * The mimetype to check
  21112. *
  21113. * @return {string}
  21114. * 'probably', 'maybe', or '' (empty string)
  21115. */
  21116. canPlayType(type) {
  21117. let can;
  21118. // Loop through each playback technology in the options order
  21119. for (let i = 0, j = this.options_.techOrder; i < j.length; i++) {
  21120. const techName = j[i];
  21121. let tech = Tech.getTech(techName);
  21122. // Support old behavior of techs being registered as components.
  21123. // Remove once that deprecated behavior is removed.
  21124. if (!tech) {
  21125. tech = Component$1.getComponent(techName);
  21126. }
  21127. // Check if the current tech is defined before continuing
  21128. if (!tech) {
  21129. log$1.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  21130. continue;
  21131. }
  21132. // Check if the browser supports this technology
  21133. if (tech.isSupported()) {
  21134. can = tech.canPlayType(type);
  21135. if (can) {
  21136. return can;
  21137. }
  21138. }
  21139. }
  21140. return '';
  21141. }
  21142. /**
  21143. * Select source based on tech-order or source-order
  21144. * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
  21145. * defaults to tech-order selection
  21146. *
  21147. * @param {Array} sources
  21148. * The sources for a media asset
  21149. *
  21150. * @return {Object|boolean}
  21151. * Object of source and tech order or false
  21152. */
  21153. selectSource(sources) {
  21154. // Get only the techs specified in `techOrder` that exist and are supported by the
  21155. // current platform
  21156. const techs = this.options_.techOrder.map(techName => {
  21157. return [techName, Tech.getTech(techName)];
  21158. }).filter(([techName, tech]) => {
  21159. // Check if the current tech is defined before continuing
  21160. if (tech) {
  21161. // Check if the browser supports this technology
  21162. return tech.isSupported();
  21163. }
  21164. log$1.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  21165. return false;
  21166. });
  21167. // Iterate over each `innerArray` element once per `outerArray` element and execute
  21168. // `tester` with both. If `tester` returns a non-falsy value, exit early and return
  21169. // that value.
  21170. const findFirstPassingTechSourcePair = function (outerArray, innerArray, tester) {
  21171. let found;
  21172. outerArray.some(outerChoice => {
  21173. return innerArray.some(innerChoice => {
  21174. found = tester(outerChoice, innerChoice);
  21175. if (found) {
  21176. return true;
  21177. }
  21178. });
  21179. });
  21180. return found;
  21181. };
  21182. let foundSourceAndTech;
  21183. const flip = fn => (a, b) => fn(b, a);
  21184. const finder = ([techName, tech], source) => {
  21185. if (tech.canPlaySource(source, this.options_[techName.toLowerCase()])) {
  21186. return {
  21187. source,
  21188. tech: techName
  21189. };
  21190. }
  21191. };
  21192. // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
  21193. // to select from them based on their priority.
  21194. if (this.options_.sourceOrder) {
  21195. // Source-first ordering
  21196. foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
  21197. } else {
  21198. // Tech-first ordering
  21199. foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
  21200. }
  21201. return foundSourceAndTech || false;
  21202. }
  21203. /**
  21204. * Executes source setting and getting logic
  21205. *
  21206. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  21207. * A SourceObject, an array of SourceObjects, or a string referencing
  21208. * a URL to a media source. It is _highly recommended_ that an object
  21209. * or array of objects is used here, so that source selection
  21210. * algorithms can take the `type` into account.
  21211. *
  21212. * If not provided, this method acts as a getter.
  21213. * @param {boolean} isRetry
  21214. * Indicates whether this is being called internally as a result of a retry
  21215. *
  21216. * @return {string|undefined}
  21217. * If the `source` argument is missing, returns the current source
  21218. * URL. Otherwise, returns nothing/undefined.
  21219. */
  21220. handleSrc_(source, isRetry) {
  21221. // getter usage
  21222. if (typeof source === 'undefined') {
  21223. return this.cache_.src || '';
  21224. }
  21225. // Reset retry behavior for new source
  21226. if (this.resetRetryOnError_) {
  21227. this.resetRetryOnError_();
  21228. }
  21229. // filter out invalid sources and turn our source into
  21230. // an array of source objects
  21231. const sources = filterSource(source);
  21232. // if a source was passed in then it is invalid because
  21233. // it was filtered to a zero length Array. So we have to
  21234. // show an error
  21235. if (!sources.length) {
  21236. this.setTimeout(function () {
  21237. this.error({
  21238. code: 4,
  21239. message: this.options_.notSupportedMessage
  21240. });
  21241. }, 0);
  21242. return;
  21243. }
  21244. // initial sources
  21245. this.changingSrc_ = true;
  21246. // Only update the cached source list if we are not retrying a new source after error,
  21247. // since in that case we want to include the failed source(s) in the cache
  21248. if (!isRetry) {
  21249. this.cache_.sources = sources;
  21250. }
  21251. this.updateSourceCaches_(sources[0]);
  21252. // middlewareSource is the source after it has been changed by middleware
  21253. setSource(this, sources[0], (middlewareSource, mws) => {
  21254. this.middleware_ = mws;
  21255. // since sourceSet is async we have to update the cache again after we select a source since
  21256. // the source that is selected could be out of order from the cache update above this callback.
  21257. if (!isRetry) {
  21258. this.cache_.sources = sources;
  21259. }
  21260. this.updateSourceCaches_(middlewareSource);
  21261. const err = this.src_(middlewareSource);
  21262. if (err) {
  21263. if (sources.length > 1) {
  21264. return this.handleSrc_(sources.slice(1));
  21265. }
  21266. this.changingSrc_ = false;
  21267. // We need to wrap this in a timeout to give folks a chance to add error event handlers
  21268. this.setTimeout(function () {
  21269. this.error({
  21270. code: 4,
  21271. message: this.options_.notSupportedMessage
  21272. });
  21273. }, 0);
  21274. // we could not find an appropriate tech, but let's still notify the delegate that this is it
  21275. // this needs a better comment about why this is needed
  21276. this.triggerReady();
  21277. return;
  21278. }
  21279. setTech(mws, this.tech_);
  21280. });
  21281. // Try another available source if this one fails before playback.
  21282. if (sources.length > 1) {
  21283. const retry = () => {
  21284. // Remove the error modal
  21285. this.error(null);
  21286. this.handleSrc_(sources.slice(1), true);
  21287. };
  21288. const stopListeningForErrors = () => {
  21289. this.off('error', retry);
  21290. };
  21291. this.one('error', retry);
  21292. this.one('playing', stopListeningForErrors);
  21293. this.resetRetryOnError_ = () => {
  21294. this.off('error', retry);
  21295. this.off('playing', stopListeningForErrors);
  21296. };
  21297. }
  21298. }
  21299. /**
  21300. * Get or set the video source.
  21301. *
  21302. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  21303. * A SourceObject, an array of SourceObjects, or a string referencing
  21304. * a URL to a media source. It is _highly recommended_ that an object
  21305. * or array of objects is used here, so that source selection
  21306. * algorithms can take the `type` into account.
  21307. *
  21308. * If not provided, this method acts as a getter.
  21309. *
  21310. * @return {string|undefined}
  21311. * If the `source` argument is missing, returns the current source
  21312. * URL. Otherwise, returns nothing/undefined.
  21313. */
  21314. src(source) {
  21315. return this.handleSrc_(source, false);
  21316. }
  21317. /**
  21318. * Set the source object on the tech, returns a boolean that indicates whether
  21319. * there is a tech that can play the source or not
  21320. *
  21321. * @param {Tech~SourceObject} source
  21322. * The source object to set on the Tech
  21323. *
  21324. * @return {boolean}
  21325. * - True if there is no Tech to playback this source
  21326. * - False otherwise
  21327. *
  21328. * @private
  21329. */
  21330. src_(source) {
  21331. const sourceTech = this.selectSource([source]);
  21332. if (!sourceTech) {
  21333. return true;
  21334. }
  21335. if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
  21336. this.changingSrc_ = true;
  21337. // load this technology with the chosen source
  21338. this.loadTech_(sourceTech.tech, sourceTech.source);
  21339. this.tech_.ready(() => {
  21340. this.changingSrc_ = false;
  21341. });
  21342. return false;
  21343. }
  21344. // wait until the tech is ready to set the source
  21345. // and set it synchronously if possible (#2326)
  21346. this.ready(function () {
  21347. // The setSource tech method was added with source handlers
  21348. // so older techs won't support it
  21349. // We need to check the direct prototype for the case where subclasses
  21350. // of the tech do not support source handlers
  21351. if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {
  21352. this.techCall_('setSource', source);
  21353. } else {
  21354. this.techCall_('src', source.src);
  21355. }
  21356. this.changingSrc_ = false;
  21357. }, true);
  21358. return false;
  21359. }
  21360. /**
  21361. * Begin loading the src data.
  21362. */
  21363. load() {
  21364. this.techCall_('load');
  21365. }
  21366. /**
  21367. * Reset the player. Loads the first tech in the techOrder,
  21368. * removes all the text tracks in the existing `tech`,
  21369. * and calls `reset` on the `tech`.
  21370. */
  21371. reset() {
  21372. if (this.paused()) {
  21373. this.doReset_();
  21374. } else {
  21375. const playPromise = this.play();
  21376. silencePromise(playPromise.then(() => this.doReset_()));
  21377. }
  21378. }
  21379. doReset_() {
  21380. if (this.tech_) {
  21381. this.tech_.clearTracks('text');
  21382. }
  21383. this.resetCache_();
  21384. this.poster('');
  21385. this.loadTech_(this.options_.techOrder[0], null);
  21386. this.techCall_('reset');
  21387. this.resetControlBarUI_();
  21388. if (isEvented(this)) {
  21389. this.trigger('playerreset');
  21390. }
  21391. }
  21392. /**
  21393. * Reset Control Bar's UI by calling sub-methods that reset
  21394. * all of Control Bar's components
  21395. */
  21396. resetControlBarUI_() {
  21397. this.resetProgressBar_();
  21398. this.resetPlaybackRate_();
  21399. this.resetVolumeBar_();
  21400. }
  21401. /**
  21402. * Reset tech's progress so progress bar is reset in the UI
  21403. */
  21404. resetProgressBar_() {
  21405. this.currentTime(0);
  21406. const {
  21407. currentTimeDisplay,
  21408. durationDisplay,
  21409. progressControl,
  21410. remainingTimeDisplay
  21411. } = this.controlBar || {};
  21412. const {
  21413. seekBar
  21414. } = progressControl || {};
  21415. if (currentTimeDisplay) {
  21416. currentTimeDisplay.updateContent();
  21417. }
  21418. if (durationDisplay) {
  21419. durationDisplay.updateContent();
  21420. }
  21421. if (remainingTimeDisplay) {
  21422. remainingTimeDisplay.updateContent();
  21423. }
  21424. if (seekBar) {
  21425. seekBar.update();
  21426. if (seekBar.loadProgressBar) {
  21427. seekBar.loadProgressBar.update();
  21428. }
  21429. }
  21430. }
  21431. /**
  21432. * Reset Playback ratio
  21433. */
  21434. resetPlaybackRate_() {
  21435. this.playbackRate(this.defaultPlaybackRate());
  21436. this.handleTechRateChange_();
  21437. }
  21438. /**
  21439. * Reset Volume bar
  21440. */
  21441. resetVolumeBar_() {
  21442. this.volume(1.0);
  21443. this.trigger('volumechange');
  21444. }
  21445. /**
  21446. * Returns all of the current source objects.
  21447. *
  21448. * @return {Tech~SourceObject[]}
  21449. * The current source objects
  21450. */
  21451. currentSources() {
  21452. const source = this.currentSource();
  21453. const sources = [];
  21454. // assume `{}` or `{ src }`
  21455. if (Object.keys(source).length !== 0) {
  21456. sources.push(source);
  21457. }
  21458. return this.cache_.sources || sources;
  21459. }
  21460. /**
  21461. * Returns the current source object.
  21462. *
  21463. * @return {Tech~SourceObject}
  21464. * The current source object
  21465. */
  21466. currentSource() {
  21467. return this.cache_.source || {};
  21468. }
  21469. /**
  21470. * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
  21471. * Can be used in conjunction with `currentType` to assist in rebuilding the current source object.
  21472. *
  21473. * @return {string}
  21474. * The current source
  21475. */
  21476. currentSrc() {
  21477. return this.currentSource() && this.currentSource().src || '';
  21478. }
  21479. /**
  21480. * Get the current source type e.g. video/mp4
  21481. * This can allow you rebuild the current source object so that you could load the same
  21482. * source and tech later
  21483. *
  21484. * @return {string}
  21485. * The source MIME type
  21486. */
  21487. currentType() {
  21488. return this.currentSource() && this.currentSource().type || '';
  21489. }
  21490. /**
  21491. * Get or set the preload attribute
  21492. *
  21493. * @param {boolean} [value]
  21494. * - true means that we should preload
  21495. * - false means that we should not preload
  21496. *
  21497. * @return {string}
  21498. * The preload attribute value when getting
  21499. */
  21500. preload(value) {
  21501. if (value !== undefined) {
  21502. this.techCall_('setPreload', value);
  21503. this.options_.preload = value;
  21504. return;
  21505. }
  21506. return this.techGet_('preload');
  21507. }
  21508. /**
  21509. * Get or set the autoplay option. When this is a boolean it will
  21510. * modify the attribute on the tech. When this is a string the attribute on
  21511. * the tech will be removed and `Player` will handle autoplay on loadstarts.
  21512. *
  21513. * @param {boolean|string} [value]
  21514. * - true: autoplay using the browser behavior
  21515. * - false: do not autoplay
  21516. * - 'play': call play() on every loadstart
  21517. * - 'muted': call muted() then play() on every loadstart
  21518. * - 'any': call play() on every loadstart. if that fails call muted() then play().
  21519. * - *: values other than those listed here will be set `autoplay` to true
  21520. *
  21521. * @return {boolean|string}
  21522. * The current value of autoplay when getting
  21523. */
  21524. autoplay(value) {
  21525. // getter usage
  21526. if (value === undefined) {
  21527. return this.options_.autoplay || false;
  21528. }
  21529. let techAutoplay;
  21530. // if the value is a valid string set it to that, or normalize `true` to 'play', if need be
  21531. if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {
  21532. this.options_.autoplay = value;
  21533. this.manualAutoplay_(typeof value === 'string' ? value : 'play');
  21534. techAutoplay = false;
  21535. // any falsy value sets autoplay to false in the browser,
  21536. // lets do the same
  21537. } else if (!value) {
  21538. this.options_.autoplay = false;
  21539. // any other value (ie truthy) sets autoplay to true
  21540. } else {
  21541. this.options_.autoplay = true;
  21542. }
  21543. techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay;
  21544. // if we don't have a tech then we do not queue up
  21545. // a setAutoplay call on tech ready. We do this because the
  21546. // autoplay option will be passed in the constructor and we
  21547. // do not need to set it twice
  21548. if (this.tech_) {
  21549. this.techCall_('setAutoplay', techAutoplay);
  21550. }
  21551. }
  21552. /**
  21553. * Set or unset the playsinline attribute.
  21554. * Playsinline tells the browser that non-fullscreen playback is preferred.
  21555. *
  21556. * @param {boolean} [value]
  21557. * - true means that we should try to play inline by default
  21558. * - false means that we should use the browser's default playback mode,
  21559. * which in most cases is inline. iOS Safari is a notable exception
  21560. * and plays fullscreen by default.
  21561. *
  21562. * @return {string|Player}
  21563. * - the current value of playsinline
  21564. * - the player when setting
  21565. *
  21566. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  21567. */
  21568. playsinline(value) {
  21569. if (value !== undefined) {
  21570. this.techCall_('setPlaysinline', value);
  21571. this.options_.playsinline = value;
  21572. return this;
  21573. }
  21574. return this.techGet_('playsinline');
  21575. }
  21576. /**
  21577. * Get or set the loop attribute on the video element.
  21578. *
  21579. * @param {boolean} [value]
  21580. * - true means that we should loop the video
  21581. * - false means that we should not loop the video
  21582. *
  21583. * @return {boolean}
  21584. * The current value of loop when getting
  21585. */
  21586. loop(value) {
  21587. if (value !== undefined) {
  21588. this.techCall_('setLoop', value);
  21589. this.options_.loop = value;
  21590. return;
  21591. }
  21592. return this.techGet_('loop');
  21593. }
  21594. /**
  21595. * Get or set the poster image source url
  21596. *
  21597. * @fires Player#posterchange
  21598. *
  21599. * @param {string} [src]
  21600. * Poster image source URL
  21601. *
  21602. * @return {string}
  21603. * The current value of poster when getting
  21604. */
  21605. poster(src) {
  21606. if (src === undefined) {
  21607. return this.poster_;
  21608. }
  21609. // The correct way to remove a poster is to set as an empty string
  21610. // other falsey values will throw errors
  21611. if (!src) {
  21612. src = '';
  21613. }
  21614. if (src === this.poster_) {
  21615. return;
  21616. }
  21617. // update the internal poster variable
  21618. this.poster_ = src;
  21619. // update the tech's poster
  21620. this.techCall_('setPoster', src);
  21621. this.isPosterFromTech_ = false;
  21622. // alert components that the poster has been set
  21623. /**
  21624. * This event fires when the poster image is changed on the player.
  21625. *
  21626. * @event Player#posterchange
  21627. * @type {Event}
  21628. */
  21629. this.trigger('posterchange');
  21630. }
  21631. /**
  21632. * Some techs (e.g. YouTube) can provide a poster source in an
  21633. * asynchronous way. We want the poster component to use this
  21634. * poster source so that it covers up the tech's controls.
  21635. * (YouTube's play button). However we only want to use this
  21636. * source if the player user hasn't set a poster through
  21637. * the normal APIs.
  21638. *
  21639. * @fires Player#posterchange
  21640. * @listens Tech#posterchange
  21641. * @private
  21642. */
  21643. handleTechPosterChange_() {
  21644. if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
  21645. const newPoster = this.tech_.poster() || '';
  21646. if (newPoster !== this.poster_) {
  21647. this.poster_ = newPoster;
  21648. this.isPosterFromTech_ = true;
  21649. // Let components know the poster has changed
  21650. this.trigger('posterchange');
  21651. }
  21652. }
  21653. }
  21654. /**
  21655. * Get or set whether or not the controls are showing.
  21656. *
  21657. * @fires Player#controlsenabled
  21658. *
  21659. * @param {boolean} [bool]
  21660. * - true to turn controls on
  21661. * - false to turn controls off
  21662. *
  21663. * @return {boolean}
  21664. * The current value of controls when getting
  21665. */
  21666. controls(bool) {
  21667. if (bool === undefined) {
  21668. return !!this.controls_;
  21669. }
  21670. bool = !!bool;
  21671. // Don't trigger a change event unless it actually changed
  21672. if (this.controls_ === bool) {
  21673. return;
  21674. }
  21675. this.controls_ = bool;
  21676. if (this.usingNativeControls()) {
  21677. this.techCall_('setControls', bool);
  21678. }
  21679. if (this.controls_) {
  21680. this.removeClass('vjs-controls-disabled');
  21681. this.addClass('vjs-controls-enabled');
  21682. /**
  21683. * @event Player#controlsenabled
  21684. * @type {Event}
  21685. */
  21686. this.trigger('controlsenabled');
  21687. if (!this.usingNativeControls()) {
  21688. this.addTechControlsListeners_();
  21689. }
  21690. } else {
  21691. this.removeClass('vjs-controls-enabled');
  21692. this.addClass('vjs-controls-disabled');
  21693. /**
  21694. * @event Player#controlsdisabled
  21695. * @type {Event}
  21696. */
  21697. this.trigger('controlsdisabled');
  21698. if (!this.usingNativeControls()) {
  21699. this.removeTechControlsListeners_();
  21700. }
  21701. }
  21702. }
  21703. /**
  21704. * Toggle native controls on/off. Native controls are the controls built into
  21705. * devices (e.g. default iPhone controls) or other techs
  21706. * (e.g. Vimeo Controls)
  21707. * **This should only be set by the current tech, because only the tech knows
  21708. * if it can support native controls**
  21709. *
  21710. * @fires Player#usingnativecontrols
  21711. * @fires Player#usingcustomcontrols
  21712. *
  21713. * @param {boolean} [bool]
  21714. * - true to turn native controls on
  21715. * - false to turn native controls off
  21716. *
  21717. * @return {boolean}
  21718. * The current value of native controls when getting
  21719. */
  21720. usingNativeControls(bool) {
  21721. if (bool === undefined) {
  21722. return !!this.usingNativeControls_;
  21723. }
  21724. bool = !!bool;
  21725. // Don't trigger a change event unless it actually changed
  21726. if (this.usingNativeControls_ === bool) {
  21727. return;
  21728. }
  21729. this.usingNativeControls_ = bool;
  21730. if (this.usingNativeControls_) {
  21731. this.addClass('vjs-using-native-controls');
  21732. /**
  21733. * player is using the native device controls
  21734. *
  21735. * @event Player#usingnativecontrols
  21736. * @type {Event}
  21737. */
  21738. this.trigger('usingnativecontrols');
  21739. } else {
  21740. this.removeClass('vjs-using-native-controls');
  21741. /**
  21742. * player is using the custom HTML controls
  21743. *
  21744. * @event Player#usingcustomcontrols
  21745. * @type {Event}
  21746. */
  21747. this.trigger('usingcustomcontrols');
  21748. }
  21749. }
  21750. /**
  21751. * Set or get the current MediaError
  21752. *
  21753. * @fires Player#error
  21754. *
  21755. * @param {MediaError|string|number} [err]
  21756. * A MediaError or a string/number to be turned
  21757. * into a MediaError
  21758. *
  21759. * @return {MediaError|null}
  21760. * The current MediaError when getting (or null)
  21761. */
  21762. error(err) {
  21763. if (err === undefined) {
  21764. return this.error_ || null;
  21765. }
  21766. // allow hooks to modify error object
  21767. hooks('beforeerror').forEach(hookFunction => {
  21768. const newErr = hookFunction(this, err);
  21769. if (!(isObject(newErr) && !Array.isArray(newErr) || typeof newErr === 'string' || typeof newErr === 'number' || newErr === null)) {
  21770. this.log.error('please return a value that MediaError expects in beforeerror hooks');
  21771. return;
  21772. }
  21773. err = newErr;
  21774. });
  21775. // Suppress the first error message for no compatible source until
  21776. // user interaction
  21777. if (this.options_.suppressNotSupportedError && err && err.code === 4) {
  21778. const triggerSuppressedError = function () {
  21779. this.error(err);
  21780. };
  21781. this.options_.suppressNotSupportedError = false;
  21782. this.any(['click', 'touchstart'], triggerSuppressedError);
  21783. this.one('loadstart', function () {
  21784. this.off(['click', 'touchstart'], triggerSuppressedError);
  21785. });
  21786. return;
  21787. }
  21788. // restoring to default
  21789. if (err === null) {
  21790. this.error_ = err;
  21791. this.removeClass('vjs-error');
  21792. if (this.errorDisplay) {
  21793. this.errorDisplay.close();
  21794. }
  21795. return;
  21796. }
  21797. this.error_ = new MediaError(err);
  21798. // add the vjs-error classname to the player
  21799. this.addClass('vjs-error');
  21800. // log the name of the error type and any message
  21801. // IE11 logs "[object object]" and required you to expand message to see error object
  21802. log$1.error(`(CODE:${this.error_.code} ${MediaError.errorTypes[this.error_.code]})`, this.error_.message, this.error_);
  21803. /**
  21804. * @event Player#error
  21805. * @type {Event}
  21806. */
  21807. this.trigger('error');
  21808. // notify hooks of the per player error
  21809. hooks('error').forEach(hookFunction => hookFunction(this, this.error_));
  21810. return;
  21811. }
  21812. /**
  21813. * Report user activity
  21814. *
  21815. * @param {Object} event
  21816. * Event object
  21817. */
  21818. reportUserActivity(event) {
  21819. this.userActivity_ = true;
  21820. }
  21821. /**
  21822. * Get/set if user is active
  21823. *
  21824. * @fires Player#useractive
  21825. * @fires Player#userinactive
  21826. *
  21827. * @param {boolean} [bool]
  21828. * - true if the user is active
  21829. * - false if the user is inactive
  21830. *
  21831. * @return {boolean}
  21832. * The current value of userActive when getting
  21833. */
  21834. userActive(bool) {
  21835. if (bool === undefined) {
  21836. return this.userActive_;
  21837. }
  21838. bool = !!bool;
  21839. if (bool === this.userActive_) {
  21840. return;
  21841. }
  21842. this.userActive_ = bool;
  21843. if (this.userActive_) {
  21844. this.userActivity_ = true;
  21845. this.removeClass('vjs-user-inactive');
  21846. this.addClass('vjs-user-active');
  21847. /**
  21848. * @event Player#useractive
  21849. * @type {Event}
  21850. */
  21851. this.trigger('useractive');
  21852. return;
  21853. }
  21854. // Chrome/Safari/IE have bugs where when you change the cursor it can
  21855. // trigger a mousemove event. This causes an issue when you're hiding
  21856. // the cursor when the user is inactive, and a mousemove signals user
  21857. // activity. Making it impossible to go into inactive mode. Specifically
  21858. // this happens in fullscreen when we really need to hide the cursor.
  21859. //
  21860. // When this gets resolved in ALL browsers it can be removed
  21861. // https://code.google.com/p/chromium/issues/detail?id=103041
  21862. if (this.tech_) {
  21863. this.tech_.one('mousemove', function (e) {
  21864. e.stopPropagation();
  21865. e.preventDefault();
  21866. });
  21867. }
  21868. this.userActivity_ = false;
  21869. this.removeClass('vjs-user-active');
  21870. this.addClass('vjs-user-inactive');
  21871. /**
  21872. * @event Player#userinactive
  21873. * @type {Event}
  21874. */
  21875. this.trigger('userinactive');
  21876. }
  21877. /**
  21878. * Listen for user activity based on timeout value
  21879. *
  21880. * @private
  21881. */
  21882. listenForUserActivity_() {
  21883. let mouseInProgress;
  21884. let lastMoveX;
  21885. let lastMoveY;
  21886. const handleActivity = bind_(this, this.reportUserActivity);
  21887. const handleMouseMove = function (e) {
  21888. // #1068 - Prevent mousemove spamming
  21889. // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
  21890. if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
  21891. lastMoveX = e.screenX;
  21892. lastMoveY = e.screenY;
  21893. handleActivity();
  21894. }
  21895. };
  21896. const handleMouseDown = function () {
  21897. handleActivity();
  21898. // For as long as the they are touching the device or have their mouse down,
  21899. // we consider them active even if they're not moving their finger or mouse.
  21900. // So we want to continue to update that they are active
  21901. this.clearInterval(mouseInProgress);
  21902. // Setting userActivity=true now and setting the interval to the same time
  21903. // as the activityCheck interval (250) should ensure we never miss the
  21904. // next activityCheck
  21905. mouseInProgress = this.setInterval(handleActivity, 250);
  21906. };
  21907. const handleMouseUpAndMouseLeave = function (event) {
  21908. handleActivity();
  21909. // Stop the interval that maintains activity if the mouse/touch is down
  21910. this.clearInterval(mouseInProgress);
  21911. };
  21912. // Any mouse movement will be considered user activity
  21913. this.on('mousedown', handleMouseDown);
  21914. this.on('mousemove', handleMouseMove);
  21915. this.on('mouseup', handleMouseUpAndMouseLeave);
  21916. this.on('mouseleave', handleMouseUpAndMouseLeave);
  21917. const controlBar = this.getChild('controlBar');
  21918. // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed)
  21919. // controlBar would no longer be hidden by default timeout.
  21920. if (controlBar && !IS_IOS && !IS_ANDROID) {
  21921. controlBar.on('mouseenter', function (event) {
  21922. if (this.player().options_.inactivityTimeout !== 0) {
  21923. this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;
  21924. }
  21925. this.player().options_.inactivityTimeout = 0;
  21926. });
  21927. controlBar.on('mouseleave', function (event) {
  21928. this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;
  21929. });
  21930. }
  21931. // Listen for keyboard navigation
  21932. // Shouldn't need to use inProgress interval because of key repeat
  21933. this.on('keydown', handleActivity);
  21934. this.on('keyup', handleActivity);
  21935. // Run an interval every 250 milliseconds instead of stuffing everything into
  21936. // the mousemove/touchmove function itself, to prevent performance degradation.
  21937. // `this.reportUserActivity` simply sets this.userActivity_ to true, which
  21938. // then gets picked up by this loop
  21939. // http://ejohn.org/blog/learning-from-twitter/
  21940. let inactivityTimeout;
  21941. this.setInterval(function () {
  21942. // Check to see if mouse/touch activity has happened
  21943. if (!this.userActivity_) {
  21944. return;
  21945. }
  21946. // Reset the activity tracker
  21947. this.userActivity_ = false;
  21948. // If the user state was inactive, set the state to active
  21949. this.userActive(true);
  21950. // Clear any existing inactivity timeout to start the timer over
  21951. this.clearTimeout(inactivityTimeout);
  21952. const timeout = this.options_.inactivityTimeout;
  21953. if (timeout <= 0) {
  21954. return;
  21955. }
  21956. // In <timeout> milliseconds, if no more activity has occurred the
  21957. // user will be considered inactive
  21958. inactivityTimeout = this.setTimeout(function () {
  21959. // Protect against the case where the inactivityTimeout can trigger just
  21960. // before the next user activity is picked up by the activity check loop
  21961. // causing a flicker
  21962. if (!this.userActivity_) {
  21963. this.userActive(false);
  21964. }
  21965. }, timeout);
  21966. }, 250);
  21967. }
  21968. /**
  21969. * Gets or sets the current playback rate. A playback rate of
  21970. * 1.0 represents normal speed and 0.5 would indicate half-speed
  21971. * playback, for instance.
  21972. *
  21973. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
  21974. *
  21975. * @param {number} [rate]
  21976. * New playback rate to set.
  21977. *
  21978. * @return {number}
  21979. * The current playback rate when getting or 1.0
  21980. */
  21981. playbackRate(rate) {
  21982. if (rate !== undefined) {
  21983. // NOTE: this.cache_.lastPlaybackRate is set from the tech handler
  21984. // that is registered above
  21985. this.techCall_('setPlaybackRate', rate);
  21986. return;
  21987. }
  21988. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  21989. return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');
  21990. }
  21991. return 1.0;
  21992. }
  21993. /**
  21994. * Gets or sets the current default playback rate. A default playback rate of
  21995. * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
  21996. * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not
  21997. * not the current playbackRate.
  21998. *
  21999. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
  22000. *
  22001. * @param {number} [rate]
  22002. * New default playback rate to set.
  22003. *
  22004. * @return {number|Player}
  22005. * - The default playback rate when getting or 1.0
  22006. * - the player when setting
  22007. */
  22008. defaultPlaybackRate(rate) {
  22009. if (rate !== undefined) {
  22010. return this.techCall_('setDefaultPlaybackRate', rate);
  22011. }
  22012. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  22013. return this.techGet_('defaultPlaybackRate');
  22014. }
  22015. return 1.0;
  22016. }
  22017. /**
  22018. * Gets or sets the audio flag
  22019. *
  22020. * @param {boolean} bool
  22021. * - true signals that this is an audio player
  22022. * - false signals that this is not an audio player
  22023. *
  22024. * @return {boolean}
  22025. * The current value of isAudio when getting
  22026. */
  22027. isAudio(bool) {
  22028. if (bool !== undefined) {
  22029. this.isAudio_ = !!bool;
  22030. return;
  22031. }
  22032. return !!this.isAudio_;
  22033. }
  22034. enableAudioOnlyUI_() {
  22035. // Update styling immediately to show the control bar so we can get its height
  22036. this.addClass('vjs-audio-only-mode');
  22037. const playerChildren = this.children();
  22038. const controlBar = this.getChild('ControlBar');
  22039. const controlBarHeight = controlBar && controlBar.currentHeight();
  22040. // Hide all player components except the control bar. Control bar components
  22041. // needed only for video are hidden with CSS
  22042. playerChildren.forEach(child => {
  22043. if (child === controlBar) {
  22044. return;
  22045. }
  22046. if (child.el_ && !child.hasClass('vjs-hidden')) {
  22047. child.hide();
  22048. this.audioOnlyCache_.hiddenChildren.push(child);
  22049. }
  22050. });
  22051. this.audioOnlyCache_.playerHeight = this.currentHeight();
  22052. // Set the player height the same as the control bar
  22053. this.height(controlBarHeight);
  22054. this.trigger('audioonlymodechange');
  22055. }
  22056. disableAudioOnlyUI_() {
  22057. this.removeClass('vjs-audio-only-mode');
  22058. // Show player components that were previously hidden
  22059. this.audioOnlyCache_.hiddenChildren.forEach(child => child.show());
  22060. // Reset player height
  22061. this.height(this.audioOnlyCache_.playerHeight);
  22062. this.trigger('audioonlymodechange');
  22063. }
  22064. /**
  22065. * Get the current audioOnlyMode state or set audioOnlyMode to true or false.
  22066. *
  22067. * Setting this to `true` will hide all player components except the control bar,
  22068. * as well as control bar components needed only for video.
  22069. *
  22070. * @param {boolean} [value]
  22071. * The value to set audioOnlyMode to.
  22072. *
  22073. * @return {Promise|boolean}
  22074. * A Promise is returned when setting the state, and a boolean when getting
  22075. * the present state
  22076. */
  22077. audioOnlyMode(value) {
  22078. if (typeof value !== 'boolean' || value === this.audioOnlyMode_) {
  22079. return this.audioOnlyMode_;
  22080. }
  22081. this.audioOnlyMode_ = value;
  22082. // Enable Audio Only Mode
  22083. if (value) {
  22084. const exitPromises = [];
  22085. // Fullscreen and PiP are not supported in audioOnlyMode, so exit if we need to.
  22086. if (this.isInPictureInPicture()) {
  22087. exitPromises.push(this.exitPictureInPicture());
  22088. }
  22089. if (this.isFullscreen()) {
  22090. exitPromises.push(this.exitFullscreen());
  22091. }
  22092. if (this.audioPosterMode()) {
  22093. exitPromises.push(this.audioPosterMode(false));
  22094. }
  22095. return Promise.all(exitPromises).then(() => this.enableAudioOnlyUI_());
  22096. }
  22097. // Disable Audio Only Mode
  22098. return Promise.resolve().then(() => this.disableAudioOnlyUI_());
  22099. }
  22100. enablePosterModeUI_() {
  22101. // Hide the video element and show the poster image to enable posterModeUI
  22102. const tech = this.tech_ && this.tech_;
  22103. tech.hide();
  22104. this.addClass('vjs-audio-poster-mode');
  22105. this.trigger('audiopostermodechange');
  22106. }
  22107. disablePosterModeUI_() {
  22108. // Show the video element and hide the poster image to disable posterModeUI
  22109. const tech = this.tech_ && this.tech_;
  22110. tech.show();
  22111. this.removeClass('vjs-audio-poster-mode');
  22112. this.trigger('audiopostermodechange');
  22113. }
  22114. /**
  22115. * Get the current audioPosterMode state or set audioPosterMode to true or false
  22116. *
  22117. * @param {boolean} [value]
  22118. * The value to set audioPosterMode to.
  22119. *
  22120. * @return {Promise|boolean}
  22121. * A Promise is returned when setting the state, and a boolean when getting
  22122. * the present state
  22123. */
  22124. audioPosterMode(value) {
  22125. if (typeof value !== 'boolean' || value === this.audioPosterMode_) {
  22126. return this.audioPosterMode_;
  22127. }
  22128. this.audioPosterMode_ = value;
  22129. if (value) {
  22130. if (this.audioOnlyMode()) {
  22131. const audioOnlyModePromise = this.audioOnlyMode(false);
  22132. return audioOnlyModePromise.then(() => {
  22133. // enable audio poster mode after audio only mode is disabled
  22134. this.enablePosterModeUI_();
  22135. });
  22136. }
  22137. return Promise.resolve().then(() => {
  22138. // enable audio poster mode
  22139. this.enablePosterModeUI_();
  22140. });
  22141. }
  22142. return Promise.resolve().then(() => {
  22143. // disable audio poster mode
  22144. this.disablePosterModeUI_();
  22145. });
  22146. }
  22147. /**
  22148. * A helper method for adding a {@link TextTrack} to our
  22149. * {@link TextTrackList}.
  22150. *
  22151. * In addition to the W3C settings we allow adding additional info through options.
  22152. *
  22153. * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
  22154. *
  22155. * @param {string} [kind]
  22156. * the kind of TextTrack you are adding
  22157. *
  22158. * @param {string} [label]
  22159. * the label to give the TextTrack label
  22160. *
  22161. * @param {string} [language]
  22162. * the language to set on the TextTrack
  22163. *
  22164. * @return {TextTrack|undefined}
  22165. * the TextTrack that was added or undefined
  22166. * if there is no tech
  22167. */
  22168. addTextTrack(kind, label, language) {
  22169. if (this.tech_) {
  22170. return this.tech_.addTextTrack(kind, label, language);
  22171. }
  22172. }
  22173. /**
  22174. * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}.
  22175. *
  22176. * @param {Object} options
  22177. * Options to pass to {@link HTMLTrackElement} during creation. See
  22178. * {@link HTMLTrackElement} for object properties that you should use.
  22179. *
  22180. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack will not be removed
  22181. * from the TextTrackList and HtmlTrackElementList
  22182. * after a source change
  22183. *
  22184. * @return { import('./tracks/html-track-element').default }
  22185. * the HTMLTrackElement that was created and added
  22186. * to the HtmlTrackElementList and the remote
  22187. * TextTrackList
  22188. *
  22189. */
  22190. addRemoteTextTrack(options, manualCleanup) {
  22191. if (this.tech_) {
  22192. return this.tech_.addRemoteTextTrack(options, manualCleanup);
  22193. }
  22194. }
  22195. /**
  22196. * Remove a remote {@link TextTrack} from the respective
  22197. * {@link TextTrackList} and {@link HtmlTrackElementList}.
  22198. *
  22199. * @param {Object} track
  22200. * Remote {@link TextTrack} to remove
  22201. *
  22202. * @return {undefined}
  22203. * does not return anything
  22204. */
  22205. removeRemoteTextTrack(obj = {}) {
  22206. let {
  22207. track
  22208. } = obj;
  22209. if (!track) {
  22210. track = obj;
  22211. }
  22212. // destructure the input into an object with a track argument, defaulting to arguments[0]
  22213. // default the whole argument to an empty object if nothing was passed in
  22214. if (this.tech_) {
  22215. return this.tech_.removeRemoteTextTrack(track);
  22216. }
  22217. }
  22218. /**
  22219. * Gets available media playback quality metrics as specified by the W3C's Media
  22220. * Playback Quality API.
  22221. *
  22222. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  22223. *
  22224. * @return {Object|undefined}
  22225. * An object with supported media playback quality metrics or undefined if there
  22226. * is no tech or the tech does not support it.
  22227. */
  22228. getVideoPlaybackQuality() {
  22229. return this.techGet_('getVideoPlaybackQuality');
  22230. }
  22231. /**
  22232. * Get video width
  22233. *
  22234. * @return {number}
  22235. * current video width
  22236. */
  22237. videoWidth() {
  22238. return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
  22239. }
  22240. /**
  22241. * Get video height
  22242. *
  22243. * @return {number}
  22244. * current video height
  22245. */
  22246. videoHeight() {
  22247. return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
  22248. }
  22249. /**
  22250. * The player's language code.
  22251. *
  22252. * Changing the language will trigger
  22253. * [languagechange]{@link Player#event:languagechange}
  22254. * which Components can use to update control text.
  22255. * ClickableComponent will update its control text by default on
  22256. * [languagechange]{@link Player#event:languagechange}.
  22257. *
  22258. * @fires Player#languagechange
  22259. *
  22260. * @param {string} [code]
  22261. * the language code to set the player to
  22262. *
  22263. * @return {string}
  22264. * The current language code when getting
  22265. */
  22266. language(code) {
  22267. if (code === undefined) {
  22268. return this.language_;
  22269. }
  22270. if (this.language_ !== String(code).toLowerCase()) {
  22271. this.language_ = String(code).toLowerCase();
  22272. // during first init, it's possible some things won't be evented
  22273. if (isEvented(this)) {
  22274. /**
  22275. * fires when the player language change
  22276. *
  22277. * @event Player#languagechange
  22278. * @type {Event}
  22279. */
  22280. this.trigger('languagechange');
  22281. }
  22282. }
  22283. }
  22284. /**
  22285. * Get the player's language dictionary
  22286. * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
  22287. * Languages specified directly in the player options have precedence
  22288. *
  22289. * @return {Array}
  22290. * An array of of supported languages
  22291. */
  22292. languages() {
  22293. return merge$1(Player.prototype.options_.languages, this.languages_);
  22294. }
  22295. /**
  22296. * returns a JavaScript object representing the current track
  22297. * information. **DOES not return it as JSON**
  22298. *
  22299. * @return {Object}
  22300. * Object representing the current of track info
  22301. */
  22302. toJSON() {
  22303. const options = merge$1(this.options_);
  22304. const tracks = options.tracks;
  22305. options.tracks = [];
  22306. for (let i = 0; i < tracks.length; i++) {
  22307. let track = tracks[i];
  22308. // deep merge tracks and null out player so no circular references
  22309. track = merge$1(track);
  22310. track.player = undefined;
  22311. options.tracks[i] = track;
  22312. }
  22313. return options;
  22314. }
  22315. /**
  22316. * Creates a simple modal dialog (an instance of the {@link ModalDialog}
  22317. * component) that immediately overlays the player with arbitrary
  22318. * content and removes itself when closed.
  22319. *
  22320. * @param {string|Function|Element|Array|null} content
  22321. * Same as {@link ModalDialog#content}'s param of the same name.
  22322. * The most straight-forward usage is to provide a string or DOM
  22323. * element.
  22324. *
  22325. * @param {Object} [options]
  22326. * Extra options which will be passed on to the {@link ModalDialog}.
  22327. *
  22328. * @return {ModalDialog}
  22329. * the {@link ModalDialog} that was created
  22330. */
  22331. createModal(content, options) {
  22332. options = options || {};
  22333. options.content = content || '';
  22334. const modal = new ModalDialog(this, options);
  22335. this.addChild(modal);
  22336. modal.on('dispose', () => {
  22337. this.removeChild(modal);
  22338. });
  22339. modal.open();
  22340. return modal;
  22341. }
  22342. /**
  22343. * Change breakpoint classes when the player resizes.
  22344. *
  22345. * @private
  22346. */
  22347. updateCurrentBreakpoint_() {
  22348. if (!this.responsive()) {
  22349. return;
  22350. }
  22351. const currentBreakpoint = this.currentBreakpoint();
  22352. const currentWidth = this.currentWidth();
  22353. for (let i = 0; i < BREAKPOINT_ORDER.length; i++) {
  22354. const candidateBreakpoint = BREAKPOINT_ORDER[i];
  22355. const maxWidth = this.breakpoints_[candidateBreakpoint];
  22356. if (currentWidth <= maxWidth) {
  22357. // The current breakpoint did not change, nothing to do.
  22358. if (currentBreakpoint === candidateBreakpoint) {
  22359. return;
  22360. }
  22361. // Only remove a class if there is a current breakpoint.
  22362. if (currentBreakpoint) {
  22363. this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
  22364. }
  22365. this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
  22366. this.breakpoint_ = candidateBreakpoint;
  22367. break;
  22368. }
  22369. }
  22370. }
  22371. /**
  22372. * Removes the current breakpoint.
  22373. *
  22374. * @private
  22375. */
  22376. removeCurrentBreakpoint_() {
  22377. const className = this.currentBreakpointClass();
  22378. this.breakpoint_ = '';
  22379. if (className) {
  22380. this.removeClass(className);
  22381. }
  22382. }
  22383. /**
  22384. * Get or set breakpoints on the player.
  22385. *
  22386. * Calling this method with an object or `true` will remove any previous
  22387. * custom breakpoints and start from the defaults again.
  22388. *
  22389. * @param {Object|boolean} [breakpoints]
  22390. * If an object is given, it can be used to provide custom
  22391. * breakpoints. If `true` is given, will set default breakpoints.
  22392. * If this argument is not given, will simply return the current
  22393. * breakpoints.
  22394. *
  22395. * @param {number} [breakpoints.tiny]
  22396. * The maximum width for the "vjs-layout-tiny" class.
  22397. *
  22398. * @param {number} [breakpoints.xsmall]
  22399. * The maximum width for the "vjs-layout-x-small" class.
  22400. *
  22401. * @param {number} [breakpoints.small]
  22402. * The maximum width for the "vjs-layout-small" class.
  22403. *
  22404. * @param {number} [breakpoints.medium]
  22405. * The maximum width for the "vjs-layout-medium" class.
  22406. *
  22407. * @param {number} [breakpoints.large]
  22408. * The maximum width for the "vjs-layout-large" class.
  22409. *
  22410. * @param {number} [breakpoints.xlarge]
  22411. * The maximum width for the "vjs-layout-x-large" class.
  22412. *
  22413. * @param {number} [breakpoints.huge]
  22414. * The maximum width for the "vjs-layout-huge" class.
  22415. *
  22416. * @return {Object}
  22417. * An object mapping breakpoint names to maximum width values.
  22418. */
  22419. breakpoints(breakpoints) {
  22420. // Used as a getter.
  22421. if (breakpoints === undefined) {
  22422. return Object.assign(this.breakpoints_);
  22423. }
  22424. this.breakpoint_ = '';
  22425. this.breakpoints_ = Object.assign({}, DEFAULT_BREAKPOINTS, breakpoints);
  22426. // When breakpoint definitions change, we need to update the currently
  22427. // selected breakpoint.
  22428. this.updateCurrentBreakpoint_();
  22429. // Clone the breakpoints before returning.
  22430. return Object.assign(this.breakpoints_);
  22431. }
  22432. /**
  22433. * Get or set a flag indicating whether or not this player should adjust
  22434. * its UI based on its dimensions.
  22435. *
  22436. * @param {boolean} value
  22437. * Should be `true` if the player should adjust its UI based on its
  22438. * dimensions; otherwise, should be `false`.
  22439. *
  22440. * @return {boolean}
  22441. * Will be `true` if this player should adjust its UI based on its
  22442. * dimensions; otherwise, will be `false`.
  22443. */
  22444. responsive(value) {
  22445. // Used as a getter.
  22446. if (value === undefined) {
  22447. return this.responsive_;
  22448. }
  22449. value = Boolean(value);
  22450. const current = this.responsive_;
  22451. // Nothing changed.
  22452. if (value === current) {
  22453. return;
  22454. }
  22455. // The value actually changed, set it.
  22456. this.responsive_ = value;
  22457. // Start listening for breakpoints and set the initial breakpoint if the
  22458. // player is now responsive.
  22459. if (value) {
  22460. this.on('playerresize', this.boundUpdateCurrentBreakpoint_);
  22461. this.updateCurrentBreakpoint_();
  22462. // Stop listening for breakpoints if the player is no longer responsive.
  22463. } else {
  22464. this.off('playerresize', this.boundUpdateCurrentBreakpoint_);
  22465. this.removeCurrentBreakpoint_();
  22466. }
  22467. return value;
  22468. }
  22469. /**
  22470. * Get current breakpoint name, if any.
  22471. *
  22472. * @return {string}
  22473. * If there is currently a breakpoint set, returns a the key from the
  22474. * breakpoints object matching it. Otherwise, returns an empty string.
  22475. */
  22476. currentBreakpoint() {
  22477. return this.breakpoint_;
  22478. }
  22479. /**
  22480. * Get the current breakpoint class name.
  22481. *
  22482. * @return {string}
  22483. * The matching class name (e.g. `"vjs-layout-tiny"` or
  22484. * `"vjs-layout-large"`) for the current breakpoint. Empty string if
  22485. * there is no current breakpoint.
  22486. */
  22487. currentBreakpointClass() {
  22488. return BREAKPOINT_CLASSES[this.breakpoint_] || '';
  22489. }
  22490. /**
  22491. * An object that describes a single piece of media.
  22492. *
  22493. * Properties that are not part of this type description will be retained; so,
  22494. * this can be viewed as a generic metadata storage mechanism as well.
  22495. *
  22496. * @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}
  22497. * @typedef {Object} Player~MediaObject
  22498. *
  22499. * @property {string} [album]
  22500. * Unused, except if this object is passed to the `MediaSession`
  22501. * API.
  22502. *
  22503. * @property {string} [artist]
  22504. * Unused, except if this object is passed to the `MediaSession`
  22505. * API.
  22506. *
  22507. * @property {Object[]} [artwork]
  22508. * Unused, except if this object is passed to the `MediaSession`
  22509. * API. If not specified, will be populated via the `poster`, if
  22510. * available.
  22511. *
  22512. * @property {string} [poster]
  22513. * URL to an image that will display before playback.
  22514. *
  22515. * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src]
  22516. * A single source object, an array of source objects, or a string
  22517. * referencing a URL to a media source. It is _highly recommended_
  22518. * that an object or array of objects is used here, so that source
  22519. * selection algorithms can take the `type` into account.
  22520. *
  22521. * @property {string} [title]
  22522. * Unused, except if this object is passed to the `MediaSession`
  22523. * API.
  22524. *
  22525. * @property {Object[]} [textTracks]
  22526. * An array of objects to be used to create text tracks, following
  22527. * the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}.
  22528. * For ease of removal, these will be created as "remote" text
  22529. * tracks and set to automatically clean up on source changes.
  22530. *
  22531. * These objects may have properties like `src`, `kind`, `label`,
  22532. * and `language`, see {@link Tech#createRemoteTextTrack}.
  22533. */
  22534. /**
  22535. * Populate the player using a {@link Player~MediaObject|MediaObject}.
  22536. *
  22537. * @param {Player~MediaObject} media
  22538. * A media object.
  22539. *
  22540. * @param {Function} ready
  22541. * A callback to be called when the player is ready.
  22542. */
  22543. loadMedia(media, ready) {
  22544. if (!media || typeof media !== 'object') {
  22545. return;
  22546. }
  22547. this.reset();
  22548. // Clone the media object so it cannot be mutated from outside.
  22549. this.cache_.media = merge$1(media);
  22550. const {
  22551. artist,
  22552. artwork,
  22553. description,
  22554. poster,
  22555. src,
  22556. textTracks,
  22557. title
  22558. } = this.cache_.media;
  22559. // If `artwork` is not given, create it using `poster`.
  22560. if (!artwork && poster) {
  22561. this.cache_.media.artwork = [{
  22562. src: poster,
  22563. type: getMimetype(poster)
  22564. }];
  22565. }
  22566. if (src) {
  22567. this.src(src);
  22568. }
  22569. if (poster) {
  22570. this.poster(poster);
  22571. }
  22572. if (Array.isArray(textTracks)) {
  22573. textTracks.forEach(tt => this.addRemoteTextTrack(tt, false));
  22574. }
  22575. if (this.titleBar) {
  22576. this.titleBar.update({
  22577. title,
  22578. description: description || artist || ''
  22579. });
  22580. }
  22581. this.ready(ready);
  22582. }
  22583. /**
  22584. * Get a clone of the current {@link Player~MediaObject} for this player.
  22585. *
  22586. * If the `loadMedia` method has not been used, will attempt to return a
  22587. * {@link Player~MediaObject} based on the current state of the player.
  22588. *
  22589. * @return {Player~MediaObject}
  22590. */
  22591. getMedia() {
  22592. if (!this.cache_.media) {
  22593. const poster = this.poster();
  22594. const src = this.currentSources();
  22595. const textTracks = Array.prototype.map.call(this.remoteTextTracks(), tt => ({
  22596. kind: tt.kind,
  22597. label: tt.label,
  22598. language: tt.language,
  22599. src: tt.src
  22600. }));
  22601. const media = {
  22602. src,
  22603. textTracks
  22604. };
  22605. if (poster) {
  22606. media.poster = poster;
  22607. media.artwork = [{
  22608. src: media.poster,
  22609. type: getMimetype(media.poster)
  22610. }];
  22611. }
  22612. return media;
  22613. }
  22614. return merge$1(this.cache_.media);
  22615. }
  22616. /**
  22617. * Gets tag settings
  22618. *
  22619. * @param {Element} tag
  22620. * The player tag
  22621. *
  22622. * @return {Object}
  22623. * An object containing all of the settings
  22624. * for a player tag
  22625. */
  22626. static getTagSettings(tag) {
  22627. const baseOptions = {
  22628. sources: [],
  22629. tracks: []
  22630. };
  22631. const tagOptions = getAttributes(tag);
  22632. const dataSetup = tagOptions['data-setup'];
  22633. if (hasClass(tag, 'vjs-fill')) {
  22634. tagOptions.fill = true;
  22635. }
  22636. if (hasClass(tag, 'vjs-fluid')) {
  22637. tagOptions.fluid = true;
  22638. }
  22639. // Check if data-setup attr exists.
  22640. if (dataSetup !== null) {
  22641. // Parse options JSON
  22642. // If empty string, make it a parsable json object.
  22643. const [err, data] = safeParseTuple(dataSetup || '{}');
  22644. if (err) {
  22645. log$1.error(err);
  22646. }
  22647. Object.assign(tagOptions, data);
  22648. }
  22649. Object.assign(baseOptions, tagOptions);
  22650. // Get tag children settings
  22651. if (tag.hasChildNodes()) {
  22652. const children = tag.childNodes;
  22653. for (let i = 0, j = children.length; i < j; i++) {
  22654. const child = children[i];
  22655. // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
  22656. const childName = child.nodeName.toLowerCase();
  22657. if (childName === 'source') {
  22658. baseOptions.sources.push(getAttributes(child));
  22659. } else if (childName === 'track') {
  22660. baseOptions.tracks.push(getAttributes(child));
  22661. }
  22662. }
  22663. }
  22664. return baseOptions;
  22665. }
  22666. /**
  22667. * Set debug mode to enable/disable logs at info level.
  22668. *
  22669. * @param {boolean} enabled
  22670. * @fires Player#debugon
  22671. * @fires Player#debugoff
  22672. */
  22673. debug(enabled) {
  22674. if (enabled === undefined) {
  22675. return this.debugEnabled_;
  22676. }
  22677. if (enabled) {
  22678. this.trigger('debugon');
  22679. this.previousLogLevel_ = this.log.level;
  22680. this.log.level('debug');
  22681. this.debugEnabled_ = true;
  22682. } else {
  22683. this.trigger('debugoff');
  22684. this.log.level(this.previousLogLevel_);
  22685. this.previousLogLevel_ = undefined;
  22686. this.debugEnabled_ = false;
  22687. }
  22688. }
  22689. /**
  22690. * Set or get current playback rates.
  22691. * Takes an array and updates the playback rates menu with the new items.
  22692. * Pass in an empty array to hide the menu.
  22693. * Values other than arrays are ignored.
  22694. *
  22695. * @fires Player#playbackrateschange
  22696. * @param {number[]} newRates
  22697. * The new rates that the playback rates menu should update to.
  22698. * An empty array will hide the menu
  22699. * @return {number[]} When used as a getter will return the current playback rates
  22700. */
  22701. playbackRates(newRates) {
  22702. if (newRates === undefined) {
  22703. return this.cache_.playbackRates;
  22704. }
  22705. // ignore any value that isn't an array
  22706. if (!Array.isArray(newRates)) {
  22707. return;
  22708. }
  22709. // ignore any arrays that don't only contain numbers
  22710. if (!newRates.every(rate => typeof rate === 'number')) {
  22711. return;
  22712. }
  22713. this.cache_.playbackRates = newRates;
  22714. /**
  22715. * fires when the playback rates in a player are changed
  22716. *
  22717. * @event Player#playbackrateschange
  22718. * @type {Event}
  22719. */
  22720. this.trigger('playbackrateschange');
  22721. }
  22722. }
  22723. /**
  22724. * Get the {@link VideoTrackList}
  22725. *
  22726. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
  22727. *
  22728. * @return {VideoTrackList}
  22729. * the current video track list
  22730. *
  22731. * @method Player.prototype.videoTracks
  22732. */
  22733. /**
  22734. * Get the {@link AudioTrackList}
  22735. *
  22736. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
  22737. *
  22738. * @return {AudioTrackList}
  22739. * the current audio track list
  22740. *
  22741. * @method Player.prototype.audioTracks
  22742. */
  22743. /**
  22744. * Get the {@link TextTrackList}
  22745. *
  22746. * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
  22747. *
  22748. * @return {TextTrackList}
  22749. * the current text track list
  22750. *
  22751. * @method Player.prototype.textTracks
  22752. */
  22753. /**
  22754. * Get the remote {@link TextTrackList}
  22755. *
  22756. * @return {TextTrackList}
  22757. * The current remote text track list
  22758. *
  22759. * @method Player.prototype.remoteTextTracks
  22760. */
  22761. /**
  22762. * Get the remote {@link HtmlTrackElementList} tracks.
  22763. *
  22764. * @return {HtmlTrackElementList}
  22765. * The current remote text track element list
  22766. *
  22767. * @method Player.prototype.remoteTextTrackEls
  22768. */
  22769. ALL.names.forEach(function (name) {
  22770. const props = ALL[name];
  22771. Player.prototype[props.getterName] = function () {
  22772. if (this.tech_) {
  22773. return this.tech_[props.getterName]();
  22774. }
  22775. // if we have not yet loadTech_, we create {video,audio,text}Tracks_
  22776. // these will be passed to the tech during loading
  22777. this[props.privateName] = this[props.privateName] || new props.ListClass();
  22778. return this[props.privateName];
  22779. };
  22780. });
  22781. /**
  22782. * Get or set the `Player`'s crossorigin option. For the HTML5 player, this
  22783. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  22784. * behavior.
  22785. *
  22786. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  22787. *
  22788. * @param {string} [value]
  22789. * The value to set the `Player`'s crossorigin to. If an argument is
  22790. * given, must be one of `anonymous` or `use-credentials`.
  22791. *
  22792. * @return {string|undefined}
  22793. * - The current crossorigin value of the `Player` when getting.
  22794. * - undefined when setting
  22795. */
  22796. Player.prototype.crossorigin = Player.prototype.crossOrigin;
  22797. /**
  22798. * Global enumeration of players.
  22799. *
  22800. * The keys are the player IDs and the values are either the {@link Player}
  22801. * instance or `null` for disposed players.
  22802. *
  22803. * @type {Object}
  22804. */
  22805. Player.players = {};
  22806. const navigator = window$1.navigator;
  22807. /*
  22808. * Player instance options, surfaced using options
  22809. * options = Player.prototype.options_
  22810. * Make changes in options, not here.
  22811. *
  22812. * @type {Object}
  22813. * @private
  22814. */
  22815. Player.prototype.options_ = {
  22816. // Default order of fallback technology
  22817. techOrder: Tech.defaultTechOrder_,
  22818. html5: {},
  22819. // enable sourceset by default
  22820. enableSourceset: true,
  22821. // default inactivity timeout
  22822. inactivityTimeout: 2000,
  22823. // default playback rates
  22824. playbackRates: [],
  22825. // Add playback rate selection by adding rates
  22826. // 'playbackRates': [0.5, 1, 1.5, 2],
  22827. liveui: false,
  22828. // Included control sets
  22829. children: ['mediaLoader', 'posterImage', 'titleBar', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'],
  22830. language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',
  22831. // locales and their language translations
  22832. languages: {},
  22833. // Default message to show when a video cannot be played.
  22834. notSupportedMessage: 'No compatible source was found for this media.',
  22835. normalizeAutoplay: false,
  22836. fullscreen: {
  22837. options: {
  22838. navigationUI: 'hide'
  22839. }
  22840. },
  22841. breakpoints: {},
  22842. responsive: false,
  22843. audioOnlyMode: false,
  22844. audioPosterMode: false
  22845. };
  22846. [
  22847. /**
  22848. * Returns whether or not the player is in the "ended" state.
  22849. *
  22850. * @return {Boolean} True if the player is in the ended state, false if not.
  22851. * @method Player#ended
  22852. */
  22853. 'ended',
  22854. /**
  22855. * Returns whether or not the player is in the "seeking" state.
  22856. *
  22857. * @return {Boolean} True if the player is in the seeking state, false if not.
  22858. * @method Player#seeking
  22859. */
  22860. 'seeking',
  22861. /**
  22862. * Returns the TimeRanges of the media that are currently available
  22863. * for seeking to.
  22864. *
  22865. * @return {TimeRanges} the seekable intervals of the media timeline
  22866. * @method Player#seekable
  22867. */
  22868. 'seekable',
  22869. /**
  22870. * Returns the current state of network activity for the element, from
  22871. * the codes in the list below.
  22872. * - NETWORK_EMPTY (numeric value 0)
  22873. * The element has not yet been initialised. All attributes are in
  22874. * their initial states.
  22875. * - NETWORK_IDLE (numeric value 1)
  22876. * The element's resource selection algorithm is active and has
  22877. * selected a resource, but it is not actually using the network at
  22878. * this time.
  22879. * - NETWORK_LOADING (numeric value 2)
  22880. * The user agent is actively trying to download data.
  22881. * - NETWORK_NO_SOURCE (numeric value 3)
  22882. * The element's resource selection algorithm is active, but it has
  22883. * not yet found a resource to use.
  22884. *
  22885. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
  22886. * @return {number} the current network activity state
  22887. * @method Player#networkState
  22888. */
  22889. 'networkState',
  22890. /**
  22891. * Returns a value that expresses the current state of the element
  22892. * with respect to rendering the current playback position, from the
  22893. * codes in the list below.
  22894. * - HAVE_NOTHING (numeric value 0)
  22895. * No information regarding the media resource is available.
  22896. * - HAVE_METADATA (numeric value 1)
  22897. * Enough of the resource has been obtained that the duration of the
  22898. * resource is available.
  22899. * - HAVE_CURRENT_DATA (numeric value 2)
  22900. * Data for the immediate current playback position is available.
  22901. * - HAVE_FUTURE_DATA (numeric value 3)
  22902. * Data for the immediate current playback position is available, as
  22903. * well as enough data for the user agent to advance the current
  22904. * playback position in the direction of playback.
  22905. * - HAVE_ENOUGH_DATA (numeric value 4)
  22906. * The user agent estimates that enough data is available for
  22907. * playback to proceed uninterrupted.
  22908. *
  22909. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
  22910. * @return {number} the current playback rendering state
  22911. * @method Player#readyState
  22912. */
  22913. 'readyState'].forEach(function (fn) {
  22914. Player.prototype[fn] = function () {
  22915. return this.techGet_(fn);
  22916. };
  22917. });
  22918. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  22919. Player.prototype[`handleTech${toTitleCase$1(event)}_`] = function () {
  22920. return this.trigger(event);
  22921. };
  22922. });
  22923. /**
  22924. * Fired when the player has initial duration and dimension information
  22925. *
  22926. * @event Player#loadedmetadata
  22927. * @type {Event}
  22928. */
  22929. /**
  22930. * Fired when the player has downloaded data at the current playback position
  22931. *
  22932. * @event Player#loadeddata
  22933. * @type {Event}
  22934. */
  22935. /**
  22936. * Fired when the current playback position has changed *
  22937. * During playback this is fired every 15-250 milliseconds, depending on the
  22938. * playback technology in use.
  22939. *
  22940. * @event Player#timeupdate
  22941. * @type {Event}
  22942. */
  22943. /**
  22944. * Fired when the volume changes
  22945. *
  22946. * @event Player#volumechange
  22947. * @type {Event}
  22948. */
  22949. /**
  22950. * Reports whether or not a player has a plugin available.
  22951. *
  22952. * This does not report whether or not the plugin has ever been initialized
  22953. * on this player. For that, [usingPlugin]{@link Player#usingPlugin}.
  22954. *
  22955. * @method Player#hasPlugin
  22956. * @param {string} name
  22957. * The name of a plugin.
  22958. *
  22959. * @return {boolean}
  22960. * Whether or not this player has the requested plugin available.
  22961. */
  22962. /**
  22963. * Reports whether or not a player is using a plugin by name.
  22964. *
  22965. * For basic plugins, this only reports whether the plugin has _ever_ been
  22966. * initialized on this player.
  22967. *
  22968. * @method Player#usingPlugin
  22969. * @param {string} name
  22970. * The name of a plugin.
  22971. *
  22972. * @return {boolean}
  22973. * Whether or not this player is using the requested plugin.
  22974. */
  22975. Component$1.registerComponent('Player', Player);
  22976. /**
  22977. * @file plugin.js
  22978. */
  22979. /**
  22980. * The base plugin name.
  22981. *
  22982. * @private
  22983. * @constant
  22984. * @type {string}
  22985. */
  22986. const BASE_PLUGIN_NAME = 'plugin';
  22987. /**
  22988. * The key on which a player's active plugins cache is stored.
  22989. *
  22990. * @private
  22991. * @constant
  22992. * @type {string}
  22993. */
  22994. const PLUGIN_CACHE_KEY = 'activePlugins_';
  22995. /**
  22996. * Stores registered plugins in a private space.
  22997. *
  22998. * @private
  22999. * @type {Object}
  23000. */
  23001. const pluginStorage = {};
  23002. /**
  23003. * Reports whether or not a plugin has been registered.
  23004. *
  23005. * @private
  23006. * @param {string} name
  23007. * The name of a plugin.
  23008. *
  23009. * @return {boolean}
  23010. * Whether or not the plugin has been registered.
  23011. */
  23012. const pluginExists = name => pluginStorage.hasOwnProperty(name);
  23013. /**
  23014. * Get a single registered plugin by name.
  23015. *
  23016. * @private
  23017. * @param {string} name
  23018. * The name of a plugin.
  23019. *
  23020. * @return {typeof Plugin|Function|undefined}
  23021. * The plugin (or undefined).
  23022. */
  23023. const getPlugin = name => pluginExists(name) ? pluginStorage[name] : undefined;
  23024. /**
  23025. * Marks a plugin as "active" on a player.
  23026. *
  23027. * Also, ensures that the player has an object for tracking active plugins.
  23028. *
  23029. * @private
  23030. * @param {Player} player
  23031. * A Video.js player instance.
  23032. *
  23033. * @param {string} name
  23034. * The name of a plugin.
  23035. */
  23036. const markPluginAsActive = (player, name) => {
  23037. player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
  23038. player[PLUGIN_CACHE_KEY][name] = true;
  23039. };
  23040. /**
  23041. * Triggers a pair of plugin setup events.
  23042. *
  23043. * @private
  23044. * @param {Player} player
  23045. * A Video.js player instance.
  23046. *
  23047. * @param {Plugin~PluginEventHash} hash
  23048. * A plugin event hash.
  23049. *
  23050. * @param {boolean} [before]
  23051. * If true, prefixes the event name with "before". In other words,
  23052. * use this to trigger "beforepluginsetup" instead of "pluginsetup".
  23053. */
  23054. const triggerSetupEvent = (player, hash, before) => {
  23055. const eventName = (before ? 'before' : '') + 'pluginsetup';
  23056. player.trigger(eventName, hash);
  23057. player.trigger(eventName + ':' + hash.name, hash);
  23058. };
  23059. /**
  23060. * Takes a basic plugin function and returns a wrapper function which marks
  23061. * on the player that the plugin has been activated.
  23062. *
  23063. * @private
  23064. * @param {string} name
  23065. * The name of the plugin.
  23066. *
  23067. * @param {Function} plugin
  23068. * The basic plugin.
  23069. *
  23070. * @return {Function}
  23071. * A wrapper function for the given plugin.
  23072. */
  23073. const createBasicPlugin = function (name, plugin) {
  23074. const basicPluginWrapper = function () {
  23075. // We trigger the "beforepluginsetup" and "pluginsetup" events on the player
  23076. // regardless, but we want the hash to be consistent with the hash provided
  23077. // for advanced plugins.
  23078. //
  23079. // The only potentially counter-intuitive thing here is the `instance` in
  23080. // the "pluginsetup" event is the value returned by the `plugin` function.
  23081. triggerSetupEvent(this, {
  23082. name,
  23083. plugin,
  23084. instance: null
  23085. }, true);
  23086. const instance = plugin.apply(this, arguments);
  23087. markPluginAsActive(this, name);
  23088. triggerSetupEvent(this, {
  23089. name,
  23090. plugin,
  23091. instance
  23092. });
  23093. return instance;
  23094. };
  23095. Object.keys(plugin).forEach(function (prop) {
  23096. basicPluginWrapper[prop] = plugin[prop];
  23097. });
  23098. return basicPluginWrapper;
  23099. };
  23100. /**
  23101. * Takes a plugin sub-class and returns a factory function for generating
  23102. * instances of it.
  23103. *
  23104. * This factory function will replace itself with an instance of the requested
  23105. * sub-class of Plugin.
  23106. *
  23107. * @private
  23108. * @param {string} name
  23109. * The name of the plugin.
  23110. *
  23111. * @param {Plugin} PluginSubClass
  23112. * The advanced plugin.
  23113. *
  23114. * @return {Function}
  23115. */
  23116. const createPluginFactory = (name, PluginSubClass) => {
  23117. // Add a `name` property to the plugin prototype so that each plugin can
  23118. // refer to itself by name.
  23119. PluginSubClass.prototype.name = name;
  23120. return function (...args) {
  23121. triggerSetupEvent(this, {
  23122. name,
  23123. plugin: PluginSubClass,
  23124. instance: null
  23125. }, true);
  23126. const instance = new PluginSubClass(...[this, ...args]);
  23127. // The plugin is replaced by a function that returns the current instance.
  23128. this[name] = () => instance;
  23129. triggerSetupEvent(this, instance.getEventHash());
  23130. return instance;
  23131. };
  23132. };
  23133. /**
  23134. * Parent class for all advanced plugins.
  23135. *
  23136. * @mixes module:evented~EventedMixin
  23137. * @mixes module:stateful~StatefulMixin
  23138. * @fires Player#beforepluginsetup
  23139. * @fires Player#beforepluginsetup:$name
  23140. * @fires Player#pluginsetup
  23141. * @fires Player#pluginsetup:$name
  23142. * @listens Player#dispose
  23143. * @throws {Error}
  23144. * If attempting to instantiate the base {@link Plugin} class
  23145. * directly instead of via a sub-class.
  23146. */
  23147. class Plugin {
  23148. /**
  23149. * Creates an instance of this class.
  23150. *
  23151. * Sub-classes should call `super` to ensure plugins are properly initialized.
  23152. *
  23153. * @param {Player} player
  23154. * A Video.js player instance.
  23155. */
  23156. constructor(player) {
  23157. if (this.constructor === Plugin) {
  23158. throw new Error('Plugin must be sub-classed; not directly instantiated.');
  23159. }
  23160. this.player = player;
  23161. if (!this.log) {
  23162. this.log = this.player.log.createLogger(this.name);
  23163. }
  23164. // Make this object evented, but remove the added `trigger` method so we
  23165. // use the prototype version instead.
  23166. evented(this);
  23167. delete this.trigger;
  23168. stateful(this, this.constructor.defaultState);
  23169. markPluginAsActive(player, this.name);
  23170. // Auto-bind the dispose method so we can use it as a listener and unbind
  23171. // it later easily.
  23172. this.dispose = this.dispose.bind(this);
  23173. // If the player is disposed, dispose the plugin.
  23174. player.on('dispose', this.dispose);
  23175. }
  23176. /**
  23177. * Get the version of the plugin that was set on <pluginName>.VERSION
  23178. */
  23179. version() {
  23180. return this.constructor.VERSION;
  23181. }
  23182. /**
  23183. * Each event triggered by plugins includes a hash of additional data with
  23184. * conventional properties.
  23185. *
  23186. * This returns that object or mutates an existing hash.
  23187. *
  23188. * @param {Object} [hash={}]
  23189. * An object to be used as event an event hash.
  23190. *
  23191. * @return {Plugin~PluginEventHash}
  23192. * An event hash object with provided properties mixed-in.
  23193. */
  23194. getEventHash(hash = {}) {
  23195. hash.name = this.name;
  23196. hash.plugin = this.constructor;
  23197. hash.instance = this;
  23198. return hash;
  23199. }
  23200. /**
  23201. * Triggers an event on the plugin object and overrides
  23202. * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.
  23203. *
  23204. * @param {string|Object} event
  23205. * An event type or an object with a type property.
  23206. *
  23207. * @param {Object} [hash={}]
  23208. * Additional data hash to merge with a
  23209. * {@link Plugin~PluginEventHash|PluginEventHash}.
  23210. *
  23211. * @return {boolean}
  23212. * Whether or not default was prevented.
  23213. */
  23214. trigger(event, hash = {}) {
  23215. return trigger(this.eventBusEl_, event, this.getEventHash(hash));
  23216. }
  23217. /**
  23218. * Handles "statechanged" events on the plugin. No-op by default, override by
  23219. * subclassing.
  23220. *
  23221. * @abstract
  23222. * @param {Event} e
  23223. * An event object provided by a "statechanged" event.
  23224. *
  23225. * @param {Object} e.changes
  23226. * An object describing changes that occurred with the "statechanged"
  23227. * event.
  23228. */
  23229. handleStateChanged(e) {}
  23230. /**
  23231. * Disposes a plugin.
  23232. *
  23233. * Subclasses can override this if they want, but for the sake of safety,
  23234. * it's probably best to subscribe the "dispose" event.
  23235. *
  23236. * @fires Plugin#dispose
  23237. */
  23238. dispose() {
  23239. const {
  23240. name,
  23241. player
  23242. } = this;
  23243. /**
  23244. * Signals that a advanced plugin is about to be disposed.
  23245. *
  23246. * @event Plugin#dispose
  23247. * @type {Event}
  23248. */
  23249. this.trigger('dispose');
  23250. this.off();
  23251. player.off('dispose', this.dispose);
  23252. // Eliminate any possible sources of leaking memory by clearing up
  23253. // references between the player and the plugin instance and nulling out
  23254. // the plugin's state and replacing methods with a function that throws.
  23255. player[PLUGIN_CACHE_KEY][name] = false;
  23256. this.player = this.state = null;
  23257. // Finally, replace the plugin name on the player with a new factory
  23258. // function, so that the plugin is ready to be set up again.
  23259. player[name] = createPluginFactory(name, pluginStorage[name]);
  23260. }
  23261. /**
  23262. * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).
  23263. *
  23264. * @param {string|Function} plugin
  23265. * If a string, matches the name of a plugin. If a function, will be
  23266. * tested directly.
  23267. *
  23268. * @return {boolean}
  23269. * Whether or not a plugin is a basic plugin.
  23270. */
  23271. static isBasic(plugin) {
  23272. const p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;
  23273. return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);
  23274. }
  23275. /**
  23276. * Register a Video.js plugin.
  23277. *
  23278. * @param {string} name
  23279. * The name of the plugin to be registered. Must be a string and
  23280. * must not match an existing plugin or a method on the `Player`
  23281. * prototype.
  23282. *
  23283. * @param {typeof Plugin|Function} plugin
  23284. * A sub-class of `Plugin` or a function for basic plugins.
  23285. *
  23286. * @return {typeof Plugin|Function}
  23287. * For advanced plugins, a factory function for that plugin. For
  23288. * basic plugins, a wrapper function that initializes the plugin.
  23289. */
  23290. static registerPlugin(name, plugin) {
  23291. if (typeof name !== 'string') {
  23292. throw new Error(`Illegal plugin name, "${name}", must be a string, was ${typeof name}.`);
  23293. }
  23294. if (pluginExists(name)) {
  23295. log$1.warn(`A plugin named "${name}" already exists. You may want to avoid re-registering plugins!`);
  23296. } else if (Player.prototype.hasOwnProperty(name)) {
  23297. throw new Error(`Illegal plugin name, "${name}", cannot share a name with an existing player method!`);
  23298. }
  23299. if (typeof plugin !== 'function') {
  23300. throw new Error(`Illegal plugin for "${name}", must be a function, was ${typeof plugin}.`);
  23301. }
  23302. pluginStorage[name] = plugin;
  23303. // Add a player prototype method for all sub-classed plugins (but not for
  23304. // the base Plugin class).
  23305. if (name !== BASE_PLUGIN_NAME) {
  23306. if (Plugin.isBasic(plugin)) {
  23307. Player.prototype[name] = createBasicPlugin(name, plugin);
  23308. } else {
  23309. Player.prototype[name] = createPluginFactory(name, plugin);
  23310. }
  23311. }
  23312. return plugin;
  23313. }
  23314. /**
  23315. * De-register a Video.js plugin.
  23316. *
  23317. * @param {string} name
  23318. * The name of the plugin to be de-registered. Must be a string that
  23319. * matches an existing plugin.
  23320. *
  23321. * @throws {Error}
  23322. * If an attempt is made to de-register the base plugin.
  23323. */
  23324. static deregisterPlugin(name) {
  23325. if (name === BASE_PLUGIN_NAME) {
  23326. throw new Error('Cannot de-register base plugin.');
  23327. }
  23328. if (pluginExists(name)) {
  23329. delete pluginStorage[name];
  23330. delete Player.prototype[name];
  23331. }
  23332. }
  23333. /**
  23334. * Gets an object containing multiple Video.js plugins.
  23335. *
  23336. * @param {Array} [names]
  23337. * If provided, should be an array of plugin names. Defaults to _all_
  23338. * plugin names.
  23339. *
  23340. * @return {Object|undefined}
  23341. * An object containing plugin(s) associated with their name(s) or
  23342. * `undefined` if no matching plugins exist).
  23343. */
  23344. static getPlugins(names = Object.keys(pluginStorage)) {
  23345. let result;
  23346. names.forEach(name => {
  23347. const plugin = getPlugin(name);
  23348. if (plugin) {
  23349. result = result || {};
  23350. result[name] = plugin;
  23351. }
  23352. });
  23353. return result;
  23354. }
  23355. /**
  23356. * Gets a plugin's version, if available
  23357. *
  23358. * @param {string} name
  23359. * The name of a plugin.
  23360. *
  23361. * @return {string}
  23362. * The plugin's version or an empty string.
  23363. */
  23364. static getPluginVersion(name) {
  23365. const plugin = getPlugin(name);
  23366. return plugin && plugin.VERSION || '';
  23367. }
  23368. }
  23369. /**
  23370. * Gets a plugin by name if it exists.
  23371. *
  23372. * @static
  23373. * @method getPlugin
  23374. * @memberOf Plugin
  23375. * @param {string} name
  23376. * The name of a plugin.
  23377. *
  23378. * @returns {typeof Plugin|Function|undefined}
  23379. * The plugin (or `undefined`).
  23380. */
  23381. Plugin.getPlugin = getPlugin;
  23382. /**
  23383. * The name of the base plugin class as it is registered.
  23384. *
  23385. * @type {string}
  23386. */
  23387. Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
  23388. Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
  23389. /**
  23390. * Documented in player.js
  23391. *
  23392. * @ignore
  23393. */
  23394. Player.prototype.usingPlugin = function (name) {
  23395. return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
  23396. };
  23397. /**
  23398. * Documented in player.js
  23399. *
  23400. * @ignore
  23401. */
  23402. Player.prototype.hasPlugin = function (name) {
  23403. return !!pluginExists(name);
  23404. };
  23405. /**
  23406. * Signals that a plugin is about to be set up on a player.
  23407. *
  23408. * @event Player#beforepluginsetup
  23409. * @type {Plugin~PluginEventHash}
  23410. */
  23411. /**
  23412. * Signals that a plugin is about to be set up on a player - by name. The name
  23413. * is the name of the plugin.
  23414. *
  23415. * @event Player#beforepluginsetup:$name
  23416. * @type {Plugin~PluginEventHash}
  23417. */
  23418. /**
  23419. * Signals that a plugin has just been set up on a player.
  23420. *
  23421. * @event Player#pluginsetup
  23422. * @type {Plugin~PluginEventHash}
  23423. */
  23424. /**
  23425. * Signals that a plugin has just been set up on a player - by name. The name
  23426. * is the name of the plugin.
  23427. *
  23428. * @event Player#pluginsetup:$name
  23429. * @type {Plugin~PluginEventHash}
  23430. */
  23431. /**
  23432. * @typedef {Object} Plugin~PluginEventHash
  23433. *
  23434. * @property {string} instance
  23435. * For basic plugins, the return value of the plugin function. For
  23436. * advanced plugins, the plugin instance on which the event is fired.
  23437. *
  23438. * @property {string} name
  23439. * The name of the plugin.
  23440. *
  23441. * @property {string} plugin
  23442. * For basic plugins, the plugin function. For advanced plugins, the
  23443. * plugin class/constructor.
  23444. */
  23445. /**
  23446. * @file deprecate.js
  23447. * @module deprecate
  23448. */
  23449. /**
  23450. * Decorate a function with a deprecation message the first time it is called.
  23451. *
  23452. * @param {string} message
  23453. * A deprecation message to log the first time the returned function
  23454. * is called.
  23455. *
  23456. * @param {Function} fn
  23457. * The function to be deprecated.
  23458. *
  23459. * @return {Function}
  23460. * A wrapper function that will log a deprecation warning the first
  23461. * time it is called. The return value will be the return value of
  23462. * the wrapped function.
  23463. */
  23464. function deprecate(message, fn) {
  23465. let warned = false;
  23466. return function (...args) {
  23467. if (!warned) {
  23468. log$1.warn(message);
  23469. }
  23470. warned = true;
  23471. return fn.apply(this, args);
  23472. };
  23473. }
  23474. /**
  23475. * Internal function used to mark a function as deprecated in the next major
  23476. * version with consistent messaging.
  23477. *
  23478. * @param {number} major The major version where it will be removed
  23479. * @param {string} oldName The old function name
  23480. * @param {string} newName The new function name
  23481. * @param {Function} fn The function to deprecate
  23482. * @return {Function} The decorated function
  23483. */
  23484. function deprecateForMajor(major, oldName, newName, fn) {
  23485. return deprecate(`${oldName} is deprecated and will be removed in ${major}.0; please use ${newName} instead.`, fn);
  23486. }
  23487. /**
  23488. * @file video.js
  23489. * @module videojs
  23490. */
  23491. /**
  23492. * Normalize an `id` value by trimming off a leading `#`
  23493. *
  23494. * @private
  23495. * @param {string} id
  23496. * A string, maybe with a leading `#`.
  23497. *
  23498. * @return {string}
  23499. * The string, without any leading `#`.
  23500. */
  23501. const normalizeId = id => id.indexOf('#') === 0 ? id.slice(1) : id;
  23502. /**
  23503. * A callback that is called when a component is ready. Does not have any
  23504. * parameters and any callback value will be ignored. See: {@link Component~ReadyCallback}
  23505. *
  23506. * @callback ReadyCallback
  23507. */
  23508. /**
  23509. * The `videojs()` function doubles as the main function for users to create a
  23510. * {@link Player} instance as well as the main library namespace.
  23511. *
  23512. * It can also be used as a getter for a pre-existing {@link Player} instance.
  23513. * However, we _strongly_ recommend using `videojs.getPlayer()` for this
  23514. * purpose because it avoids any potential for unintended initialization.
  23515. *
  23516. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  23517. * of our JSDoc template, we cannot properly document this as both a function
  23518. * and a namespace, so its function signature is documented here.
  23519. *
  23520. * #### Arguments
  23521. * ##### id
  23522. * string|Element, **required**
  23523. *
  23524. * Video element or video element ID.
  23525. *
  23526. * ##### options
  23527. * Object, optional
  23528. *
  23529. * Options object for providing settings.
  23530. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  23531. *
  23532. * ##### ready
  23533. * {@link Component~ReadyCallback}, optional
  23534. *
  23535. * A function to be called when the {@link Player} and {@link Tech} are ready.
  23536. *
  23537. * #### Return Value
  23538. *
  23539. * The `videojs()` function returns a {@link Player} instance.
  23540. *
  23541. * @namespace
  23542. *
  23543. * @borrows AudioTrack as AudioTrack
  23544. * @borrows Component.getComponent as getComponent
  23545. * @borrows module:events.on as on
  23546. * @borrows module:events.one as one
  23547. * @borrows module:events.off as off
  23548. * @borrows module:events.trigger as trigger
  23549. * @borrows EventTarget as EventTarget
  23550. * @borrows module:middleware.use as use
  23551. * @borrows Player.players as players
  23552. * @borrows Plugin.registerPlugin as registerPlugin
  23553. * @borrows Plugin.deregisterPlugin as deregisterPlugin
  23554. * @borrows Plugin.getPlugins as getPlugins
  23555. * @borrows Plugin.getPlugin as getPlugin
  23556. * @borrows Plugin.getPluginVersion as getPluginVersion
  23557. * @borrows Tech.getTech as getTech
  23558. * @borrows Tech.registerTech as registerTech
  23559. * @borrows TextTrack as TextTrack
  23560. * @borrows VideoTrack as VideoTrack
  23561. *
  23562. * @param {string|Element} id
  23563. * Video element or video element ID.
  23564. *
  23565. * @param {Object} [options]
  23566. * Options object for providing settings.
  23567. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  23568. *
  23569. * @param {ReadyCallback} [ready]
  23570. * A function to be called when the {@link Player} and {@link Tech} are
  23571. * ready.
  23572. *
  23573. * @return {Player}
  23574. * The `videojs()` function returns a {@link Player|Player} instance.
  23575. */
  23576. function videojs(id, options, ready) {
  23577. let player = videojs.getPlayer(id);
  23578. if (player) {
  23579. if (options) {
  23580. log$1.warn(`Player "${id}" is already initialised. Options will not be applied.`);
  23581. }
  23582. if (ready) {
  23583. player.ready(ready);
  23584. }
  23585. return player;
  23586. }
  23587. const el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;
  23588. if (!isEl(el)) {
  23589. throw new TypeError('The element or ID supplied is not valid. (videojs)');
  23590. }
  23591. // document.body.contains(el) will only check if el is contained within that one document.
  23592. // This causes problems for elements in iframes.
  23593. // Instead, use the element's ownerDocument instead of the global document.
  23594. // This will make sure that the element is indeed in the dom of that document.
  23595. // Additionally, check that the document in question has a default view.
  23596. // If the document is no longer attached to the dom, the defaultView of the document will be null.
  23597. if (!el.ownerDocument.defaultView || !el.ownerDocument.body.contains(el)) {
  23598. log$1.warn('The element supplied is not included in the DOM');
  23599. }
  23600. options = options || {};
  23601. // Store a copy of the el before modification, if it is to be restored in destroy()
  23602. // If div ingest, store the parent div
  23603. if (options.restoreEl === true) {
  23604. options.restoreEl = (el.parentNode && el.parentNode.hasAttribute('data-vjs-player') ? el.parentNode : el).cloneNode(true);
  23605. }
  23606. hooks('beforesetup').forEach(hookFunction => {
  23607. const opts = hookFunction(el, merge$1(options));
  23608. if (!isObject(opts) || Array.isArray(opts)) {
  23609. log$1.error('please return an object in beforesetup hooks');
  23610. return;
  23611. }
  23612. options = merge$1(options, opts);
  23613. });
  23614. // We get the current "Player" component here in case an integration has
  23615. // replaced it with a custom player.
  23616. const PlayerComponent = Component$1.getComponent('Player');
  23617. player = new PlayerComponent(el, options, ready);
  23618. hooks('setup').forEach(hookFunction => hookFunction(player));
  23619. return player;
  23620. }
  23621. videojs.hooks_ = hooks_;
  23622. videojs.hooks = hooks;
  23623. videojs.hook = hook;
  23624. videojs.hookOnce = hookOnce;
  23625. videojs.removeHook = removeHook;
  23626. // Add default styles
  23627. if (window$1.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
  23628. let style = $('.vjs-styles-defaults');
  23629. if (!style) {
  23630. style = createStyleElement('vjs-styles-defaults');
  23631. const head = $('head');
  23632. if (head) {
  23633. head.insertBefore(style, head.firstChild);
  23634. }
  23635. setTextContent(style, `
  23636. .video-js {
  23637. width: 300px;
  23638. height: 150px;
  23639. }
  23640. .vjs-fluid:not(.vjs-audio-only-mode) {
  23641. padding-top: 56.25%
  23642. }
  23643. `);
  23644. }
  23645. }
  23646. // Run Auto-load players
  23647. // You have to wait at least once in case this script is loaded after your
  23648. // video in the DOM (weird behavior only with minified version)
  23649. autoSetupTimeout(1, videojs);
  23650. /**
  23651. * Current Video.js version. Follows [semantic versioning](https://semver.org/).
  23652. *
  23653. * @type {string}
  23654. */
  23655. videojs.VERSION = version$6;
  23656. /**
  23657. * The global options object. These are the settings that take effect
  23658. * if no overrides are specified when the player is created.
  23659. *
  23660. * @type {Object}
  23661. */
  23662. videojs.options = Player.prototype.options_;
  23663. /**
  23664. * Get an object with the currently created players, keyed by player ID
  23665. *
  23666. * @return {Object}
  23667. * The created players
  23668. */
  23669. videojs.getPlayers = () => Player.players;
  23670. /**
  23671. * Get a single player based on an ID or DOM element.
  23672. *
  23673. * This is useful if you want to check if an element or ID has an associated
  23674. * Video.js player, but not create one if it doesn't.
  23675. *
  23676. * @param {string|Element} id
  23677. * An HTML element - `<video>`, `<audio>`, or `<video-js>` -
  23678. * or a string matching the `id` of such an element.
  23679. *
  23680. * @return {Player|undefined}
  23681. * A player instance or `undefined` if there is no player instance
  23682. * matching the argument.
  23683. */
  23684. videojs.getPlayer = id => {
  23685. const players = Player.players;
  23686. let tag;
  23687. if (typeof id === 'string') {
  23688. const nId = normalizeId(id);
  23689. const player = players[nId];
  23690. if (player) {
  23691. return player;
  23692. }
  23693. tag = $('#' + nId);
  23694. } else {
  23695. tag = id;
  23696. }
  23697. if (isEl(tag)) {
  23698. const {
  23699. player,
  23700. playerId
  23701. } = tag;
  23702. // Element may have a `player` property referring to an already created
  23703. // player instance. If so, return that.
  23704. if (player || players[playerId]) {
  23705. return player || players[playerId];
  23706. }
  23707. }
  23708. };
  23709. /**
  23710. * Returns an array of all current players.
  23711. *
  23712. * @return {Array}
  23713. * An array of all players. The array will be in the order that
  23714. * `Object.keys` provides, which could potentially vary between
  23715. * JavaScript engines.
  23716. *
  23717. */
  23718. videojs.getAllPlayers = () =>
  23719. // Disposed players leave a key with a `null` value, so we need to make sure
  23720. // we filter those out.
  23721. Object.keys(Player.players).map(k => Player.players[k]).filter(Boolean);
  23722. videojs.players = Player.players;
  23723. videojs.getComponent = Component$1.getComponent;
  23724. /**
  23725. * Register a component so it can referred to by name. Used when adding to other
  23726. * components, either through addChild `component.addChild('myComponent')` or through
  23727. * default children options `{ children: ['myComponent'] }`.
  23728. *
  23729. * > NOTE: You could also just initialize the component before adding.
  23730. * `component.addChild(new MyComponent());`
  23731. *
  23732. * @param {string} name
  23733. * The class name of the component
  23734. *
  23735. * @param {Component} comp
  23736. * The component class
  23737. *
  23738. * @return {Component}
  23739. * The newly registered component
  23740. */
  23741. videojs.registerComponent = (name, comp) => {
  23742. if (Tech.isTech(comp)) {
  23743. log$1.warn(`The ${name} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`);
  23744. }
  23745. Component$1.registerComponent.call(Component$1, name, comp);
  23746. };
  23747. videojs.getTech = Tech.getTech;
  23748. videojs.registerTech = Tech.registerTech;
  23749. videojs.use = use;
  23750. /**
  23751. * An object that can be returned by a middleware to signify
  23752. * that the middleware is being terminated.
  23753. *
  23754. * @type {object}
  23755. * @property {object} middleware.TERMINATOR
  23756. */
  23757. Object.defineProperty(videojs, 'middleware', {
  23758. value: {},
  23759. writeable: false,
  23760. enumerable: true
  23761. });
  23762. Object.defineProperty(videojs.middleware, 'TERMINATOR', {
  23763. value: TERMINATOR,
  23764. writeable: false,
  23765. enumerable: true
  23766. });
  23767. /**
  23768. * A reference to the {@link module:browser|browser utility module} as an object.
  23769. *
  23770. * @type {Object}
  23771. * @see {@link module:browser|browser}
  23772. */
  23773. videojs.browser = browser;
  23774. /**
  23775. * A reference to the {@link module:obj|obj utility module} as an object.
  23776. *
  23777. * @type {Object}
  23778. * @see {@link module:obj|obj}
  23779. */
  23780. videojs.obj = Obj;
  23781. /**
  23782. * Deprecated reference to the {@link module:obj.merge|merge function}
  23783. *
  23784. * @type {Function}
  23785. * @see {@link module:obj.merge|merge}
  23786. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.merge instead.
  23787. */
  23788. videojs.mergeOptions = deprecateForMajor(9, 'videojs.mergeOptions', 'videojs.obj.merge', merge$1);
  23789. /**
  23790. * Deprecated reference to the {@link module:obj.defineLazyProperty|defineLazyProperty function}
  23791. *
  23792. * @type {Function}
  23793. * @see {@link module:obj.defineLazyProperty|defineLazyProperty}
  23794. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.defineLazyProperty instead.
  23795. */
  23796. videojs.defineLazyProperty = deprecateForMajor(9, 'videojs.defineLazyProperty', 'videojs.obj.defineLazyProperty', defineLazyProperty);
  23797. /**
  23798. * Deprecated reference to the {@link module:fn.bind_|fn.bind_ function}
  23799. *
  23800. * @type {Function}
  23801. * @see {@link module:fn.bind_|fn.bind_}
  23802. * @deprecated Deprecated and will be removed in 9.0. Please use native Function.prototype.bind instead.
  23803. */
  23804. videojs.bind = deprecateForMajor(9, 'videojs.bind', 'native Function.prototype.bind', bind_);
  23805. videojs.registerPlugin = Plugin.registerPlugin;
  23806. videojs.deregisterPlugin = Plugin.deregisterPlugin;
  23807. /**
  23808. * Deprecated method to register a plugin with Video.js
  23809. *
  23810. * @deprecated Deprecated and will be removed in 9.0. Use videojs.registerPlugin() instead.
  23811. *
  23812. * @param {string} name
  23813. * The plugin name
  23814. *
  23815. * @param {Plugin|Function} plugin
  23816. * The plugin sub-class or function
  23817. */
  23818. videojs.plugin = (name, plugin) => {
  23819. log$1.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');
  23820. return Plugin.registerPlugin(name, plugin);
  23821. };
  23822. videojs.getPlugins = Plugin.getPlugins;
  23823. videojs.getPlugin = Plugin.getPlugin;
  23824. videojs.getPluginVersion = Plugin.getPluginVersion;
  23825. /**
  23826. * Adding languages so that they're available to all players.
  23827. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`
  23828. *
  23829. * @param {string} code
  23830. * The language code or dictionary property
  23831. *
  23832. * @param {Object} data
  23833. * The data values to be translated
  23834. *
  23835. * @return {Object}
  23836. * The resulting language dictionary object
  23837. */
  23838. videojs.addLanguage = function (code, data) {
  23839. code = ('' + code).toLowerCase();
  23840. videojs.options.languages = merge$1(videojs.options.languages, {
  23841. [code]: data
  23842. });
  23843. return videojs.options.languages[code];
  23844. };
  23845. /**
  23846. * A reference to the {@link module:log|log utility module} as an object.
  23847. *
  23848. * @type {Function}
  23849. * @see {@link module:log|log}
  23850. */
  23851. videojs.log = log$1;
  23852. videojs.createLogger = createLogger;
  23853. /**
  23854. * A reference to the {@link module:time|time utility module} as an object.
  23855. *
  23856. * @type {Object}
  23857. * @see {@link module:time|time}
  23858. */
  23859. videojs.time = Time;
  23860. /**
  23861. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  23862. *
  23863. * @type {Function}
  23864. * @see {@link module:time.createTimeRanges|createTimeRanges}
  23865. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  23866. */
  23867. videojs.createTimeRange = deprecateForMajor(9, 'videojs.createTimeRange', 'videojs.time.createTimeRanges', createTimeRanges$1);
  23868. /**
  23869. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  23870. *
  23871. * @type {Function}
  23872. * @see {@link module:time.createTimeRanges|createTimeRanges}
  23873. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  23874. */
  23875. videojs.createTimeRanges = deprecateForMajor(9, 'videojs.createTimeRanges', 'videojs.time.createTimeRanges', createTimeRanges$1);
  23876. /**
  23877. * Deprecated reference to the {@link module:time.formatTime|formatTime function}
  23878. *
  23879. * @type {Function}
  23880. * @see {@link module:time.formatTime|formatTime}
  23881. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.format instead.
  23882. */
  23883. videojs.formatTime = deprecateForMajor(9, 'videojs.formatTime', 'videojs.time.formatTime', formatTime);
  23884. /**
  23885. * Deprecated reference to the {@link module:time.setFormatTime|setFormatTime function}
  23886. *
  23887. * @type {Function}
  23888. * @see {@link module:time.setFormatTime|setFormatTime}
  23889. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.setFormat instead.
  23890. */
  23891. videojs.setFormatTime = deprecateForMajor(9, 'videojs.setFormatTime', 'videojs.time.setFormatTime', setFormatTime);
  23892. /**
  23893. * Deprecated reference to the {@link module:time.resetFormatTime|resetFormatTime function}
  23894. *
  23895. * @type {Function}
  23896. * @see {@link module:time.resetFormatTime|resetFormatTime}
  23897. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.resetFormat instead.
  23898. */
  23899. videojs.resetFormatTime = deprecateForMajor(9, 'videojs.resetFormatTime', 'videojs.time.resetFormatTime', resetFormatTime);
  23900. /**
  23901. * Deprecated reference to the {@link module:url.parseUrl|Url.parseUrl function}
  23902. *
  23903. * @type {Function}
  23904. * @see {@link module:url.parseUrl|parseUrl}
  23905. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.parseUrl instead.
  23906. */
  23907. videojs.parseUrl = deprecateForMajor(9, 'videojs.parseUrl', 'videojs.url.parseUrl', parseUrl);
  23908. /**
  23909. * Deprecated reference to the {@link module:url.isCrossOrigin|Url.isCrossOrigin function}
  23910. *
  23911. * @type {Function}
  23912. * @see {@link module:url.isCrossOrigin|isCrossOrigin}
  23913. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.isCrossOrigin instead.
  23914. */
  23915. videojs.isCrossOrigin = deprecateForMajor(9, 'videojs.isCrossOrigin', 'videojs.url.isCrossOrigin', isCrossOrigin);
  23916. videojs.EventTarget = EventTarget$2;
  23917. videojs.any = any;
  23918. videojs.on = on;
  23919. videojs.one = one;
  23920. videojs.off = off;
  23921. videojs.trigger = trigger;
  23922. /**
  23923. * A cross-browser XMLHttpRequest wrapper.
  23924. *
  23925. * @function
  23926. * @param {Object} options
  23927. * Settings for the request.
  23928. *
  23929. * @return {XMLHttpRequest|XDomainRequest}
  23930. * The request object.
  23931. *
  23932. * @see https://github.com/Raynos/xhr
  23933. */
  23934. videojs.xhr = XHR;
  23935. videojs.TextTrack = TextTrack;
  23936. videojs.AudioTrack = AudioTrack;
  23937. videojs.VideoTrack = VideoTrack;
  23938. ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(k => {
  23939. videojs[k] = function () {
  23940. log$1.warn(`videojs.${k}() is deprecated; use videojs.dom.${k}() instead`);
  23941. return Dom[k].apply(null, arguments);
  23942. };
  23943. });
  23944. videojs.computedStyle = deprecateForMajor(9, 'videojs.computedStyle', 'videojs.dom.computedStyle', computedStyle);
  23945. /**
  23946. * A reference to the {@link module:dom|DOM utility module} as an object.
  23947. *
  23948. * @type {Object}
  23949. * @see {@link module:dom|dom}
  23950. */
  23951. videojs.dom = Dom;
  23952. /**
  23953. * A reference to the {@link module:fn|fn utility module} as an object.
  23954. *
  23955. * @type {Object}
  23956. * @see {@link module:fn|fn}
  23957. */
  23958. videojs.fn = Fn;
  23959. /**
  23960. * A reference to the {@link module:num|num utility module} as an object.
  23961. *
  23962. * @type {Object}
  23963. * @see {@link module:num|num}
  23964. */
  23965. videojs.num = Num;
  23966. /**
  23967. * A reference to the {@link module:str|str utility module} as an object.
  23968. *
  23969. * @type {Object}
  23970. * @see {@link module:str|str}
  23971. */
  23972. videojs.str = Str;
  23973. /**
  23974. * A reference to the {@link module:url|URL utility module} as an object.
  23975. *
  23976. * @type {Object}
  23977. * @see {@link module:url|url}
  23978. */
  23979. videojs.url = Url;
  23980. /*! @name videojs-contrib-quality-levels @version 3.0.0 @license Apache-2.0 */
  23981. /**
  23982. * A single QualityLevel.
  23983. *
  23984. * interface QualityLevel {
  23985. * readonly attribute DOMString id;
  23986. * attribute DOMString label;
  23987. * readonly attribute long width;
  23988. * readonly attribute long height;
  23989. * readonly attribute long bitrate;
  23990. * attribute boolean enabled;
  23991. * };
  23992. *
  23993. * @class QualityLevel
  23994. */
  23995. class QualityLevel {
  23996. /**
  23997. * Creates a QualityLevel
  23998. *
  23999. * @param {Representation|Object} representation The representation of the quality level
  24000. * @param {string} representation.id Unique id of the QualityLevel
  24001. * @param {number=} representation.width Resolution width of the QualityLevel
  24002. * @param {number=} representation.height Resolution height of the QualityLevel
  24003. * @param {number} representation.bandwidth Bitrate of the QualityLevel
  24004. * @param {number=} representation.frameRate Frame-rate of the QualityLevel
  24005. * @param {Function} representation.enabled Callback to enable/disable QualityLevel
  24006. */
  24007. constructor(representation) {
  24008. let level = this; // eslint-disable-line
  24009. level.id = representation.id;
  24010. level.label = level.id;
  24011. level.width = representation.width;
  24012. level.height = representation.height;
  24013. level.bitrate = representation.bandwidth;
  24014. level.frameRate = representation.frameRate;
  24015. level.enabled_ = representation.enabled;
  24016. Object.defineProperty(level, 'enabled', {
  24017. /**
  24018. * Get whether the QualityLevel is enabled.
  24019. *
  24020. * @return {boolean} True if the QualityLevel is enabled.
  24021. */
  24022. get() {
  24023. return level.enabled_();
  24024. },
  24025. /**
  24026. * Enable or disable the QualityLevel.
  24027. *
  24028. * @param {boolean} enable true to enable QualityLevel, false to disable.
  24029. */
  24030. set(enable) {
  24031. level.enabled_(enable);
  24032. }
  24033. });
  24034. return level;
  24035. }
  24036. }
  24037. /**
  24038. * A list of QualityLevels.
  24039. *
  24040. * interface QualityLevelList : EventTarget {
  24041. * getter QualityLevel (unsigned long index);
  24042. * readonly attribute unsigned long length;
  24043. * readonly attribute long selectedIndex;
  24044. *
  24045. * void addQualityLevel(QualityLevel qualityLevel)
  24046. * void removeQualityLevel(QualityLevel remove)
  24047. * QualityLevel? getQualityLevelById(DOMString id);
  24048. *
  24049. * attribute EventHandler onchange;
  24050. * attribute EventHandler onaddqualitylevel;
  24051. * attribute EventHandler onremovequalitylevel;
  24052. * };
  24053. *
  24054. * @extends videojs.EventTarget
  24055. * @class QualityLevelList
  24056. */
  24057. class QualityLevelList extends videojs.EventTarget {
  24058. constructor() {
  24059. super();
  24060. let list = this; // eslint-disable-line
  24061. list.levels_ = [];
  24062. list.selectedIndex_ = -1;
  24063. /**
  24064. * Get the index of the currently selected QualityLevel.
  24065. *
  24066. * @returns {number} The index of the selected QualityLevel. -1 if none selected.
  24067. * @readonly
  24068. */
  24069. Object.defineProperty(list, 'selectedIndex', {
  24070. get() {
  24071. return list.selectedIndex_;
  24072. }
  24073. });
  24074. /**
  24075. * Get the length of the list of QualityLevels.
  24076. *
  24077. * @returns {number} The length of the list.
  24078. * @readonly
  24079. */
  24080. Object.defineProperty(list, 'length', {
  24081. get() {
  24082. return list.levels_.length;
  24083. }
  24084. });
  24085. return list;
  24086. }
  24087. /**
  24088. * Adds a quality level to the list.
  24089. *
  24090. * @param {Representation|Object} representation The representation of the quality level
  24091. * @param {string} representation.id Unique id of the QualityLevel
  24092. * @param {number=} representation.width Resolution width of the QualityLevel
  24093. * @param {number=} representation.height Resolution height of the QualityLevel
  24094. * @param {number} representation.bandwidth Bitrate of the QualityLevel
  24095. * @param {number=} representation.frameRate Frame-rate of the QualityLevel
  24096. * @param {Function} representation.enabled Callback to enable/disable QualityLevel
  24097. * @return {QualityLevel} the QualityLevel added to the list
  24098. * @method addQualityLevel
  24099. */
  24100. addQualityLevel(representation) {
  24101. let qualityLevel = this.getQualityLevelById(representation.id); // Do not add duplicate quality levels
  24102. if (qualityLevel) {
  24103. return qualityLevel;
  24104. }
  24105. const index = this.levels_.length;
  24106. qualityLevel = new QualityLevel(representation);
  24107. if (!('' + index in this)) {
  24108. Object.defineProperty(this, index, {
  24109. get() {
  24110. return this.levels_[index];
  24111. }
  24112. });
  24113. }
  24114. this.levels_.push(qualityLevel);
  24115. this.trigger({
  24116. qualityLevel,
  24117. type: 'addqualitylevel'
  24118. });
  24119. return qualityLevel;
  24120. }
  24121. /**
  24122. * Removes a quality level from the list.
  24123. *
  24124. * @param {QualityLevel} remove QualityLevel to remove to the list.
  24125. * @return {QualityLevel|null} the QualityLevel removed or null if nothing removed
  24126. * @method removeQualityLevel
  24127. */
  24128. removeQualityLevel(qualityLevel) {
  24129. let removed = null;
  24130. for (let i = 0, l = this.length; i < l; i++) {
  24131. if (this[i] === qualityLevel) {
  24132. removed = this.levels_.splice(i, 1)[0];
  24133. if (this.selectedIndex_ === i) {
  24134. this.selectedIndex_ = -1;
  24135. } else if (this.selectedIndex_ > i) {
  24136. this.selectedIndex_--;
  24137. }
  24138. break;
  24139. }
  24140. }
  24141. if (removed) {
  24142. this.trigger({
  24143. qualityLevel,
  24144. type: 'removequalitylevel'
  24145. });
  24146. }
  24147. return removed;
  24148. }
  24149. /**
  24150. * Searches for a QualityLevel with the given id.
  24151. *
  24152. * @param {string} id The id of the QualityLevel to find.
  24153. * @return {QualityLevel|null} The QualityLevel with id, or null if not found.
  24154. * @method getQualityLevelById
  24155. */
  24156. getQualityLevelById(id) {
  24157. for (let i = 0, l = this.length; i < l; i++) {
  24158. const level = this[i];
  24159. if (level.id === id) {
  24160. return level;
  24161. }
  24162. }
  24163. return null;
  24164. }
  24165. /**
  24166. * Resets the list of QualityLevels to empty
  24167. *
  24168. * @method dispose
  24169. */
  24170. dispose() {
  24171. this.selectedIndex_ = -1;
  24172. this.levels_.length = 0;
  24173. }
  24174. }
  24175. /**
  24176. * change - The selected QualityLevel has changed.
  24177. * addqualitylevel - A QualityLevel has been added to the QualityLevelList.
  24178. * removequalitylevel - A QualityLevel has been removed from the QualityLevelList.
  24179. */
  24180. QualityLevelList.prototype.allowedEvents_ = {
  24181. change: 'change',
  24182. addqualitylevel: 'addqualitylevel',
  24183. removequalitylevel: 'removequalitylevel'
  24184. }; // emulate attribute EventHandler support to allow for feature detection
  24185. for (const event in QualityLevelList.prototype.allowedEvents_) {
  24186. QualityLevelList.prototype['on' + event] = null;
  24187. }
  24188. var version$5 = "3.0.0";
  24189. const registerPlugin = videojs.registerPlugin || videojs.plugin;
  24190. /**
  24191. * Initialization function for the qualityLevels plugin. Sets up the QualityLevelList and
  24192. * event handlers.
  24193. *
  24194. * @param {Player} player Player object.
  24195. * @param {Object} options Plugin options object.
  24196. * @function initPlugin
  24197. */
  24198. const initPlugin$1 = function (player, options) {
  24199. const originalPluginFn = player.qualityLevels;
  24200. const qualityLevelList = new QualityLevelList();
  24201. const disposeHandler = function () {
  24202. qualityLevelList.dispose();
  24203. player.qualityLevels = originalPluginFn;
  24204. player.off('dispose', disposeHandler);
  24205. };
  24206. player.on('dispose', disposeHandler);
  24207. player.qualityLevels = () => qualityLevelList;
  24208. player.qualityLevels.VERSION = version$5;
  24209. return qualityLevelList;
  24210. };
  24211. /**
  24212. * A video.js plugin.
  24213. *
  24214. * In the plugin function, the value of `this` is a video.js `Player`
  24215. * instance. You cannot rely on the player being in a "ready" state here,
  24216. * depending on how the plugin is invoked. This may or may not be important
  24217. * to you; if not, remove the wait for "ready"!
  24218. *
  24219. * @param {Object} options Plugin options object
  24220. * @function qualityLevels
  24221. */
  24222. const qualityLevels = function (options) {
  24223. return initPlugin$1(this, videojs.mergeOptions({}, options));
  24224. }; // Register the plugin with video.js.
  24225. registerPlugin('qualityLevels', qualityLevels); // Include the version number.
  24226. qualityLevels.VERSION = version$5;
  24227. /*! @name @videojs/http-streaming @version 3.0.2 @license Apache-2.0 */
  24228. /**
  24229. * @file resolve-url.js - Handling how URLs are resolved and manipulated
  24230. */
  24231. const resolveUrl = _resolveUrl;
  24232. /**
  24233. * If the xhr request was redirected, return the responseURL, otherwise,
  24234. * return the original url.
  24235. *
  24236. * @api private
  24237. *
  24238. * @param {string} url - an url being requested
  24239. * @param {XMLHttpRequest} req - xhr request result
  24240. *
  24241. * @return {string}
  24242. */
  24243. const resolveManifestRedirect = (url, req) => {
  24244. // To understand how the responseURL below is set and generated:
  24245. // - https://fetch.spec.whatwg.org/#concept-response-url
  24246. // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
  24247. if (req && req.responseURL && url !== req.responseURL) {
  24248. return req.responseURL;
  24249. }
  24250. return url;
  24251. };
  24252. const logger = source => {
  24253. if (videojs.log.debug) {
  24254. return videojs.log.debug.bind(videojs, 'VHS:', `${source} >`);
  24255. }
  24256. return function () {};
  24257. };
  24258. /**
  24259. * Provides a compatibility layer between Video.js 7 and 8 API changes for VHS.
  24260. */
  24261. /**
  24262. * Delegates to videojs.obj.merge (Video.js 8) or
  24263. * videojs.mergeOptions (Video.js 7).
  24264. */
  24265. function merge(...args) {
  24266. const context = videojs.obj || videojs;
  24267. const fn = context.merge || context.mergeOptions;
  24268. return fn.apply(context, args);
  24269. }
  24270. /**
  24271. * Delegates to videojs.time.createTimeRanges (Video.js 8) or
  24272. * videojs.createTimeRanges (Video.js 7).
  24273. */
  24274. function createTimeRanges(...args) {
  24275. const context = videojs.time || videojs;
  24276. const fn = context.createTimeRanges || context.createTimeRanges;
  24277. return fn.apply(context, args);
  24278. }
  24279. /**
  24280. * ranges
  24281. *
  24282. * Utilities for working with TimeRanges.
  24283. *
  24284. */
  24285. const TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
  24286. // can be misleading because of precision differences or when the current media has poorly
  24287. // aligned audio and video, which can cause values to be slightly off from what you would
  24288. // expect. This value is what we consider to be safe to use in such comparisons to account
  24289. // for these scenarios.
  24290. const SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
  24291. const filterRanges = function (timeRanges, predicate) {
  24292. const results = [];
  24293. let i;
  24294. if (timeRanges && timeRanges.length) {
  24295. // Search for ranges that match the predicate
  24296. for (i = 0; i < timeRanges.length; i++) {
  24297. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  24298. results.push([timeRanges.start(i), timeRanges.end(i)]);
  24299. }
  24300. }
  24301. }
  24302. return createTimeRanges(results);
  24303. };
  24304. /**
  24305. * Attempts to find the buffered TimeRange that contains the specified
  24306. * time.
  24307. *
  24308. * @param {TimeRanges} buffered - the TimeRanges object to query
  24309. * @param {number} time - the time to filter on.
  24310. * @return {TimeRanges} a new TimeRanges object
  24311. */
  24312. const findRange = function (buffered, time) {
  24313. return filterRanges(buffered, function (start, end) {
  24314. return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  24315. });
  24316. };
  24317. /**
  24318. * Returns the TimeRanges that begin later than the specified time.
  24319. *
  24320. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  24321. * @param {number} time - the time to filter on.
  24322. * @return {TimeRanges} a new TimeRanges object.
  24323. */
  24324. const findNextRange = function (timeRanges, time) {
  24325. return filterRanges(timeRanges, function (start) {
  24326. return start - TIME_FUDGE_FACTOR >= time;
  24327. });
  24328. };
  24329. /**
  24330. * Returns gaps within a list of TimeRanges
  24331. *
  24332. * @param {TimeRanges} buffered - the TimeRanges object
  24333. * @return {TimeRanges} a TimeRanges object of gaps
  24334. */
  24335. const findGaps = function (buffered) {
  24336. if (buffered.length < 2) {
  24337. return createTimeRanges();
  24338. }
  24339. const ranges = [];
  24340. for (let i = 1; i < buffered.length; i++) {
  24341. const start = buffered.end(i - 1);
  24342. const end = buffered.start(i);
  24343. ranges.push([start, end]);
  24344. }
  24345. return createTimeRanges(ranges);
  24346. };
  24347. /**
  24348. * Calculate the intersection of two TimeRanges
  24349. *
  24350. * @param {TimeRanges} bufferA
  24351. * @param {TimeRanges} bufferB
  24352. * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
  24353. */
  24354. const bufferIntersection = function (bufferA, bufferB) {
  24355. let start = null;
  24356. let end = null;
  24357. let arity = 0;
  24358. const extents = [];
  24359. const ranges = [];
  24360. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  24361. return createTimeRanges();
  24362. } // Handle the case where we have both buffers and create an
  24363. // intersection of the two
  24364. let count = bufferA.length; // A) Gather up all start and end times
  24365. while (count--) {
  24366. extents.push({
  24367. time: bufferA.start(count),
  24368. type: 'start'
  24369. });
  24370. extents.push({
  24371. time: bufferA.end(count),
  24372. type: 'end'
  24373. });
  24374. }
  24375. count = bufferB.length;
  24376. while (count--) {
  24377. extents.push({
  24378. time: bufferB.start(count),
  24379. type: 'start'
  24380. });
  24381. extents.push({
  24382. time: bufferB.end(count),
  24383. type: 'end'
  24384. });
  24385. } // B) Sort them by time
  24386. extents.sort(function (a, b) {
  24387. return a.time - b.time;
  24388. }); // C) Go along one by one incrementing arity for start and decrementing
  24389. // arity for ends
  24390. for (count = 0; count < extents.length; count++) {
  24391. if (extents[count].type === 'start') {
  24392. arity++; // D) If arity is ever incremented to 2 we are entering an
  24393. // overlapping range
  24394. if (arity === 2) {
  24395. start = extents[count].time;
  24396. }
  24397. } else if (extents[count].type === 'end') {
  24398. arity--; // E) If arity is ever decremented to 1 we leaving an
  24399. // overlapping range
  24400. if (arity === 1) {
  24401. end = extents[count].time;
  24402. }
  24403. } // F) Record overlapping ranges
  24404. if (start !== null && end !== null) {
  24405. ranges.push([start, end]);
  24406. start = null;
  24407. end = null;
  24408. }
  24409. }
  24410. return createTimeRanges(ranges);
  24411. };
  24412. /**
  24413. * Gets a human readable string for a TimeRange
  24414. *
  24415. * @param {TimeRange} range
  24416. * @return {string} a human readable string
  24417. */
  24418. const printableRange = range => {
  24419. const strArr = [];
  24420. if (!range || !range.length) {
  24421. return '';
  24422. }
  24423. for (let i = 0; i < range.length; i++) {
  24424. strArr.push(range.start(i) + ' => ' + range.end(i));
  24425. }
  24426. return strArr.join(', ');
  24427. };
  24428. /**
  24429. * Calculates the amount of time left in seconds until the player hits the end of the
  24430. * buffer and causes a rebuffer
  24431. *
  24432. * @param {TimeRange} buffered
  24433. * The state of the buffer
  24434. * @param {Numnber} currentTime
  24435. * The current time of the player
  24436. * @param {number} playbackRate
  24437. * The current playback rate of the player. Defaults to 1.
  24438. * @return {number}
  24439. * Time until the player has to start rebuffering in seconds.
  24440. * @function timeUntilRebuffer
  24441. */
  24442. const timeUntilRebuffer = function (buffered, currentTime, playbackRate = 1) {
  24443. const bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  24444. return (bufferedEnd - currentTime) / playbackRate;
  24445. };
  24446. /**
  24447. * Converts a TimeRanges object into an array representation
  24448. *
  24449. * @param {TimeRanges} timeRanges
  24450. * @return {Array}
  24451. */
  24452. const timeRangesToArray = timeRanges => {
  24453. const timeRangesList = [];
  24454. for (let i = 0; i < timeRanges.length; i++) {
  24455. timeRangesList.push({
  24456. start: timeRanges.start(i),
  24457. end: timeRanges.end(i)
  24458. });
  24459. }
  24460. return timeRangesList;
  24461. };
  24462. /**
  24463. * Determines if two time range objects are different.
  24464. *
  24465. * @param {TimeRange} a
  24466. * the first time range object to check
  24467. *
  24468. * @param {TimeRange} b
  24469. * the second time range object to check
  24470. *
  24471. * @return {Boolean}
  24472. * Whether the time range objects differ
  24473. */
  24474. const isRangeDifferent = function (a, b) {
  24475. // same object
  24476. if (a === b) {
  24477. return false;
  24478. } // one or the other is undefined
  24479. if (!a && b || !b && a) {
  24480. return true;
  24481. } // length is different
  24482. if (a.length !== b.length) {
  24483. return true;
  24484. } // see if any start/end pair is different
  24485. for (let i = 0; i < a.length; i++) {
  24486. if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
  24487. return true;
  24488. }
  24489. } // if the length and every pair is the same
  24490. // this is the same time range
  24491. return false;
  24492. };
  24493. const lastBufferedEnd = function (a) {
  24494. if (!a || !a.length || !a.end) {
  24495. return;
  24496. }
  24497. return a.end(a.length - 1);
  24498. };
  24499. /**
  24500. * A utility function to add up the amount of time in a timeRange
  24501. * after a specified startTime.
  24502. * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0
  24503. * would return 40 as there are 40s seconds after 0 in the timeRange
  24504. *
  24505. * @param {TimeRange} range
  24506. * The range to check against
  24507. * @param {number} startTime
  24508. * The time in the time range that you should start counting from
  24509. *
  24510. * @return {number}
  24511. * The number of seconds in the buffer passed the specified time.
  24512. */
  24513. const timeAheadOf = function (range, startTime) {
  24514. let time = 0;
  24515. if (!range || !range.length) {
  24516. return time;
  24517. }
  24518. for (let i = 0; i < range.length; i++) {
  24519. const start = range.start(i);
  24520. const end = range.end(i); // startTime is after this range entirely
  24521. if (startTime > end) {
  24522. continue;
  24523. } // startTime is within this range
  24524. if (startTime > start && startTime <= end) {
  24525. time += end - startTime;
  24526. continue;
  24527. } // startTime is before this range.
  24528. time += end - start;
  24529. }
  24530. return time;
  24531. };
  24532. /**
  24533. * @file playlist.js
  24534. *
  24535. * Playlist related utilities.
  24536. */
  24537. /**
  24538. * Get the duration of a segment, with special cases for
  24539. * llhls segments that do not have a duration yet.
  24540. *
  24541. * @param {Object} playlist
  24542. * the playlist that the segment belongs to.
  24543. * @param {Object} segment
  24544. * the segment to get a duration for.
  24545. *
  24546. * @return {number}
  24547. * the segment duration
  24548. */
  24549. const segmentDurationWithParts = (playlist, segment) => {
  24550. // if this isn't a preload segment
  24551. // then we will have a segment duration that is accurate.
  24552. if (!segment.preload) {
  24553. return segment.duration;
  24554. } // otherwise we have to add up parts and preload hints
  24555. // to get an up to date duration.
  24556. let result = 0;
  24557. (segment.parts || []).forEach(function (p) {
  24558. result += p.duration;
  24559. }); // for preload hints we have to use partTargetDuration
  24560. // as they won't even have a duration yet.
  24561. (segment.preloadHints || []).forEach(function (p) {
  24562. if (p.type === 'PART') {
  24563. result += playlist.partTargetDuration;
  24564. }
  24565. });
  24566. return result;
  24567. };
  24568. /**
  24569. * A function to get a combined list of parts and segments with durations
  24570. * and indexes.
  24571. *
  24572. * @param {Playlist} playlist the playlist to get the list for.
  24573. *
  24574. * @return {Array} The part/segment list.
  24575. */
  24576. const getPartsAndSegments = playlist => (playlist.segments || []).reduce((acc, segment, si) => {
  24577. if (segment.parts) {
  24578. segment.parts.forEach(function (part, pi) {
  24579. acc.push({
  24580. duration: part.duration,
  24581. segmentIndex: si,
  24582. partIndex: pi,
  24583. part,
  24584. segment
  24585. });
  24586. });
  24587. } else {
  24588. acc.push({
  24589. duration: segment.duration,
  24590. segmentIndex: si,
  24591. partIndex: null,
  24592. segment,
  24593. part: null
  24594. });
  24595. }
  24596. return acc;
  24597. }, []);
  24598. const getLastParts = media => {
  24599. const lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  24600. return lastSegment && lastSegment.parts || [];
  24601. };
  24602. const getKnownPartCount = ({
  24603. preloadSegment
  24604. }) => {
  24605. if (!preloadSegment) {
  24606. return;
  24607. }
  24608. const {
  24609. parts,
  24610. preloadHints
  24611. } = preloadSegment;
  24612. let partCount = (preloadHints || []).reduce((count, hint) => count + (hint.type === 'PART' ? 1 : 0), 0);
  24613. partCount += parts && parts.length ? parts.length : 0;
  24614. return partCount;
  24615. };
  24616. /**
  24617. * Get the number of seconds to delay from the end of a
  24618. * live playlist.
  24619. *
  24620. * @param {Playlist} main the main playlist
  24621. * @param {Playlist} media the media playlist
  24622. * @return {number} the hold back in seconds.
  24623. */
  24624. const liveEdgeDelay = (main, media) => {
  24625. if (media.endList) {
  24626. return 0;
  24627. } // dash suggestedPresentationDelay trumps everything
  24628. if (main && main.suggestedPresentationDelay) {
  24629. return main.suggestedPresentationDelay;
  24630. }
  24631. const hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
  24632. if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
  24633. return media.serverControl.partHoldBack;
  24634. } else if (hasParts && media.partTargetDuration) {
  24635. return media.partTargetDuration * 3; // finally look for full segment delays
  24636. } else if (media.serverControl && media.serverControl.holdBack) {
  24637. return media.serverControl.holdBack;
  24638. } else if (media.targetDuration) {
  24639. return media.targetDuration * 3;
  24640. }
  24641. return 0;
  24642. };
  24643. /**
  24644. * walk backward until we find a duration we can use
  24645. * or return a failure
  24646. *
  24647. * @param {Playlist} playlist the playlist to walk through
  24648. * @param {Number} endSequence the mediaSequence to stop walking on
  24649. */
  24650. const backwardDuration = function (playlist, endSequence) {
  24651. let result = 0;
  24652. let i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
  24653. // the interval, use it
  24654. let segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
  24655. // information that is earlier than endSequence
  24656. if (segment) {
  24657. if (typeof segment.start !== 'undefined') {
  24658. return {
  24659. result: segment.start,
  24660. precise: true
  24661. };
  24662. }
  24663. if (typeof segment.end !== 'undefined') {
  24664. return {
  24665. result: segment.end - segment.duration,
  24666. precise: true
  24667. };
  24668. }
  24669. }
  24670. while (i--) {
  24671. segment = playlist.segments[i];
  24672. if (typeof segment.end !== 'undefined') {
  24673. return {
  24674. result: result + segment.end,
  24675. precise: true
  24676. };
  24677. }
  24678. result += segmentDurationWithParts(playlist, segment);
  24679. if (typeof segment.start !== 'undefined') {
  24680. return {
  24681. result: result + segment.start,
  24682. precise: true
  24683. };
  24684. }
  24685. }
  24686. return {
  24687. result,
  24688. precise: false
  24689. };
  24690. };
  24691. /**
  24692. * walk forward until we find a duration we can use
  24693. * or return a failure
  24694. *
  24695. * @param {Playlist} playlist the playlist to walk through
  24696. * @param {number} endSequence the mediaSequence to stop walking on
  24697. */
  24698. const forwardDuration = function (playlist, endSequence) {
  24699. let result = 0;
  24700. let segment;
  24701. let i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
  24702. // information
  24703. for (; i < playlist.segments.length; i++) {
  24704. segment = playlist.segments[i];
  24705. if (typeof segment.start !== 'undefined') {
  24706. return {
  24707. result: segment.start - result,
  24708. precise: true
  24709. };
  24710. }
  24711. result += segmentDurationWithParts(playlist, segment);
  24712. if (typeof segment.end !== 'undefined') {
  24713. return {
  24714. result: segment.end - result,
  24715. precise: true
  24716. };
  24717. }
  24718. } // indicate we didn't find a useful duration estimate
  24719. return {
  24720. result: -1,
  24721. precise: false
  24722. };
  24723. };
  24724. /**
  24725. * Calculate the media duration from the segments associated with a
  24726. * playlist. The duration of a subinterval of the available segments
  24727. * may be calculated by specifying an end index.
  24728. *
  24729. * @param {Object} playlist a media playlist object
  24730. * @param {number=} endSequence an exclusive upper boundary
  24731. * for the playlist. Defaults to playlist length.
  24732. * @param {number} expired the amount of time that has dropped
  24733. * off the front of the playlist in a live scenario
  24734. * @return {number} the duration between the first available segment
  24735. * and end index.
  24736. */
  24737. const intervalDuration = function (playlist, endSequence, expired) {
  24738. if (typeof endSequence === 'undefined') {
  24739. endSequence = playlist.mediaSequence + playlist.segments.length;
  24740. }
  24741. if (endSequence < playlist.mediaSequence) {
  24742. return 0;
  24743. } // do a backward walk to estimate the duration
  24744. const backward = backwardDuration(playlist, endSequence);
  24745. if (backward.precise) {
  24746. // if we were able to base our duration estimate on timing
  24747. // information provided directly from the Media Source, return
  24748. // it
  24749. return backward.result;
  24750. } // walk forward to see if a precise duration estimate can be made
  24751. // that way
  24752. const forward = forwardDuration(playlist, endSequence);
  24753. if (forward.precise) {
  24754. // we found a segment that has been buffered and so it's
  24755. // position is known precisely
  24756. return forward.result;
  24757. } // return the less-precise, playlist-based duration estimate
  24758. return backward.result + expired;
  24759. };
  24760. /**
  24761. * Calculates the duration of a playlist. If a start and end index
  24762. * are specified, the duration will be for the subset of the media
  24763. * timeline between those two indices. The total duration for live
  24764. * playlists is always Infinity.
  24765. *
  24766. * @param {Object} playlist a media playlist object
  24767. * @param {number=} endSequence an exclusive upper
  24768. * boundary for the playlist. Defaults to the playlist media
  24769. * sequence number plus its length.
  24770. * @param {number=} expired the amount of time that has
  24771. * dropped off the front of the playlist in a live scenario
  24772. * @return {number} the duration between the start index and end
  24773. * index.
  24774. */
  24775. const duration = function (playlist, endSequence, expired) {
  24776. if (!playlist) {
  24777. return 0;
  24778. }
  24779. if (typeof expired !== 'number') {
  24780. expired = 0;
  24781. } // if a slice of the total duration is not requested, use
  24782. // playlist-level duration indicators when they're present
  24783. if (typeof endSequence === 'undefined') {
  24784. // if present, use the duration specified in the playlist
  24785. if (playlist.totalDuration) {
  24786. return playlist.totalDuration;
  24787. } // duration should be Infinity for live playlists
  24788. if (!playlist.endList) {
  24789. return window$1.Infinity;
  24790. }
  24791. } // calculate the total duration based on the segment durations
  24792. return intervalDuration(playlist, endSequence, expired);
  24793. };
  24794. /**
  24795. * Calculate the time between two indexes in the current playlist
  24796. * neight the start- nor the end-index need to be within the current
  24797. * playlist in which case, the targetDuration of the playlist is used
  24798. * to approximate the durations of the segments
  24799. *
  24800. * @param {Array} options.durationList list to iterate over for durations.
  24801. * @param {number} options.defaultDuration duration to use for elements before or after the durationList
  24802. * @param {number} options.startIndex partsAndSegments index to start
  24803. * @param {number} options.endIndex partsAndSegments index to end.
  24804. * @return {number} the number of seconds between startIndex and endIndex
  24805. */
  24806. const sumDurations = function ({
  24807. defaultDuration,
  24808. durationList,
  24809. startIndex,
  24810. endIndex
  24811. }) {
  24812. let durations = 0;
  24813. if (startIndex > endIndex) {
  24814. [startIndex, endIndex] = [endIndex, startIndex];
  24815. }
  24816. if (startIndex < 0) {
  24817. for (let i = startIndex; i < Math.min(0, endIndex); i++) {
  24818. durations += defaultDuration;
  24819. }
  24820. startIndex = 0;
  24821. }
  24822. for (let i = startIndex; i < endIndex; i++) {
  24823. durations += durationList[i].duration;
  24824. }
  24825. return durations;
  24826. };
  24827. /**
  24828. * Calculates the playlist end time
  24829. *
  24830. * @param {Object} playlist a media playlist object
  24831. * @param {number=} expired the amount of time that has
  24832. * dropped off the front of the playlist in a live scenario
  24833. * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
  24834. * playlist end calculation should consider the safe live end
  24835. * (truncate the playlist end by three segments). This is normally
  24836. * used for calculating the end of the playlist's seekable range.
  24837. * This takes into account the value of liveEdgePadding.
  24838. * Setting liveEdgePadding to 0 is equivalent to setting this to false.
  24839. * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
  24840. * If this is provided, it is used in the safe live end calculation.
  24841. * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
  24842. * Corresponds to suggestedPresentationDelay in DASH manifests.
  24843. * @return {number} the end time of playlist
  24844. * @function playlistEnd
  24845. */
  24846. const playlistEnd = function (playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  24847. if (!playlist || !playlist.segments) {
  24848. return null;
  24849. }
  24850. if (playlist.endList) {
  24851. return duration(playlist);
  24852. }
  24853. if (expired === null) {
  24854. return null;
  24855. }
  24856. expired = expired || 0;
  24857. let lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  24858. if (useSafeLiveEnd) {
  24859. liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
  24860. lastSegmentEndTime -= liveEdgePadding;
  24861. } // don't return a time less than zero
  24862. return Math.max(0, lastSegmentEndTime);
  24863. };
  24864. /**
  24865. * Calculates the interval of time that is currently seekable in a
  24866. * playlist. The returned time ranges are relative to the earliest
  24867. * moment in the specified playlist that is still available. A full
  24868. * seekable implementation for live streams would need to offset
  24869. * these values by the duration of content that has expired from the
  24870. * stream.
  24871. *
  24872. * @param {Object} playlist a media playlist object
  24873. * dropped off the front of the playlist in a live scenario
  24874. * @param {number=} expired the amount of time that has
  24875. * dropped off the front of the playlist in a live scenario
  24876. * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
  24877. * Corresponds to suggestedPresentationDelay in DASH manifests.
  24878. * @return {TimeRanges} the periods of time that are valid targets
  24879. * for seeking
  24880. */
  24881. const seekable = function (playlist, expired, liveEdgePadding) {
  24882. const useSafeLiveEnd = true;
  24883. const seekableStart = expired || 0;
  24884. const seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  24885. if (seekableEnd === null) {
  24886. return createTimeRanges();
  24887. }
  24888. return createTimeRanges(seekableStart, seekableEnd);
  24889. };
  24890. /**
  24891. * Determine the index and estimated starting time of the segment that
  24892. * contains a specified playback position in a media playlist.
  24893. *
  24894. * @param {Object} options.playlist the media playlist to query
  24895. * @param {number} options.currentTime The number of seconds since the earliest
  24896. * possible position to determine the containing segment for
  24897. * @param {number} options.startTime the time when the segment/part starts
  24898. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  24899. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  24900. *
  24901. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  24902. */
  24903. const getMediaInfoForTime = function ({
  24904. playlist,
  24905. currentTime,
  24906. startingSegmentIndex,
  24907. startingPartIndex,
  24908. startTime,
  24909. exactManifestTimings
  24910. }) {
  24911. let time = currentTime - startTime;
  24912. const partsAndSegments = getPartsAndSegments(playlist);
  24913. let startIndex = 0;
  24914. for (let i = 0; i < partsAndSegments.length; i++) {
  24915. const partAndSegment = partsAndSegments[i];
  24916. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  24917. continue;
  24918. } // skip this if part index does not match.
  24919. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  24920. continue;
  24921. }
  24922. startIndex = i;
  24923. break;
  24924. }
  24925. if (time < 0) {
  24926. // Walk backward from startIndex in the playlist, adding durations
  24927. // until we find a segment that contains `time` and return it
  24928. if (startIndex > 0) {
  24929. for (let i = startIndex - 1; i >= 0; i--) {
  24930. const partAndSegment = partsAndSegments[i];
  24931. time += partAndSegment.duration;
  24932. if (exactManifestTimings) {
  24933. if (time < 0) {
  24934. continue;
  24935. }
  24936. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  24937. continue;
  24938. }
  24939. return {
  24940. partIndex: partAndSegment.partIndex,
  24941. segmentIndex: partAndSegment.segmentIndex,
  24942. startTime: startTime - sumDurations({
  24943. defaultDuration: playlist.targetDuration,
  24944. durationList: partsAndSegments,
  24945. startIndex,
  24946. endIndex: i
  24947. })
  24948. };
  24949. }
  24950. } // We were unable to find a good segment within the playlist
  24951. // so select the first segment
  24952. return {
  24953. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  24954. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  24955. startTime: currentTime
  24956. };
  24957. } // When startIndex is negative, we first walk forward to first segment
  24958. // adding target durations. If we "run out of time" before getting to
  24959. // the first segment, return the first segment
  24960. if (startIndex < 0) {
  24961. for (let i = startIndex; i < 0; i++) {
  24962. time -= playlist.targetDuration;
  24963. if (time < 0) {
  24964. return {
  24965. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  24966. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  24967. startTime: currentTime
  24968. };
  24969. }
  24970. }
  24971. startIndex = 0;
  24972. } // Walk forward from startIndex in the playlist, subtracting durations
  24973. // until we find a segment that contains `time` and return it
  24974. for (let i = startIndex; i < partsAndSegments.length; i++) {
  24975. const partAndSegment = partsAndSegments[i];
  24976. time -= partAndSegment.duration;
  24977. if (exactManifestTimings) {
  24978. if (time > 0) {
  24979. continue;
  24980. }
  24981. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  24982. continue;
  24983. }
  24984. return {
  24985. partIndex: partAndSegment.partIndex,
  24986. segmentIndex: partAndSegment.segmentIndex,
  24987. startTime: startTime + sumDurations({
  24988. defaultDuration: playlist.targetDuration,
  24989. durationList: partsAndSegments,
  24990. startIndex,
  24991. endIndex: i
  24992. })
  24993. };
  24994. } // We are out of possible candidates so load the last one...
  24995. return {
  24996. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  24997. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  24998. startTime: currentTime
  24999. };
  25000. };
  25001. /**
  25002. * Check whether the playlist is excluded or not.
  25003. *
  25004. * @param {Object} playlist the media playlist object
  25005. * @return {boolean} whether the playlist is excluded or not
  25006. * @function isExcluded
  25007. */
  25008. const isExcluded = function (playlist) {
  25009. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  25010. };
  25011. /**
  25012. * Check whether the playlist is compatible with current playback configuration or has
  25013. * been excluded permanently for being incompatible.
  25014. *
  25015. * @param {Object} playlist the media playlist object
  25016. * @return {boolean} whether the playlist is incompatible or not
  25017. * @function isIncompatible
  25018. */
  25019. const isIncompatible = function (playlist) {
  25020. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  25021. };
  25022. /**
  25023. * Check whether the playlist is enabled or not.
  25024. *
  25025. * @param {Object} playlist the media playlist object
  25026. * @return {boolean} whether the playlist is enabled or not
  25027. * @function isEnabled
  25028. */
  25029. const isEnabled = function (playlist) {
  25030. const excluded = isExcluded(playlist);
  25031. return !playlist.disabled && !excluded;
  25032. };
  25033. /**
  25034. * Check whether the playlist has been manually disabled through the representations api.
  25035. *
  25036. * @param {Object} playlist the media playlist object
  25037. * @return {boolean} whether the playlist is disabled manually or not
  25038. * @function isDisabled
  25039. */
  25040. const isDisabled = function (playlist) {
  25041. return playlist.disabled;
  25042. };
  25043. /**
  25044. * Returns whether the current playlist is an AES encrypted HLS stream
  25045. *
  25046. * @return {boolean} true if it's an AES encrypted HLS stream
  25047. */
  25048. const isAes = function (media) {
  25049. for (let i = 0; i < media.segments.length; i++) {
  25050. if (media.segments[i].key) {
  25051. return true;
  25052. }
  25053. }
  25054. return false;
  25055. };
  25056. /**
  25057. * Checks if the playlist has a value for the specified attribute
  25058. *
  25059. * @param {string} attr
  25060. * Attribute to check for
  25061. * @param {Object} playlist
  25062. * The media playlist object
  25063. * @return {boolean}
  25064. * Whether the playlist contains a value for the attribute or not
  25065. * @function hasAttribute
  25066. */
  25067. const hasAttribute = function (attr, playlist) {
  25068. return playlist.attributes && playlist.attributes[attr];
  25069. };
  25070. /**
  25071. * Estimates the time required to complete a segment download from the specified playlist
  25072. *
  25073. * @param {number} segmentDuration
  25074. * Duration of requested segment
  25075. * @param {number} bandwidth
  25076. * Current measured bandwidth of the player
  25077. * @param {Object} playlist
  25078. * The media playlist object
  25079. * @param {number=} bytesReceived
  25080. * Number of bytes already received for the request. Defaults to 0
  25081. * @return {number|NaN}
  25082. * The estimated time to request the segment. NaN if bandwidth information for
  25083. * the given playlist is unavailable
  25084. * @function estimateSegmentRequestTime
  25085. */
  25086. const estimateSegmentRequestTime = function (segmentDuration, bandwidth, playlist, bytesReceived = 0) {
  25087. if (!hasAttribute('BANDWIDTH', playlist)) {
  25088. return NaN;
  25089. }
  25090. const size = segmentDuration * playlist.attributes.BANDWIDTH;
  25091. return (size - bytesReceived * 8) / bandwidth;
  25092. };
  25093. /*
  25094. * Returns whether the current playlist is the lowest rendition
  25095. *
  25096. * @return {Boolean} true if on lowest rendition
  25097. */
  25098. const isLowestEnabledRendition = (main, media) => {
  25099. if (main.playlists.length === 1) {
  25100. return true;
  25101. }
  25102. const currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  25103. return main.playlists.filter(playlist => {
  25104. if (!isEnabled(playlist)) {
  25105. return false;
  25106. }
  25107. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  25108. }).length === 0;
  25109. };
  25110. const playlistMatch = (a, b) => {
  25111. // both playlits are null
  25112. // or only one playlist is non-null
  25113. // no match
  25114. if (!a && !b || !a && b || a && !b) {
  25115. return false;
  25116. } // playlist objects are the same, match
  25117. if (a === b) {
  25118. return true;
  25119. } // first try to use id as it should be the most
  25120. // accurate
  25121. if (a.id && b.id && a.id === b.id) {
  25122. return true;
  25123. } // next try to use reslovedUri as it should be the
  25124. // second most accurate.
  25125. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  25126. return true;
  25127. } // finally try to use uri as it should be accurate
  25128. // but might miss a few cases for relative uris
  25129. if (a.uri && b.uri && a.uri === b.uri) {
  25130. return true;
  25131. }
  25132. return false;
  25133. };
  25134. const someAudioVariant = function (main, callback) {
  25135. const AUDIO = main && main.mediaGroups && main.mediaGroups.AUDIO || {};
  25136. let found = false;
  25137. for (const groupName in AUDIO) {
  25138. for (const label in AUDIO[groupName]) {
  25139. found = callback(AUDIO[groupName][label]);
  25140. if (found) {
  25141. break;
  25142. }
  25143. }
  25144. if (found) {
  25145. break;
  25146. }
  25147. }
  25148. return !!found;
  25149. };
  25150. const isAudioOnly = main => {
  25151. // we are audio only if we have no main playlists but do
  25152. // have media group playlists.
  25153. if (!main || !main.playlists || !main.playlists.length) {
  25154. // without audio variants or playlists this
  25155. // is not an audio only main.
  25156. const found = someAudioVariant(main, variant => variant.playlists && variant.playlists.length || variant.uri);
  25157. return found;
  25158. } // if every playlist has only an audio codec it is audio only
  25159. for (let i = 0; i < main.playlists.length; i++) {
  25160. const playlist = main.playlists[i];
  25161. const CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  25162. if (CODECS && CODECS.split(',').every(c => isAudioCodec(c))) {
  25163. continue;
  25164. } // playlist is in an audio group it is audio only
  25165. const found = someAudioVariant(main, variant => playlistMatch(playlist, variant));
  25166. if (found) {
  25167. continue;
  25168. } // if we make it here this playlist isn't audio and we
  25169. // are not audio only
  25170. return false;
  25171. } // if we make it past every playlist without returning, then
  25172. // this is an audio only playlist.
  25173. return true;
  25174. }; // exports
  25175. var Playlist = {
  25176. liveEdgeDelay,
  25177. duration,
  25178. seekable,
  25179. getMediaInfoForTime,
  25180. isEnabled,
  25181. isDisabled,
  25182. isExcluded,
  25183. isIncompatible,
  25184. playlistEnd,
  25185. isAes,
  25186. hasAttribute,
  25187. estimateSegmentRequestTime,
  25188. isLowestEnabledRendition,
  25189. isAudioOnly,
  25190. playlistMatch,
  25191. segmentDurationWithParts
  25192. };
  25193. const {
  25194. log
  25195. } = videojs;
  25196. const createPlaylistID = (index, uri) => {
  25197. return `${index}-${uri}`;
  25198. }; // default function for creating a group id
  25199. const groupID = (type, group, label) => {
  25200. return `placeholder-uri-${type}-${group}-${label}`;
  25201. };
  25202. /**
  25203. * Parses a given m3u8 playlist
  25204. *
  25205. * @param {Function} [onwarn]
  25206. * a function to call when the parser triggers a warning event.
  25207. * @param {Function} [oninfo]
  25208. * a function to call when the parser triggers an info event.
  25209. * @param {string} manifestString
  25210. * The downloaded manifest string
  25211. * @param {Object[]} [customTagParsers]
  25212. * An array of custom tag parsers for the m3u8-parser instance
  25213. * @param {Object[]} [customTagMappers]
  25214. * An array of custom tag mappers for the m3u8-parser instance
  25215. * @param {boolean} [llhls]
  25216. * Whether to keep ll-hls features in the manifest after parsing.
  25217. * @return {Object}
  25218. * The manifest object
  25219. */
  25220. const parseManifest = ({
  25221. onwarn,
  25222. oninfo,
  25223. manifestString,
  25224. customTagParsers = [],
  25225. customTagMappers = [],
  25226. llhls
  25227. }) => {
  25228. const parser = new Parser();
  25229. if (onwarn) {
  25230. parser.on('warn', onwarn);
  25231. }
  25232. if (oninfo) {
  25233. parser.on('info', oninfo);
  25234. }
  25235. customTagParsers.forEach(customParser => parser.addParser(customParser));
  25236. customTagMappers.forEach(mapper => parser.addTagMapper(mapper));
  25237. parser.push(manifestString);
  25238. parser.end();
  25239. const manifest = parser.manifest; // remove llhls features from the parsed manifest
  25240. // if we don't want llhls support.
  25241. if (!llhls) {
  25242. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  25243. if (manifest.hasOwnProperty(k)) {
  25244. delete manifest[k];
  25245. }
  25246. });
  25247. if (manifest.segments) {
  25248. manifest.segments.forEach(function (segment) {
  25249. ['parts', 'preloadHints'].forEach(function (k) {
  25250. if (segment.hasOwnProperty(k)) {
  25251. delete segment[k];
  25252. }
  25253. });
  25254. });
  25255. }
  25256. }
  25257. if (!manifest.targetDuration) {
  25258. let targetDuration = 10;
  25259. if (manifest.segments && manifest.segments.length) {
  25260. targetDuration = manifest.segments.reduce((acc, s) => Math.max(acc, s.duration), 0);
  25261. }
  25262. if (onwarn) {
  25263. onwarn(`manifest has no targetDuration defaulting to ${targetDuration}`);
  25264. }
  25265. manifest.targetDuration = targetDuration;
  25266. }
  25267. const parts = getLastParts(manifest);
  25268. if (parts.length && !manifest.partTargetDuration) {
  25269. const partTargetDuration = parts.reduce((acc, p) => Math.max(acc, p.duration), 0);
  25270. if (onwarn) {
  25271. onwarn(`manifest has no partTargetDuration defaulting to ${partTargetDuration}`);
  25272. 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.');
  25273. }
  25274. manifest.partTargetDuration = partTargetDuration;
  25275. }
  25276. return manifest;
  25277. };
  25278. /**
  25279. * Loops through all supported media groups in main and calls the provided
  25280. * callback for each group
  25281. *
  25282. * @param {Object} main
  25283. * The parsed main manifest object
  25284. * @param {Function} callback
  25285. * Callback to call for each media group
  25286. */
  25287. const forEachMediaGroup = (main, callback) => {
  25288. if (!main.mediaGroups) {
  25289. return;
  25290. }
  25291. ['AUDIO', 'SUBTITLES'].forEach(mediaType => {
  25292. if (!main.mediaGroups[mediaType]) {
  25293. return;
  25294. }
  25295. for (const groupKey in main.mediaGroups[mediaType]) {
  25296. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  25297. const mediaProperties = main.mediaGroups[mediaType][groupKey][labelKey];
  25298. callback(mediaProperties, mediaType, groupKey, labelKey);
  25299. }
  25300. }
  25301. });
  25302. };
  25303. /**
  25304. * Adds properties and attributes to the playlist to keep consistent functionality for
  25305. * playlists throughout VHS.
  25306. *
  25307. * @param {Object} config
  25308. * Arguments object
  25309. * @param {Object} config.playlist
  25310. * The media playlist
  25311. * @param {string} [config.uri]
  25312. * The uri to the media playlist (if media playlist is not from within a main
  25313. * playlist)
  25314. * @param {string} id
  25315. * ID to use for the playlist
  25316. */
  25317. const setupMediaPlaylist = ({
  25318. playlist,
  25319. uri,
  25320. id
  25321. }) => {
  25322. playlist.id = id;
  25323. playlist.playlistErrors_ = 0;
  25324. if (uri) {
  25325. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  25326. // playlists do not contain their own source URI, but one is needed for consistency in
  25327. // VHS.
  25328. playlist.uri = uri;
  25329. } // For HLS main playlists, even though certain attributes MUST be defined, the
  25330. // stream may still be played without them.
  25331. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  25332. // manifest.
  25333. //
  25334. // To avoid undefined reference errors through the project, and make the code easier
  25335. // to write/read, add an empty attributes object for these cases.
  25336. playlist.attributes = playlist.attributes || {};
  25337. };
  25338. /**
  25339. * Adds ID, resolvedUri, and attributes properties to each playlist of the main, where
  25340. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  25341. * playlist references to the playlists array.
  25342. *
  25343. * @param {Object} main
  25344. * The main playlist
  25345. */
  25346. const setupMediaPlaylists = main => {
  25347. let i = main.playlists.length;
  25348. while (i--) {
  25349. const playlist = main.playlists[i];
  25350. setupMediaPlaylist({
  25351. playlist,
  25352. id: createPlaylistID(i, playlist.uri)
  25353. });
  25354. playlist.resolvedUri = resolveUrl(main.uri, playlist.uri);
  25355. main.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  25356. main.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  25357. // the stream can be played without it. Although an attributes property may have been
  25358. // added to the playlist to prevent undefined references, issue a warning to fix the
  25359. // manifest.
  25360. if (!playlist.attributes.BANDWIDTH) {
  25361. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  25362. }
  25363. }
  25364. };
  25365. /**
  25366. * Adds resolvedUri properties to each media group.
  25367. *
  25368. * @param {Object} main
  25369. * The main playlist
  25370. */
  25371. const resolveMediaGroupUris = main => {
  25372. forEachMediaGroup(main, properties => {
  25373. if (properties.uri) {
  25374. properties.resolvedUri = resolveUrl(main.uri, properties.uri);
  25375. }
  25376. });
  25377. };
  25378. /**
  25379. * Creates a main playlist wrapper to insert a sole media playlist into.
  25380. *
  25381. * @param {Object} media
  25382. * Media playlist
  25383. * @param {string} uri
  25384. * The media URI
  25385. *
  25386. * @return {Object}
  25387. * main playlist
  25388. */
  25389. const mainForMedia = (media, uri) => {
  25390. const id = createPlaylistID(0, uri);
  25391. const main = {
  25392. mediaGroups: {
  25393. 'AUDIO': {},
  25394. 'VIDEO': {},
  25395. 'CLOSED-CAPTIONS': {},
  25396. 'SUBTITLES': {}
  25397. },
  25398. uri: window$1.location.href,
  25399. resolvedUri: window$1.location.href,
  25400. playlists: [{
  25401. uri,
  25402. id,
  25403. resolvedUri: uri,
  25404. // m3u8-parser does not attach an attributes property to media playlists so make
  25405. // sure that the property is attached to avoid undefined reference errors
  25406. attributes: {}
  25407. }]
  25408. }; // set up ID reference
  25409. main.playlists[id] = main.playlists[0]; // URI reference added for backwards compatibility
  25410. main.playlists[uri] = main.playlists[0];
  25411. return main;
  25412. };
  25413. /**
  25414. * Does an in-place update of the main manifest to add updated playlist URI references
  25415. * as well as other properties needed by VHS that aren't included by the parser.
  25416. *
  25417. * @param {Object} main
  25418. * main manifest object
  25419. * @param {string} uri
  25420. * The source URI
  25421. * @param {function} createGroupID
  25422. * A function to determine how to create the groupID for mediaGroups
  25423. */
  25424. const addPropertiesToMain = (main, uri, createGroupID = groupID) => {
  25425. main.uri = uri;
  25426. for (let i = 0; i < main.playlists.length; i++) {
  25427. if (!main.playlists[i].uri) {
  25428. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  25429. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  25430. // TODO: consider adding dummy URIs in mpd-parser
  25431. const phonyUri = `placeholder-uri-${i}`;
  25432. main.playlists[i].uri = phonyUri;
  25433. }
  25434. }
  25435. const audioOnlyMain = isAudioOnly(main);
  25436. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  25437. // add a playlist array under properties
  25438. if (!properties.playlists || !properties.playlists.length) {
  25439. // If the manifest is audio only and this media group does not have a uri, check
  25440. // if the media group is located in the main list of playlists. If it is, don't add
  25441. // placeholder properties as it shouldn't be considered an alternate audio track.
  25442. if (audioOnlyMain && mediaType === 'AUDIO' && !properties.uri) {
  25443. for (let i = 0; i < main.playlists.length; i++) {
  25444. const p = main.playlists[i];
  25445. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  25446. return;
  25447. }
  25448. }
  25449. }
  25450. properties.playlists = [_extends({}, properties)];
  25451. }
  25452. properties.playlists.forEach(function (p, i) {
  25453. const groupId = createGroupID(mediaType, groupKey, labelKey, p);
  25454. const id = createPlaylistID(i, groupId);
  25455. if (p.uri) {
  25456. p.resolvedUri = p.resolvedUri || resolveUrl(main.uri, p.uri);
  25457. } else {
  25458. // DEPRECATED, this has been added to prevent a breaking change.
  25459. // previously we only ever had a single media group playlist, so
  25460. // we mark the first playlist uri without prepending the index as we used to
  25461. // ideally we would do all of the playlists the same way.
  25462. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  25463. // the placeholder again
  25464. p.resolvedUri = p.uri;
  25465. }
  25466. p.id = p.id || id; // add an empty attributes object, all playlists are
  25467. // expected to have this.
  25468. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  25469. main.playlists[p.id] = p;
  25470. main.playlists[p.uri] = p;
  25471. });
  25472. });
  25473. setupMediaPlaylists(main);
  25474. resolveMediaGroupUris(main);
  25475. };
  25476. /**
  25477. * @file playlist-loader.js
  25478. *
  25479. * A state machine that manages the loading, caching, and updating of
  25480. * M3U8 playlists.
  25481. *
  25482. */
  25483. const {
  25484. EventTarget: EventTarget$1
  25485. } = videojs;
  25486. const addLLHLSQueryDirectives = (uri, media) => {
  25487. if (media.endList || !media.serverControl) {
  25488. return uri;
  25489. }
  25490. const parameters = {};
  25491. if (media.serverControl.canBlockReload) {
  25492. const {
  25493. preloadSegment
  25494. } = media; // next msn is a zero based value, length is not.
  25495. let nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  25496. // that we are going to request a part of that preload segment.
  25497. // the logic below is used to determine that.
  25498. if (preloadSegment) {
  25499. const parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  25500. const nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  25501. // length of parts, then we know we had part preload hints
  25502. // and we need to add the _HLS_part= query
  25503. if (nextPart > -1 && nextPart !== parts.length - 1) {
  25504. // add existing parts to our preload hints
  25505. // eslint-disable-next-line
  25506. parameters._HLS_part = nextPart;
  25507. } // this if statement makes sure that we request the msn
  25508. // of the preload segment if:
  25509. // 1. the preload segment had parts (and was not yet a full segment)
  25510. // but was added to our segments array
  25511. // 2. the preload segment had preload hints for parts that are not in
  25512. // the manifest yet.
  25513. // in all other cases we want the segment after the preload segment
  25514. // which will be given by using media.segments.length because it is 1 based
  25515. // rather than 0 based.
  25516. if (nextPart > -1 || parts.length) {
  25517. nextMSN--;
  25518. }
  25519. } // add _HLS_msn= in front of any _HLS_part query
  25520. // eslint-disable-next-line
  25521. parameters._HLS_msn = nextMSN;
  25522. }
  25523. if (media.serverControl && media.serverControl.canSkipUntil) {
  25524. // add _HLS_skip= infront of all other queries.
  25525. // eslint-disable-next-line
  25526. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  25527. }
  25528. if (Object.keys(parameters).length) {
  25529. const parsedUri = new window$1.URL(uri);
  25530. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  25531. if (!parameters.hasOwnProperty(name)) {
  25532. return;
  25533. }
  25534. parsedUri.searchParams.set(name, parameters[name]);
  25535. });
  25536. uri = parsedUri.toString();
  25537. }
  25538. return uri;
  25539. };
  25540. /**
  25541. * Returns a new segment object with properties and
  25542. * the parts array merged.
  25543. *
  25544. * @param {Object} a the old segment
  25545. * @param {Object} b the new segment
  25546. *
  25547. * @return {Object} the merged segment
  25548. */
  25549. const updateSegment = (a, b) => {
  25550. if (!a) {
  25551. return b;
  25552. }
  25553. const result = merge(a, b); // if only the old segment has preload hints
  25554. // and the new one does not, remove preload hints.
  25555. if (a.preloadHints && !b.preloadHints) {
  25556. delete result.preloadHints;
  25557. } // if only the old segment has parts
  25558. // then the parts are no longer valid
  25559. if (a.parts && !b.parts) {
  25560. delete result.parts; // if both segments have parts
  25561. // copy part propeties from the old segment
  25562. // to the new one.
  25563. } else if (a.parts && b.parts) {
  25564. for (let i = 0; i < b.parts.length; i++) {
  25565. if (a.parts && a.parts[i]) {
  25566. result.parts[i] = merge(a.parts[i], b.parts[i]);
  25567. }
  25568. }
  25569. } // set skipped to false for segments that have
  25570. // have had information merged from the old segment.
  25571. if (!a.skipped && b.skipped) {
  25572. result.skipped = false;
  25573. } // set preload to false for segments that have
  25574. // had information added in the new segment.
  25575. if (a.preload && !b.preload) {
  25576. result.preload = false;
  25577. }
  25578. return result;
  25579. };
  25580. /**
  25581. * Returns a new array of segments that is the result of merging
  25582. * properties from an older list of segments onto an updated
  25583. * list. No properties on the updated playlist will be ovewritten.
  25584. *
  25585. * @param {Array} original the outdated list of segments
  25586. * @param {Array} update the updated list of segments
  25587. * @param {number=} offset the index of the first update
  25588. * segment in the original segment list. For non-live playlists,
  25589. * this should always be zero and does not need to be
  25590. * specified. For live playlists, it should be the difference
  25591. * between the media sequence numbers in the original and updated
  25592. * playlists.
  25593. * @return {Array} a list of merged segment objects
  25594. */
  25595. const updateSegments = (original, update, offset) => {
  25596. const oldSegments = original.slice();
  25597. const newSegments = update.slice();
  25598. offset = offset || 0;
  25599. const result = [];
  25600. let currentMap;
  25601. for (let newIndex = 0; newIndex < newSegments.length; newIndex++) {
  25602. const oldSegment = oldSegments[newIndex + offset];
  25603. const newSegment = newSegments[newIndex];
  25604. if (oldSegment) {
  25605. currentMap = oldSegment.map || currentMap;
  25606. result.push(updateSegment(oldSegment, newSegment));
  25607. } else {
  25608. // carry over map to new segment if it is missing
  25609. if (currentMap && !newSegment.map) {
  25610. newSegment.map = currentMap;
  25611. }
  25612. result.push(newSegment);
  25613. }
  25614. }
  25615. return result;
  25616. };
  25617. const resolveSegmentUris = (segment, baseUri) => {
  25618. // preloadSegment will not have a uri at all
  25619. // as the segment isn't actually in the manifest yet, only parts
  25620. if (!segment.resolvedUri && segment.uri) {
  25621. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  25622. }
  25623. if (segment.key && !segment.key.resolvedUri) {
  25624. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  25625. }
  25626. if (segment.map && !segment.map.resolvedUri) {
  25627. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  25628. }
  25629. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  25630. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  25631. }
  25632. if (segment.parts && segment.parts.length) {
  25633. segment.parts.forEach(p => {
  25634. if (p.resolvedUri) {
  25635. return;
  25636. }
  25637. p.resolvedUri = resolveUrl(baseUri, p.uri);
  25638. });
  25639. }
  25640. if (segment.preloadHints && segment.preloadHints.length) {
  25641. segment.preloadHints.forEach(p => {
  25642. if (p.resolvedUri) {
  25643. return;
  25644. }
  25645. p.resolvedUri = resolveUrl(baseUri, p.uri);
  25646. });
  25647. }
  25648. };
  25649. const getAllSegments = function (media) {
  25650. const segments = media.segments || [];
  25651. const preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  25652. // a usable segment, only include a preloadSegment that has
  25653. // parts.
  25654. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  25655. // if preloadHints has a MAP that means that the
  25656. // init segment is going to change. We cannot use any of the parts
  25657. // from this preload segment.
  25658. if (preloadSegment.preloadHints) {
  25659. for (let i = 0; i < preloadSegment.preloadHints.length; i++) {
  25660. if (preloadSegment.preloadHints[i].type === 'MAP') {
  25661. return segments;
  25662. }
  25663. }
  25664. } // set the duration for our preload segment to target duration.
  25665. preloadSegment.duration = media.targetDuration;
  25666. preloadSegment.preload = true;
  25667. segments.push(preloadSegment);
  25668. }
  25669. return segments;
  25670. }; // consider the playlist unchanged if the playlist object is the same or
  25671. // the number of segments is equal, the media sequence number is unchanged,
  25672. // and this playlist hasn't become the end of the playlist
  25673. 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;
  25674. /**
  25675. * Returns a new main playlist that is the result of merging an
  25676. * updated media playlist into the original version. If the
  25677. * updated media playlist does not match any of the playlist
  25678. * entries in the original main playlist, null is returned.
  25679. *
  25680. * @param {Object} main a parsed main M3U8 object
  25681. * @param {Object} media a parsed media M3U8 object
  25682. * @return {Object} a new object that represents the original
  25683. * main playlist with the updated media playlist merged in, or
  25684. * null if the merge produced no change.
  25685. */
  25686. const updateMain$1 = (main, newMedia, unchangedCheck = isPlaylistUnchanged) => {
  25687. const result = merge(main, {});
  25688. const oldMedia = result.playlists[newMedia.id];
  25689. if (!oldMedia) {
  25690. return null;
  25691. }
  25692. if (unchangedCheck(oldMedia, newMedia)) {
  25693. return null;
  25694. }
  25695. newMedia.segments = getAllSegments(newMedia);
  25696. const mergedPlaylist = merge(oldMedia, newMedia); // always use the new media's preload segment
  25697. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  25698. delete mergedPlaylist.preloadSegment;
  25699. } // if the update could overlap existing segment information, merge the two segment lists
  25700. if (oldMedia.segments) {
  25701. if (newMedia.skip) {
  25702. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  25703. // old properties into the new segments
  25704. for (let i = 0; i < newMedia.skip.skippedSegments; i++) {
  25705. newMedia.segments.unshift({
  25706. skipped: true
  25707. });
  25708. }
  25709. }
  25710. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  25711. } // resolve any segment URIs to prevent us from having to do it later
  25712. mergedPlaylist.segments.forEach(segment => {
  25713. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  25714. }); // TODO Right now in the playlists array there are two references to each playlist, one
  25715. // that is referenced by index, and one by URI. The index reference may no longer be
  25716. // necessary.
  25717. for (let i = 0; i < result.playlists.length; i++) {
  25718. if (result.playlists[i].id === newMedia.id) {
  25719. result.playlists[i] = mergedPlaylist;
  25720. }
  25721. }
  25722. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  25723. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  25724. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  25725. if (!properties.playlists) {
  25726. return;
  25727. }
  25728. for (let i = 0; i < properties.playlists.length; i++) {
  25729. if (newMedia.id === properties.playlists[i].id) {
  25730. properties.playlists[i] = mergedPlaylist;
  25731. }
  25732. }
  25733. });
  25734. return result;
  25735. };
  25736. /**
  25737. * Calculates the time to wait before refreshing a live playlist
  25738. *
  25739. * @param {Object} media
  25740. * The current media
  25741. * @param {boolean} update
  25742. * True if there were any updates from the last refresh, false otherwise
  25743. * @return {number}
  25744. * The time in ms to wait before refreshing the live playlist
  25745. */
  25746. const refreshDelay = (media, update) => {
  25747. const segments = media.segments || [];
  25748. const lastSegment = segments[segments.length - 1];
  25749. const lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  25750. const lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  25751. if (update && lastDuration) {
  25752. return lastDuration * 1000;
  25753. } // if the playlist is unchanged since the last reload or last segment duration
  25754. // cannot be determined, try again after half the target duration
  25755. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  25756. };
  25757. /**
  25758. * Load a playlist from a remote location
  25759. *
  25760. * @class PlaylistLoader
  25761. * @extends Stream
  25762. * @param {string|Object} src url or object of manifest
  25763. * @param {boolean} withCredentials the withCredentials xhr option
  25764. * @class
  25765. */
  25766. class PlaylistLoader extends EventTarget$1 {
  25767. constructor(src, vhs, options = {}) {
  25768. super();
  25769. if (!src) {
  25770. throw new Error('A non-empty playlist URL or object is required');
  25771. }
  25772. this.logger_ = logger('PlaylistLoader');
  25773. const {
  25774. withCredentials = false
  25775. } = options;
  25776. this.src = src;
  25777. this.vhs_ = vhs;
  25778. this.withCredentials = withCredentials;
  25779. const vhsOptions = vhs.options_;
  25780. this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  25781. this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  25782. this.llhls = vhsOptions && vhsOptions.llhls; // initialize the loader state
  25783. this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  25784. this.handleMediaupdatetimeout_ = this.handleMediaupdatetimeout_.bind(this);
  25785. this.on('mediaupdatetimeout', this.handleMediaupdatetimeout_);
  25786. }
  25787. handleMediaupdatetimeout_() {
  25788. if (this.state !== 'HAVE_METADATA') {
  25789. // only refresh the media playlist if no other activity is going on
  25790. return;
  25791. }
  25792. const media = this.media();
  25793. let uri = resolveUrl(this.main.uri, media.uri);
  25794. if (this.llhls) {
  25795. uri = addLLHLSQueryDirectives(uri, media);
  25796. }
  25797. this.state = 'HAVE_CURRENT_METADATA';
  25798. this.request = this.vhs_.xhr({
  25799. uri,
  25800. withCredentials: this.withCredentials
  25801. }, (error, req) => {
  25802. // disposed
  25803. if (!this.request) {
  25804. return;
  25805. }
  25806. if (error) {
  25807. return this.playlistRequestError(this.request, this.media(), 'HAVE_METADATA');
  25808. }
  25809. this.haveMetadata({
  25810. playlistString: this.request.responseText,
  25811. url: this.media().uri,
  25812. id: this.media().id
  25813. });
  25814. });
  25815. }
  25816. playlistRequestError(xhr, playlist, startingState) {
  25817. const {
  25818. uri,
  25819. id
  25820. } = playlist; // any in-flight request is now finished
  25821. this.request = null;
  25822. if (startingState) {
  25823. this.state = startingState;
  25824. }
  25825. this.error = {
  25826. playlist: this.main.playlists[id],
  25827. status: xhr.status,
  25828. message: `HLS playlist request error at URL: ${uri}.`,
  25829. responseText: xhr.responseText,
  25830. code: xhr.status >= 500 ? 4 : 2
  25831. };
  25832. this.trigger('error');
  25833. }
  25834. parseManifest_({
  25835. url,
  25836. manifestString
  25837. }) {
  25838. return parseManifest({
  25839. onwarn: ({
  25840. message
  25841. }) => this.logger_(`m3u8-parser warn for ${url}: ${message}`),
  25842. oninfo: ({
  25843. message
  25844. }) => this.logger_(`m3u8-parser info for ${url}: ${message}`),
  25845. manifestString,
  25846. customTagParsers: this.customTagParsers,
  25847. customTagMappers: this.customTagMappers,
  25848. llhls: this.llhls
  25849. });
  25850. }
  25851. /**
  25852. * Update the playlist loader's state in response to a new or updated playlist.
  25853. *
  25854. * @param {string} [playlistString]
  25855. * Playlist string (if playlistObject is not provided)
  25856. * @param {Object} [playlistObject]
  25857. * Playlist object (if playlistString is not provided)
  25858. * @param {string} url
  25859. * URL of playlist
  25860. * @param {string} id
  25861. * ID to use for playlist
  25862. */
  25863. haveMetadata({
  25864. playlistString,
  25865. playlistObject,
  25866. url,
  25867. id
  25868. }) {
  25869. // any in-flight request is now finished
  25870. this.request = null;
  25871. this.state = 'HAVE_METADATA';
  25872. const playlist = playlistObject || this.parseManifest_({
  25873. url,
  25874. manifestString: playlistString
  25875. });
  25876. playlist.lastRequest = Date.now();
  25877. setupMediaPlaylist({
  25878. playlist,
  25879. uri: url,
  25880. id
  25881. }); // merge this playlist into the main manifest
  25882. const update = updateMain$1(this.main, playlist);
  25883. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  25884. this.pendingMedia_ = null;
  25885. if (update) {
  25886. this.main = update;
  25887. this.media_ = this.main.playlists[id];
  25888. } else {
  25889. this.trigger('playlistunchanged');
  25890. }
  25891. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  25892. this.trigger('loadedplaylist');
  25893. }
  25894. /**
  25895. * Abort any outstanding work and clean up.
  25896. */
  25897. dispose() {
  25898. this.trigger('dispose');
  25899. this.stopRequest();
  25900. window$1.clearTimeout(this.mediaUpdateTimeout);
  25901. window$1.clearTimeout(this.finalRenditionTimeout);
  25902. this.off();
  25903. }
  25904. stopRequest() {
  25905. if (this.request) {
  25906. const oldRequest = this.request;
  25907. this.request = null;
  25908. oldRequest.onreadystatechange = null;
  25909. oldRequest.abort();
  25910. }
  25911. }
  25912. /**
  25913. * When called without any arguments, returns the currently
  25914. * active media playlist. When called with a single argument,
  25915. * triggers the playlist loader to asynchronously switch to the
  25916. * specified media playlist. Calling this method while the
  25917. * loader is in the HAVE_NOTHING causes an error to be emitted
  25918. * but otherwise has no effect.
  25919. *
  25920. * @param {Object=} playlist the parsed media playlist
  25921. * object to switch to
  25922. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  25923. *
  25924. * @return {Playlist} the current loaded media
  25925. */
  25926. media(playlist, shouldDelay) {
  25927. // getter
  25928. if (!playlist) {
  25929. return this.media_;
  25930. } // setter
  25931. if (this.state === 'HAVE_NOTHING') {
  25932. throw new Error('Cannot switch media playlist from ' + this.state);
  25933. } // find the playlist object if the target playlist has been
  25934. // specified by URI
  25935. if (typeof playlist === 'string') {
  25936. if (!this.main.playlists[playlist]) {
  25937. throw new Error('Unknown playlist URI: ' + playlist);
  25938. }
  25939. playlist = this.main.playlists[playlist];
  25940. }
  25941. window$1.clearTimeout(this.finalRenditionTimeout);
  25942. if (shouldDelay) {
  25943. const delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  25944. this.finalRenditionTimeout = window$1.setTimeout(this.media.bind(this, playlist, false), delay);
  25945. return;
  25946. }
  25947. const startingState = this.state;
  25948. const mediaChange = !this.media_ || playlist.id !== this.media_.id;
  25949. const mainPlaylistRef = this.main.playlists[playlist.id]; // switch to fully loaded playlists immediately
  25950. if (mainPlaylistRef && mainPlaylistRef.endList ||
  25951. // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  25952. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  25953. playlist.endList && playlist.segments.length) {
  25954. // abort outstanding playlist requests
  25955. if (this.request) {
  25956. this.request.onreadystatechange = null;
  25957. this.request.abort();
  25958. this.request = null;
  25959. }
  25960. this.state = 'HAVE_METADATA';
  25961. this.media_ = playlist; // trigger media change if the active media has been updated
  25962. if (mediaChange) {
  25963. this.trigger('mediachanging');
  25964. if (startingState === 'HAVE_MAIN_MANIFEST') {
  25965. // The initial playlist was a main manifest, and the first media selected was
  25966. // also provided (in the form of a resolved playlist object) as part of the
  25967. // source object (rather than just a URL). Therefore, since the media playlist
  25968. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  25969. // normal flow, and needs an explicit trigger here.
  25970. this.trigger('loadedmetadata');
  25971. } else {
  25972. this.trigger('mediachange');
  25973. }
  25974. }
  25975. return;
  25976. } // We update/set the timeout here so that live playlists
  25977. // that are not a media change will "start" the loader as expected.
  25978. // We expect that this function will start the media update timeout
  25979. // cycle again. This also prevents a playlist switch failure from
  25980. // causing us to stall during live.
  25981. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  25982. if (!mediaChange) {
  25983. return;
  25984. }
  25985. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  25986. if (this.request) {
  25987. if (playlist.resolvedUri === this.request.url) {
  25988. // requesting to switch to the same playlist multiple times
  25989. // has no effect after the first
  25990. return;
  25991. }
  25992. this.request.onreadystatechange = null;
  25993. this.request.abort();
  25994. this.request = null;
  25995. } // request the new playlist
  25996. if (this.media_) {
  25997. this.trigger('mediachanging');
  25998. }
  25999. this.pendingMedia_ = playlist;
  26000. this.request = this.vhs_.xhr({
  26001. uri: playlist.resolvedUri,
  26002. withCredentials: this.withCredentials
  26003. }, (error, req) => {
  26004. // disposed
  26005. if (!this.request) {
  26006. return;
  26007. }
  26008. playlist.lastRequest = Date.now();
  26009. playlist.resolvedUri = resolveManifestRedirect(playlist.resolvedUri, req);
  26010. if (error) {
  26011. return this.playlistRequestError(this.request, playlist, startingState);
  26012. }
  26013. this.haveMetadata({
  26014. playlistString: req.responseText,
  26015. url: playlist.uri,
  26016. id: playlist.id
  26017. }); // fire loadedmetadata the first time a media playlist is loaded
  26018. if (startingState === 'HAVE_MAIN_MANIFEST') {
  26019. this.trigger('loadedmetadata');
  26020. } else {
  26021. this.trigger('mediachange');
  26022. }
  26023. });
  26024. }
  26025. /**
  26026. * pause loading of the playlist
  26027. */
  26028. pause() {
  26029. if (this.mediaUpdateTimeout) {
  26030. window$1.clearTimeout(this.mediaUpdateTimeout);
  26031. this.mediaUpdateTimeout = null;
  26032. }
  26033. this.stopRequest();
  26034. if (this.state === 'HAVE_NOTHING') {
  26035. // If we pause the loader before any data has been retrieved, its as if we never
  26036. // started, so reset to an unstarted state.
  26037. this.started = false;
  26038. } // Need to restore state now that no activity is happening
  26039. if (this.state === 'SWITCHING_MEDIA') {
  26040. // if the loader was in the process of switching media, it should either return to
  26041. // HAVE_MAIN_MANIFEST or HAVE_METADATA depending on if the loader has loaded a media
  26042. // playlist yet. This is determined by the existence of loader.media_
  26043. if (this.media_) {
  26044. this.state = 'HAVE_METADATA';
  26045. } else {
  26046. this.state = 'HAVE_MAIN_MANIFEST';
  26047. }
  26048. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  26049. this.state = 'HAVE_METADATA';
  26050. }
  26051. }
  26052. /**
  26053. * start loading of the playlist
  26054. */
  26055. load(shouldDelay) {
  26056. if (this.mediaUpdateTimeout) {
  26057. window$1.clearTimeout(this.mediaUpdateTimeout);
  26058. this.mediaUpdateTimeout = null;
  26059. }
  26060. const media = this.media();
  26061. if (shouldDelay) {
  26062. const delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  26063. this.mediaUpdateTimeout = window$1.setTimeout(() => {
  26064. this.mediaUpdateTimeout = null;
  26065. this.load();
  26066. }, delay);
  26067. return;
  26068. }
  26069. if (!this.started) {
  26070. this.start();
  26071. return;
  26072. }
  26073. if (media && !media.endList) {
  26074. this.trigger('mediaupdatetimeout');
  26075. } else {
  26076. this.trigger('loadedplaylist');
  26077. }
  26078. }
  26079. updateMediaUpdateTimeout_(delay) {
  26080. if (this.mediaUpdateTimeout) {
  26081. window$1.clearTimeout(this.mediaUpdateTimeout);
  26082. this.mediaUpdateTimeout = null;
  26083. } // we only have use mediaupdatetimeout for live playlists.
  26084. if (!this.media() || this.media().endList) {
  26085. return;
  26086. }
  26087. this.mediaUpdateTimeout = window$1.setTimeout(() => {
  26088. this.mediaUpdateTimeout = null;
  26089. this.trigger('mediaupdatetimeout');
  26090. this.updateMediaUpdateTimeout_(delay);
  26091. }, delay);
  26092. }
  26093. /**
  26094. * start loading of the playlist
  26095. */
  26096. start() {
  26097. this.started = true;
  26098. if (typeof this.src === 'object') {
  26099. // in the case of an entirely constructed manifest object (meaning there's no actual
  26100. // manifest on a server), default the uri to the page's href
  26101. if (!this.src.uri) {
  26102. this.src.uri = window$1.location.href;
  26103. } // resolvedUri is added on internally after the initial request. Since there's no
  26104. // request for pre-resolved manifests, add on resolvedUri here.
  26105. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  26106. // request can be skipped (since the top level of the manifest, at a minimum, is
  26107. // already available as a parsed manifest object). However, if the manifest object
  26108. // represents a main playlist, some media playlists may need to be resolved before
  26109. // the starting segment list is available. Therefore, go directly to setup of the
  26110. // initial playlist, and let the normal flow continue from there.
  26111. //
  26112. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  26113. // that the first request is asynchronous.
  26114. setTimeout(() => {
  26115. this.setupInitialPlaylist(this.src);
  26116. }, 0);
  26117. return;
  26118. } // request the specified URL
  26119. this.request = this.vhs_.xhr({
  26120. uri: this.src,
  26121. withCredentials: this.withCredentials
  26122. }, (error, req) => {
  26123. // disposed
  26124. if (!this.request) {
  26125. return;
  26126. } // clear the loader's request reference
  26127. this.request = null;
  26128. if (error) {
  26129. this.error = {
  26130. status: req.status,
  26131. message: `HLS playlist request error at URL: ${this.src}.`,
  26132. responseText: req.responseText,
  26133. // MEDIA_ERR_NETWORK
  26134. code: 2
  26135. };
  26136. if (this.state === 'HAVE_NOTHING') {
  26137. this.started = false;
  26138. }
  26139. return this.trigger('error');
  26140. }
  26141. this.src = resolveManifestRedirect(this.src, req);
  26142. const manifest = this.parseManifest_({
  26143. manifestString: req.responseText,
  26144. url: this.src
  26145. });
  26146. this.setupInitialPlaylist(manifest);
  26147. });
  26148. }
  26149. srcUri() {
  26150. return typeof this.src === 'string' ? this.src : this.src.uri;
  26151. }
  26152. /**
  26153. * Given a manifest object that's either a main or media playlist, trigger the proper
  26154. * events and set the state of the playlist loader.
  26155. *
  26156. * If the manifest object represents a main playlist, `loadedplaylist` will be
  26157. * triggered to allow listeners to select a playlist. If none is selected, the loader
  26158. * will default to the first one in the playlists array.
  26159. *
  26160. * If the manifest object represents a media playlist, `loadedplaylist` will be
  26161. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  26162. *
  26163. * In the case of a media playlist, a main playlist object wrapper with one playlist
  26164. * will be created so that all logic can handle playlists in the same fashion (as an
  26165. * assumed manifest object schema).
  26166. *
  26167. * @param {Object} manifest
  26168. * The parsed manifest object
  26169. */
  26170. setupInitialPlaylist(manifest) {
  26171. this.state = 'HAVE_MAIN_MANIFEST';
  26172. if (manifest.playlists) {
  26173. this.main = manifest;
  26174. addPropertiesToMain(this.main, this.srcUri()); // If the initial main playlist has playlists wtih segments already resolved,
  26175. // then resolve URIs in advance, as they are usually done after a playlist request,
  26176. // which may not happen if the playlist is resolved.
  26177. manifest.playlists.forEach(playlist => {
  26178. playlist.segments = getAllSegments(playlist);
  26179. playlist.segments.forEach(segment => {
  26180. resolveSegmentUris(segment, playlist.resolvedUri);
  26181. });
  26182. });
  26183. this.trigger('loadedplaylist');
  26184. if (!this.request) {
  26185. // no media playlist was specifically selected so start
  26186. // from the first listed one
  26187. this.media(this.main.playlists[0]);
  26188. }
  26189. return;
  26190. } // In order to support media playlists passed in as vhs-json, the case where the uri
  26191. // is not provided as part of the manifest should be considered, and an appropriate
  26192. // default used.
  26193. const uri = this.srcUri() || window$1.location.href;
  26194. this.main = mainForMedia(manifest, uri);
  26195. this.haveMetadata({
  26196. playlistObject: manifest,
  26197. url: uri,
  26198. id: this.main.playlists[0].id
  26199. });
  26200. this.trigger('loadedmetadata');
  26201. }
  26202. }
  26203. /**
  26204. * @file xhr.js
  26205. */
  26206. const {
  26207. xhr: videojsXHR
  26208. } = videojs;
  26209. const callbackWrapper = function (request, error, response, callback) {
  26210. const reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  26211. if (!error && reqResponse) {
  26212. request.responseTime = Date.now();
  26213. request.roundTripTime = request.responseTime - request.requestTime;
  26214. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  26215. if (!request.bandwidth) {
  26216. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  26217. }
  26218. }
  26219. if (response.headers) {
  26220. request.responseHeaders = response.headers;
  26221. } // videojs.xhr now uses a specific code on the error
  26222. // object to signal that a request has timed out instead
  26223. // of setting a boolean on the request object
  26224. if (error && error.code === 'ETIMEDOUT') {
  26225. request.timedout = true;
  26226. } // videojs.xhr no longer considers status codes outside of 200 and 0
  26227. // (for file uris) to be errors, but the old XHR did, so emulate that
  26228. // behavior. Status 206 may be used in response to byterange requests.
  26229. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  26230. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  26231. }
  26232. callback(error, request);
  26233. };
  26234. const xhrFactory = function () {
  26235. const xhr = function XhrFunction(options, callback) {
  26236. // Add a default timeout
  26237. options = merge({
  26238. timeout: 45e3
  26239. }, options); // Allow an optional user-specified function to modify the option
  26240. // object before we construct the xhr request
  26241. const beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest;
  26242. if (beforeRequest && typeof beforeRequest === 'function') {
  26243. const newOptions = beforeRequest(options);
  26244. if (newOptions) {
  26245. options = newOptions;
  26246. }
  26247. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  26248. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  26249. const xhrMethod = videojs.Vhs.xhr.original === true ? videojsXHR : videojs.Vhs.xhr;
  26250. const request = xhrMethod(options, function (error, response) {
  26251. return callbackWrapper(request, error, response, callback);
  26252. });
  26253. const originalAbort = request.abort;
  26254. request.abort = function () {
  26255. request.aborted = true;
  26256. return originalAbort.apply(request, arguments);
  26257. };
  26258. request.uri = options.uri;
  26259. request.requestTime = Date.now();
  26260. return request;
  26261. };
  26262. xhr.original = true;
  26263. return xhr;
  26264. };
  26265. /**
  26266. * Turns segment byterange into a string suitable for use in
  26267. * HTTP Range requests
  26268. *
  26269. * @param {Object} byterange - an object with two values defining the start and end
  26270. * of a byte-range
  26271. */
  26272. const byterangeStr = function (byterange) {
  26273. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  26274. // header uses inclusive ranges
  26275. let byterangeEnd;
  26276. const byterangeStart = byterange.offset;
  26277. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  26278. byterangeEnd = window$1.BigInt(byterange.offset) + window$1.BigInt(byterange.length) - window$1.BigInt(1);
  26279. } else {
  26280. byterangeEnd = byterange.offset + byterange.length - 1;
  26281. }
  26282. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  26283. };
  26284. /**
  26285. * Defines headers for use in the xhr request for a particular segment.
  26286. *
  26287. * @param {Object} segment - a simplified copy of the segmentInfo object
  26288. * from SegmentLoader
  26289. */
  26290. const segmentXhrHeaders = function (segment) {
  26291. const headers = {};
  26292. if (segment.byterange) {
  26293. headers.Range = byterangeStr(segment.byterange);
  26294. }
  26295. return headers;
  26296. };
  26297. /**
  26298. * @file bin-utils.js
  26299. */
  26300. /**
  26301. * convert a TimeRange to text
  26302. *
  26303. * @param {TimeRange} range the timerange to use for conversion
  26304. * @param {number} i the iterator on the range to convert
  26305. * @return {string} the range in string format
  26306. */
  26307. const textRange = function (range, i) {
  26308. return range.start(i) + '-' + range.end(i);
  26309. };
  26310. /**
  26311. * format a number as hex string
  26312. *
  26313. * @param {number} e The number
  26314. * @param {number} i the iterator
  26315. * @return {string} the hex formatted number as a string
  26316. */
  26317. const formatHexString = function (e, i) {
  26318. const value = e.toString(16);
  26319. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  26320. };
  26321. const formatAsciiString = function (e) {
  26322. if (e >= 0x20 && e < 0x7e) {
  26323. return String.fromCharCode(e);
  26324. }
  26325. return '.';
  26326. };
  26327. /**
  26328. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  26329. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  26330. *
  26331. * @param {Object} message
  26332. * Object of properties and values to send to the web worker
  26333. * @return {Object}
  26334. * Modified message with TypedArray values expanded
  26335. * @function createTransferableMessage
  26336. */
  26337. const createTransferableMessage = function (message) {
  26338. const transferable = {};
  26339. Object.keys(message).forEach(key => {
  26340. const value = message[key];
  26341. if (isArrayBufferView(value)) {
  26342. transferable[key] = {
  26343. bytes: value.buffer,
  26344. byteOffset: value.byteOffset,
  26345. byteLength: value.byteLength
  26346. };
  26347. } else {
  26348. transferable[key] = value;
  26349. }
  26350. });
  26351. return transferable;
  26352. };
  26353. /**
  26354. * Returns a unique string identifier for a media initialization
  26355. * segment.
  26356. *
  26357. * @param {Object} initSegment
  26358. * the init segment object.
  26359. *
  26360. * @return {string} the generated init segment id
  26361. */
  26362. const initSegmentId = function (initSegment) {
  26363. const byterange = initSegment.byterange || {
  26364. length: Infinity,
  26365. offset: 0
  26366. };
  26367. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  26368. };
  26369. /**
  26370. * Returns a unique string identifier for a media segment key.
  26371. *
  26372. * @param {Object} key the encryption key
  26373. * @return {string} the unique id for the media segment key.
  26374. */
  26375. const segmentKeyId = function (key) {
  26376. return key.resolvedUri;
  26377. };
  26378. /**
  26379. * utils to help dump binary data to the console
  26380. *
  26381. * @param {Array|TypedArray} data
  26382. * data to dump to a string
  26383. *
  26384. * @return {string} the data as a hex string.
  26385. */
  26386. const hexDump = data => {
  26387. const bytes = Array.prototype.slice.call(data);
  26388. const step = 16;
  26389. let result = '';
  26390. let hex;
  26391. let ascii;
  26392. for (let j = 0; j < bytes.length / step; j++) {
  26393. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  26394. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  26395. result += hex + ' ' + ascii + '\n';
  26396. }
  26397. return result;
  26398. };
  26399. const tagDump = ({
  26400. bytes
  26401. }) => hexDump(bytes);
  26402. const textRanges = ranges => {
  26403. let result = '';
  26404. let i;
  26405. for (i = 0; i < ranges.length; i++) {
  26406. result += textRange(ranges, i) + ' ';
  26407. }
  26408. return result;
  26409. };
  26410. var utils = /*#__PURE__*/Object.freeze({
  26411. __proto__: null,
  26412. createTransferableMessage: createTransferableMessage,
  26413. initSegmentId: initSegmentId,
  26414. segmentKeyId: segmentKeyId,
  26415. hexDump: hexDump,
  26416. tagDump: tagDump,
  26417. textRanges: textRanges
  26418. });
  26419. // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  26420. // 25% was arbitrarily chosen, and may need to be refined over time.
  26421. const SEGMENT_END_FUDGE_PERCENT = 0.25;
  26422. /**
  26423. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  26424. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  26425. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  26426. *
  26427. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  26428. * point" (a point where we have a mapping from program time to player time, with player
  26429. * time being the post transmux start of the segment).
  26430. *
  26431. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  26432. *
  26433. * @param {number} playerTime the player time
  26434. * @param {Object} segment the segment which contains the player time
  26435. * @return {Date} program time
  26436. */
  26437. const playerTimeToProgramTime = (playerTime, segment) => {
  26438. if (!segment.dateTimeObject) {
  26439. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  26440. // be used to map the start of a segment with a real world time).
  26441. return null;
  26442. }
  26443. const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  26444. const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  26445. const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  26446. const offsetFromSegmentStart = playerTime - startOfSegment;
  26447. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  26448. };
  26449. const originalSegmentVideoDuration = videoTimingInfo => {
  26450. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  26451. };
  26452. /**
  26453. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  26454. * returned segment might be an estimate or an accurate match.
  26455. *
  26456. * @param {string} programTime The ISO-8601 programTime to find a match for
  26457. * @param {Object} playlist A playlist object to search within
  26458. */
  26459. const findSegmentForProgramTime = (programTime, playlist) => {
  26460. // Assumptions:
  26461. // - verifyProgramDateTimeTags has already been run
  26462. // - live streams have been started
  26463. let dateTimeObject;
  26464. try {
  26465. dateTimeObject = new Date(programTime);
  26466. } catch (e) {
  26467. return null;
  26468. }
  26469. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  26470. return null;
  26471. }
  26472. let segment = playlist.segments[0];
  26473. if (dateTimeObject < segment.dateTimeObject) {
  26474. // Requested time is before stream start.
  26475. return null;
  26476. }
  26477. for (let i = 0; i < playlist.segments.length - 1; i++) {
  26478. segment = playlist.segments[i];
  26479. const nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
  26480. if (dateTimeObject < nextSegmentStart) {
  26481. break;
  26482. }
  26483. }
  26484. const lastSegment = playlist.segments[playlist.segments.length - 1];
  26485. const lastSegmentStart = lastSegment.dateTimeObject;
  26486. const lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  26487. const lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  26488. if (dateTimeObject > lastSegmentEnd) {
  26489. // Beyond the end of the stream, or our best guess of the end of the stream.
  26490. return null;
  26491. }
  26492. if (dateTimeObject > lastSegmentStart) {
  26493. segment = lastSegment;
  26494. }
  26495. return {
  26496. segment,
  26497. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  26498. // Although, given that all segments have accurate date time objects, the segment
  26499. // selected should be accurate, unless the video has been transmuxed at some point
  26500. // (determined by the presence of the videoTimingInfo object), the segment's "player
  26501. // time" (the start time in the player) can't be considered accurate.
  26502. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  26503. };
  26504. };
  26505. /**
  26506. * Finds a segment that contains the given player time(in seconds).
  26507. *
  26508. * @param {number} time The player time to find a match for
  26509. * @param {Object} playlist A playlist object to search within
  26510. */
  26511. const findSegmentForPlayerTime = (time, playlist) => {
  26512. // Assumptions:
  26513. // - there will always be a segment.duration
  26514. // - we can start from zero
  26515. // - segments are in time order
  26516. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  26517. return null;
  26518. }
  26519. let segmentEnd = 0;
  26520. let segment;
  26521. for (let i = 0; i < playlist.segments.length; i++) {
  26522. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  26523. // should contain the most accurate values we have for the segment's player times.
  26524. //
  26525. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  26526. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  26527. // calculate an end value.
  26528. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  26529. if (time <= segmentEnd) {
  26530. break;
  26531. }
  26532. }
  26533. const lastSegment = playlist.segments[playlist.segments.length - 1];
  26534. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  26535. // The time requested is beyond the stream end.
  26536. return null;
  26537. }
  26538. if (time > segmentEnd) {
  26539. // The time is within or beyond the last segment.
  26540. //
  26541. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  26542. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  26543. // Technically, because the duration value is only an estimate, the time may still
  26544. // exist in the last segment, however, there isn't enough information to make even
  26545. // a reasonable estimate.
  26546. return null;
  26547. }
  26548. segment = lastSegment;
  26549. }
  26550. return {
  26551. segment,
  26552. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  26553. // Because videoTimingInfo is only set after transmux, it is the only way to get
  26554. // accurate timing values.
  26555. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  26556. };
  26557. };
  26558. /**
  26559. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  26560. * If the offset returned is positive, the programTime occurs after the
  26561. * comparisonTimestamp.
  26562. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  26563. *
  26564. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  26565. * @param {string} programTime The programTime as an ISO-8601 string
  26566. * @return {number} offset
  26567. */
  26568. const getOffsetFromTimestamp = (comparisonTimeStamp, programTime) => {
  26569. let segmentDateTime;
  26570. let programDateTime;
  26571. try {
  26572. segmentDateTime = new Date(comparisonTimeStamp);
  26573. programDateTime = new Date(programTime);
  26574. } catch (e) {// TODO handle error
  26575. }
  26576. const segmentTimeEpoch = segmentDateTime.getTime();
  26577. const programTimeEpoch = programDateTime.getTime();
  26578. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  26579. };
  26580. /**
  26581. * Checks that all segments in this playlist have programDateTime tags.
  26582. *
  26583. * @param {Object} playlist A playlist object
  26584. */
  26585. const verifyProgramDateTimeTags = playlist => {
  26586. if (!playlist.segments || playlist.segments.length === 0) {
  26587. return false;
  26588. }
  26589. for (let i = 0; i < playlist.segments.length; i++) {
  26590. const segment = playlist.segments[i];
  26591. if (!segment.dateTimeObject) {
  26592. return false;
  26593. }
  26594. }
  26595. return true;
  26596. };
  26597. /**
  26598. * Returns the programTime of the media given a playlist and a playerTime.
  26599. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  26600. * If the segments containing the time requested have not been buffered yet, an estimate
  26601. * may be returned to the callback.
  26602. *
  26603. * @param {Object} args
  26604. * @param {Object} args.playlist A playlist object to search within
  26605. * @param {number} time A playerTime in seconds
  26606. * @param {Function} callback(err, programTime)
  26607. * @return {string} err.message A detailed error message
  26608. * @return {Object} programTime
  26609. * @return {number} programTime.mediaSeconds The streamTime in seconds
  26610. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  26611. */
  26612. const getProgramTime = ({
  26613. playlist,
  26614. time = undefined,
  26615. callback
  26616. }) => {
  26617. if (!callback) {
  26618. throw new Error('getProgramTime: callback must be provided');
  26619. }
  26620. if (!playlist || time === undefined) {
  26621. return callback({
  26622. message: 'getProgramTime: playlist and time must be provided'
  26623. });
  26624. }
  26625. const matchedSegment = findSegmentForPlayerTime(time, playlist);
  26626. if (!matchedSegment) {
  26627. return callback({
  26628. message: 'valid programTime was not found'
  26629. });
  26630. }
  26631. if (matchedSegment.type === 'estimate') {
  26632. return callback({
  26633. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  26634. seekTime: matchedSegment.estimatedStart
  26635. });
  26636. }
  26637. const programTimeObject = {
  26638. mediaSeconds: time
  26639. };
  26640. const programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  26641. if (programTime) {
  26642. programTimeObject.programDateTime = programTime.toISOString();
  26643. }
  26644. return callback(null, programTimeObject);
  26645. };
  26646. /**
  26647. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  26648. *
  26649. * @param {Object} args
  26650. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  26651. * @param {Object} args.playlist A playlist to look within
  26652. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  26653. * @param {Function} args.seekTo A method to perform a seek
  26654. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  26655. * @param {Object} args.tech The tech to seek on
  26656. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  26657. * @return {string} err.message A detailed error message
  26658. * @return {number} newTime The exact time that was seeked to in seconds
  26659. */
  26660. const seekToProgramTime = ({
  26661. programTime,
  26662. playlist,
  26663. retryCount = 2,
  26664. seekTo,
  26665. pauseAfterSeek = true,
  26666. tech,
  26667. callback
  26668. }) => {
  26669. if (!callback) {
  26670. throw new Error('seekToProgramTime: callback must be provided');
  26671. }
  26672. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  26673. return callback({
  26674. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  26675. });
  26676. }
  26677. if (!playlist.endList && !tech.hasStarted_) {
  26678. return callback({
  26679. message: 'player must be playing a live stream to start buffering'
  26680. });
  26681. }
  26682. if (!verifyProgramDateTimeTags(playlist)) {
  26683. return callback({
  26684. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  26685. });
  26686. }
  26687. const matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  26688. if (!matchedSegment) {
  26689. return callback({
  26690. message: `${programTime} was not found in the stream`
  26691. });
  26692. }
  26693. const segment = matchedSegment.segment;
  26694. const mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  26695. if (matchedSegment.type === 'estimate') {
  26696. // we've run out of retries
  26697. if (retryCount === 0) {
  26698. return callback({
  26699. message: `${programTime} is not buffered yet. Try again`
  26700. });
  26701. }
  26702. seekTo(matchedSegment.estimatedStart + mediaOffset);
  26703. tech.one('seeked', () => {
  26704. seekToProgramTime({
  26705. programTime,
  26706. playlist,
  26707. retryCount: retryCount - 1,
  26708. seekTo,
  26709. pauseAfterSeek,
  26710. tech,
  26711. callback
  26712. });
  26713. });
  26714. return;
  26715. } // Since the segment.start value is determined from the buffered end or ending time
  26716. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  26717. // modifications.
  26718. const seekToTime = segment.start + mediaOffset;
  26719. const seekedCallback = () => {
  26720. return callback(null, tech.currentTime());
  26721. }; // listen for seeked event
  26722. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  26723. if (pauseAfterSeek) {
  26724. tech.pause();
  26725. }
  26726. seekTo(seekToTime);
  26727. };
  26728. // which will only happen if the request is complete.
  26729. const callbackOnCompleted = (request, cb) => {
  26730. if (request.readyState === 4) {
  26731. return cb();
  26732. }
  26733. return;
  26734. };
  26735. const containerRequest = (uri, xhr, cb) => {
  26736. let bytes = [];
  26737. let id3Offset;
  26738. let finished = false;
  26739. const endRequestAndCallback = function (err, req, type, _bytes) {
  26740. req.abort();
  26741. finished = true;
  26742. return cb(err, req, type, _bytes);
  26743. };
  26744. const progressListener = function (error, request) {
  26745. if (finished) {
  26746. return;
  26747. }
  26748. if (error) {
  26749. return endRequestAndCallback(error, request, '', bytes);
  26750. } // grap the new part of content that was just downloaded
  26751. const newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  26752. bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
  26753. id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
  26754. // or we need at least two bytes after an id3Offset
  26755. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  26756. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  26757. }
  26758. const type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  26759. // to see the second sync byte, wait until we have enough data
  26760. // before declaring it ts
  26761. if (type === 'ts' && bytes.length < 188) {
  26762. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  26763. } // this may be an unsynced ts segment
  26764. // wait for 376 bytes before detecting no container
  26765. if (!type && bytes.length < 376) {
  26766. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  26767. }
  26768. return endRequestAndCallback(null, request, type, bytes);
  26769. };
  26770. const options = {
  26771. uri,
  26772. beforeSend(request) {
  26773. // this forces the browser to pass the bytes to us unprocessed
  26774. request.overrideMimeType('text/plain; charset=x-user-defined');
  26775. request.addEventListener('progress', function ({
  26776. total,
  26777. loaded
  26778. }) {
  26779. return callbackWrapper(request, null, {
  26780. statusCode: request.status
  26781. }, progressListener);
  26782. });
  26783. }
  26784. };
  26785. const request = xhr(options, function (error, response) {
  26786. return callbackWrapper(request, error, response, progressListener);
  26787. });
  26788. return request;
  26789. };
  26790. const {
  26791. EventTarget
  26792. } = videojs;
  26793. const dashPlaylistUnchanged = function (a, b) {
  26794. if (!isPlaylistUnchanged(a, b)) {
  26795. return false;
  26796. } // for dash the above check will often return true in scenarios where
  26797. // the playlist actually has changed because mediaSequence isn't a
  26798. // dash thing, and we often set it to 1. So if the playlists have the same amount
  26799. // of segments we return true.
  26800. // So for dash we need to make sure that the underlying segments are different.
  26801. // if sidx changed then the playlists are different.
  26802. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  26803. return false;
  26804. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  26805. return false;
  26806. } // one or the other does not have segments
  26807. // there was a change.
  26808. if (a.segments && !b.segments || !a.segments && b.segments) {
  26809. return false;
  26810. } // neither has segments nothing changed
  26811. if (!a.segments && !b.segments) {
  26812. return true;
  26813. } // check segments themselves
  26814. for (let i = 0; i < a.segments.length; i++) {
  26815. const aSegment = a.segments[i];
  26816. const bSegment = b.segments[i]; // if uris are different between segments there was a change
  26817. if (aSegment.uri !== bSegment.uri) {
  26818. return false;
  26819. } // neither segment has a byterange, there will be no byterange change.
  26820. if (!aSegment.byterange && !bSegment.byterange) {
  26821. continue;
  26822. }
  26823. const aByterange = aSegment.byterange;
  26824. const bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  26825. if (aByterange && !bByterange || !aByterange && bByterange) {
  26826. return false;
  26827. } // if both segments have byterange with different offsets, there was a change.
  26828. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  26829. return false;
  26830. }
  26831. } // if everything was the same with segments, this is the same playlist.
  26832. return true;
  26833. };
  26834. /**
  26835. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  26836. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  26837. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  26838. * periods without continuous playback this function may need modification as well as the parser.
  26839. */
  26840. const dashGroupId = (type, group, label, playlist) => {
  26841. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  26842. const playlistId = playlist.attributes.NAME || label;
  26843. return `placeholder-uri-${type}-${group}-${playlistId}`;
  26844. };
  26845. /**
  26846. * Parses the main XML string and updates playlist URI references.
  26847. *
  26848. * @param {Object} config
  26849. * Object of arguments
  26850. * @param {string} config.mainXml
  26851. * The mpd XML
  26852. * @param {string} config.srcUrl
  26853. * The mpd URL
  26854. * @param {Date} config.clientOffset
  26855. * A time difference between server and client
  26856. * @param {Object} config.sidxMapping
  26857. * SIDX mappings for moof/mdat URIs and byte ranges
  26858. * @return {Object}
  26859. * The parsed mpd manifest object
  26860. */
  26861. const parseMainXml = ({
  26862. mainXml,
  26863. srcUrl,
  26864. clientOffset,
  26865. sidxMapping,
  26866. previousManifest
  26867. }) => {
  26868. const manifest = parse(mainXml, {
  26869. manifestUri: srcUrl,
  26870. clientOffset,
  26871. sidxMapping,
  26872. previousManifest
  26873. });
  26874. addPropertiesToMain(manifest, srcUrl, dashGroupId);
  26875. return manifest;
  26876. };
  26877. /**
  26878. * Removes any mediaGroup labels that no longer exist in the newMain
  26879. *
  26880. * @param {Object} update
  26881. * The previous mpd object being updated
  26882. * @param {Object} newMain
  26883. * The new mpd object
  26884. */
  26885. const removeOldMediaGroupLabels = (update, newMain) => {
  26886. forEachMediaGroup(update, (properties, type, group, label) => {
  26887. if (!(label in newMain.mediaGroups[type][group])) {
  26888. delete update.mediaGroups[type][group][label];
  26889. }
  26890. });
  26891. };
  26892. /**
  26893. * Returns a new main manifest that is the result of merging an updated main manifest
  26894. * into the original version.
  26895. *
  26896. * @param {Object} oldMain
  26897. * The old parsed mpd object
  26898. * @param {Object} newMain
  26899. * The updated parsed mpd object
  26900. * @return {Object}
  26901. * A new object representing the original main manifest with the updated media
  26902. * playlists merged in
  26903. */
  26904. const updateMain = (oldMain, newMain, sidxMapping) => {
  26905. let noChanges = true;
  26906. let update = merge(oldMain, {
  26907. // These are top level properties that can be updated
  26908. duration: newMain.duration,
  26909. minimumUpdatePeriod: newMain.minimumUpdatePeriod,
  26910. timelineStarts: newMain.timelineStarts
  26911. }); // First update the playlists in playlist list
  26912. for (let i = 0; i < newMain.playlists.length; i++) {
  26913. const playlist = newMain.playlists[i];
  26914. if (playlist.sidx) {
  26915. const sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  26916. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  26917. addSidxSegmentsToPlaylist(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  26918. }
  26919. }
  26920. const playlistUpdate = updateMain$1(update, playlist, dashPlaylistUnchanged);
  26921. if (playlistUpdate) {
  26922. update = playlistUpdate;
  26923. noChanges = false;
  26924. }
  26925. } // Then update media group playlists
  26926. forEachMediaGroup(newMain, (properties, type, group, label) => {
  26927. if (properties.playlists && properties.playlists.length) {
  26928. const id = properties.playlists[0].id;
  26929. const playlistUpdate = updateMain$1(update, properties.playlists[0], dashPlaylistUnchanged);
  26930. if (playlistUpdate) {
  26931. update = playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  26932. if (!(label in update.mediaGroups[type][group])) {
  26933. update.mediaGroups[type][group][label] = properties;
  26934. } // update the playlist reference within media groups
  26935. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  26936. noChanges = false;
  26937. }
  26938. }
  26939. }); // remove mediaGroup labels and references that no longer exist in the newMain
  26940. removeOldMediaGroupLabels(update, newMain);
  26941. if (newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  26942. noChanges = false;
  26943. }
  26944. if (noChanges) {
  26945. return null;
  26946. }
  26947. return update;
  26948. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  26949. // If the SIDXs have maps, the two maps should match,
  26950. // both `a` and `b` missing SIDXs is considered matching.
  26951. // If `a` or `b` but not both have a map, they aren't matching.
  26952. const equivalentSidx = (a, b) => {
  26953. const neitherMap = Boolean(!a.map && !b.map);
  26954. const equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  26955. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  26956. }; // exported for testing
  26957. const compareSidxEntry = (playlists, oldSidxMapping) => {
  26958. const newSidxMapping = {};
  26959. for (const id in playlists) {
  26960. const playlist = playlists[id];
  26961. const currentSidxInfo = playlist.sidx;
  26962. if (currentSidxInfo) {
  26963. const key = generateSidxKey(currentSidxInfo);
  26964. if (!oldSidxMapping[key]) {
  26965. break;
  26966. }
  26967. const savedSidxInfo = oldSidxMapping[key].sidxInfo;
  26968. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  26969. newSidxMapping[key] = oldSidxMapping[key];
  26970. }
  26971. }
  26972. }
  26973. return newSidxMapping;
  26974. };
  26975. /**
  26976. * A function that filters out changed items as they need to be requested separately.
  26977. *
  26978. * The method is exported for testing
  26979. *
  26980. * @param {Object} main the parsed mpd XML returned via mpd-parser
  26981. * @param {Object} oldSidxMapping the SIDX to compare against
  26982. */
  26983. const filterChangedSidxMappings = (main, oldSidxMapping) => {
  26984. const videoSidx = compareSidxEntry(main.playlists, oldSidxMapping);
  26985. let mediaGroupSidx = videoSidx;
  26986. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  26987. if (properties.playlists && properties.playlists.length) {
  26988. const playlists = properties.playlists;
  26989. mediaGroupSidx = merge(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  26990. }
  26991. });
  26992. return mediaGroupSidx;
  26993. };
  26994. class DashPlaylistLoader extends EventTarget {
  26995. // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  26996. // playlist loader setups from media groups will expect to be able to pass a playlist
  26997. // (since there aren't external URLs to media playlists with DASH)
  26998. constructor(srcUrlOrPlaylist, vhs, options = {}, mainPlaylistLoader) {
  26999. super();
  27000. this.mainPlaylistLoader_ = mainPlaylistLoader || this;
  27001. if (!mainPlaylistLoader) {
  27002. this.isMain_ = true;
  27003. }
  27004. const {
  27005. withCredentials = false
  27006. } = options;
  27007. this.vhs_ = vhs;
  27008. this.withCredentials = withCredentials;
  27009. if (!srcUrlOrPlaylist) {
  27010. throw new Error('A non-empty playlist URL or object is required');
  27011. } // event naming?
  27012. this.on('minimumUpdatePeriod', () => {
  27013. this.refreshXml_();
  27014. }); // live playlist staleness timeout
  27015. this.on('mediaupdatetimeout', () => {
  27016. this.refreshMedia_(this.media().id);
  27017. });
  27018. this.state = 'HAVE_NOTHING';
  27019. this.loadedPlaylists_ = {};
  27020. this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  27021. // The mainPlaylistLoader will be created with a string
  27022. if (this.isMain_) {
  27023. this.mainPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  27024. // once multi-period is refactored
  27025. this.mainPlaylistLoader_.sidxMapping_ = {};
  27026. } else {
  27027. this.childPlaylist_ = srcUrlOrPlaylist;
  27028. }
  27029. }
  27030. requestErrored_(err, request, startingState) {
  27031. // disposed
  27032. if (!this.request) {
  27033. return true;
  27034. } // pending request is cleared
  27035. this.request = null;
  27036. if (err) {
  27037. // use the provided error object or create one
  27038. // based on the request/response
  27039. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  27040. status: request.status,
  27041. message: 'DASH request error at URL: ' + request.uri,
  27042. response: request.response,
  27043. // MEDIA_ERR_NETWORK
  27044. code: 2
  27045. };
  27046. if (startingState) {
  27047. this.state = startingState;
  27048. }
  27049. this.trigger('error');
  27050. return true;
  27051. }
  27052. }
  27053. /**
  27054. * Verify that the container of the sidx segment can be parsed
  27055. * and if it can, get and parse that segment.
  27056. */
  27057. addSidxSegments_(playlist, startingState, cb) {
  27058. const sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  27059. if (!playlist.sidx || !sidxKey || this.mainPlaylistLoader_.sidxMapping_[sidxKey]) {
  27060. // keep this function async
  27061. this.mediaRequest_ = window$1.setTimeout(() => cb(false), 0);
  27062. return;
  27063. } // resolve the segment URL relative to the playlist
  27064. const uri = resolveManifestRedirect(playlist.sidx.resolvedUri);
  27065. const fin = (err, request) => {
  27066. if (this.requestErrored_(err, request, startingState)) {
  27067. return;
  27068. }
  27069. const sidxMapping = this.mainPlaylistLoader_.sidxMapping_;
  27070. let sidx;
  27071. try {
  27072. sidx = parseSidx(toUint8(request.response).subarray(8));
  27073. } catch (e) {
  27074. // sidx parsing failed.
  27075. this.requestErrored_(e, request, startingState);
  27076. return;
  27077. }
  27078. sidxMapping[sidxKey] = {
  27079. sidxInfo: playlist.sidx,
  27080. sidx
  27081. };
  27082. addSidxSegmentsToPlaylist(playlist, sidx, playlist.sidx.resolvedUri);
  27083. return cb(true);
  27084. };
  27085. this.request = containerRequest(uri, this.vhs_.xhr, (err, request, container, bytes) => {
  27086. if (err) {
  27087. return fin(err, request);
  27088. }
  27089. if (!container || container !== 'mp4') {
  27090. return fin({
  27091. status: request.status,
  27092. message: `Unsupported ${container || 'unknown'} container type for sidx segment at URL: ${uri}`,
  27093. // response is just bytes in this case
  27094. // but we really don't want to return that.
  27095. response: '',
  27096. playlist,
  27097. internal: true,
  27098. playlistExclusionDuration: Infinity,
  27099. // MEDIA_ERR_NETWORK
  27100. code: 2
  27101. }, request);
  27102. } // if we already downloaded the sidx bytes in the container request, use them
  27103. const {
  27104. offset,
  27105. length
  27106. } = playlist.sidx.byterange;
  27107. if (bytes.length >= length + offset) {
  27108. return fin(err, {
  27109. response: bytes.subarray(offset, offset + length),
  27110. status: request.status,
  27111. uri: request.uri
  27112. });
  27113. } // otherwise request sidx bytes
  27114. this.request = this.vhs_.xhr({
  27115. uri,
  27116. responseType: 'arraybuffer',
  27117. headers: segmentXhrHeaders({
  27118. byterange: playlist.sidx.byterange
  27119. })
  27120. }, fin);
  27121. });
  27122. }
  27123. dispose() {
  27124. this.trigger('dispose');
  27125. this.stopRequest();
  27126. this.loadedPlaylists_ = {};
  27127. window$1.clearTimeout(this.minimumUpdatePeriodTimeout_);
  27128. window$1.clearTimeout(this.mediaRequest_);
  27129. window$1.clearTimeout(this.mediaUpdateTimeout);
  27130. this.mediaUpdateTimeout = null;
  27131. this.mediaRequest_ = null;
  27132. this.minimumUpdatePeriodTimeout_ = null;
  27133. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  27134. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  27135. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  27136. }
  27137. this.off();
  27138. }
  27139. hasPendingRequest() {
  27140. return this.request || this.mediaRequest_;
  27141. }
  27142. stopRequest() {
  27143. if (this.request) {
  27144. const oldRequest = this.request;
  27145. this.request = null;
  27146. oldRequest.onreadystatechange = null;
  27147. oldRequest.abort();
  27148. }
  27149. }
  27150. media(playlist) {
  27151. // getter
  27152. if (!playlist) {
  27153. return this.media_;
  27154. } // setter
  27155. if (this.state === 'HAVE_NOTHING') {
  27156. throw new Error('Cannot switch media playlist from ' + this.state);
  27157. }
  27158. const startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  27159. if (typeof playlist === 'string') {
  27160. if (!this.mainPlaylistLoader_.main.playlists[playlist]) {
  27161. throw new Error('Unknown playlist URI: ' + playlist);
  27162. }
  27163. playlist = this.mainPlaylistLoader_.main.playlists[playlist];
  27164. }
  27165. const mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  27166. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  27167. this.state = 'HAVE_METADATA';
  27168. this.media_ = playlist; // trigger media change if the active media has been updated
  27169. if (mediaChange) {
  27170. this.trigger('mediachanging');
  27171. this.trigger('mediachange');
  27172. }
  27173. return;
  27174. } // switching to the active playlist is a no-op
  27175. if (!mediaChange) {
  27176. return;
  27177. } // switching from an already loaded playlist
  27178. if (this.media_) {
  27179. this.trigger('mediachanging');
  27180. }
  27181. this.addSidxSegments_(playlist, startingState, sidxChanged => {
  27182. // everything is ready just continue to haveMetadata
  27183. this.haveMetadata({
  27184. startingState,
  27185. playlist
  27186. });
  27187. });
  27188. }
  27189. haveMetadata({
  27190. startingState,
  27191. playlist
  27192. }) {
  27193. this.state = 'HAVE_METADATA';
  27194. this.loadedPlaylists_[playlist.id] = playlist;
  27195. this.mediaRequest_ = null; // This will trigger loadedplaylist
  27196. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  27197. // to resolve setup of media groups
  27198. if (startingState === 'HAVE_MAIN_MANIFEST') {
  27199. this.trigger('loadedmetadata');
  27200. } else {
  27201. // trigger media change if the active media has been updated
  27202. this.trigger('mediachange');
  27203. }
  27204. }
  27205. pause() {
  27206. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  27207. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  27208. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  27209. }
  27210. this.stopRequest();
  27211. window$1.clearTimeout(this.mediaUpdateTimeout);
  27212. this.mediaUpdateTimeout = null;
  27213. if (this.isMain_) {
  27214. window$1.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_);
  27215. this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  27216. }
  27217. if (this.state === 'HAVE_NOTHING') {
  27218. // If we pause the loader before any data has been retrieved, its as if we never
  27219. // started, so reset to an unstarted state.
  27220. this.started = false;
  27221. }
  27222. }
  27223. load(isFinalRendition) {
  27224. window$1.clearTimeout(this.mediaUpdateTimeout);
  27225. this.mediaUpdateTimeout = null;
  27226. const media = this.media();
  27227. if (isFinalRendition) {
  27228. const delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  27229. this.mediaUpdateTimeout = window$1.setTimeout(() => this.load(), delay);
  27230. return;
  27231. } // because the playlists are internal to the manifest, load should either load the
  27232. // main manifest, or do nothing but trigger an event
  27233. if (!this.started) {
  27234. this.start();
  27235. return;
  27236. }
  27237. if (media && !media.endList) {
  27238. // Check to see if this is the main loader and the MUP was cleared (this happens
  27239. // when the loader was paused). `media` should be set at this point since one is always
  27240. // set during `start()`.
  27241. if (this.isMain_ && !this.minimumUpdatePeriodTimeout_) {
  27242. // Trigger minimumUpdatePeriod to refresh the main manifest
  27243. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  27244. this.updateMinimumUpdatePeriodTimeout_();
  27245. }
  27246. this.trigger('mediaupdatetimeout');
  27247. } else {
  27248. this.trigger('loadedplaylist');
  27249. }
  27250. }
  27251. start() {
  27252. this.started = true; // We don't need to request the main manifest again
  27253. // Call this asynchronously to match the xhr request behavior below
  27254. if (!this.isMain_) {
  27255. this.mediaRequest_ = window$1.setTimeout(() => this.haveMain_(), 0);
  27256. return;
  27257. }
  27258. this.requestMain_((req, mainChanged) => {
  27259. this.haveMain_();
  27260. if (!this.hasPendingRequest() && !this.media_) {
  27261. this.media(this.mainPlaylistLoader_.main.playlists[0]);
  27262. }
  27263. });
  27264. }
  27265. requestMain_(cb) {
  27266. this.request = this.vhs_.xhr({
  27267. uri: this.mainPlaylistLoader_.srcUrl,
  27268. withCredentials: this.withCredentials
  27269. }, (error, req) => {
  27270. if (this.requestErrored_(error, req)) {
  27271. if (this.state === 'HAVE_NOTHING') {
  27272. this.started = false;
  27273. }
  27274. return;
  27275. }
  27276. const mainChanged = req.responseText !== this.mainPlaylistLoader_.mainXml_;
  27277. this.mainPlaylistLoader_.mainXml_ = req.responseText;
  27278. if (req.responseHeaders && req.responseHeaders.date) {
  27279. this.mainLoaded_ = Date.parse(req.responseHeaders.date);
  27280. } else {
  27281. this.mainLoaded_ = Date.now();
  27282. }
  27283. this.mainPlaylistLoader_.srcUrl = resolveManifestRedirect(this.mainPlaylistLoader_.srcUrl, req);
  27284. if (mainChanged) {
  27285. this.handleMain_();
  27286. this.syncClientServerClock_(() => {
  27287. return cb(req, mainChanged);
  27288. });
  27289. return;
  27290. }
  27291. return cb(req, mainChanged);
  27292. });
  27293. }
  27294. /**
  27295. * Parses the main xml for UTCTiming node to sync the client clock to the server
  27296. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  27297. *
  27298. * @param {Function} done
  27299. * Function to call when clock sync has completed
  27300. */
  27301. syncClientServerClock_(done) {
  27302. const utcTiming = parseUTCTiming(this.mainPlaylistLoader_.mainXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  27303. // server clock
  27304. if (utcTiming === null) {
  27305. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  27306. return done();
  27307. }
  27308. if (utcTiming.method === 'DIRECT') {
  27309. this.mainPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  27310. return done();
  27311. }
  27312. this.request = this.vhs_.xhr({
  27313. uri: resolveUrl(this.mainPlaylistLoader_.srcUrl, utcTiming.value),
  27314. method: utcTiming.method,
  27315. withCredentials: this.withCredentials
  27316. }, (error, req) => {
  27317. // disposed
  27318. if (!this.request) {
  27319. return;
  27320. }
  27321. if (error) {
  27322. // sync request failed, fall back to using date header from mpd
  27323. // TODO: log warning
  27324. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  27325. return done();
  27326. }
  27327. let serverTime;
  27328. if (utcTiming.method === 'HEAD') {
  27329. if (!req.responseHeaders || !req.responseHeaders.date) {
  27330. // expected date header not preset, fall back to using date header from mpd
  27331. // TODO: log warning
  27332. serverTime = this.mainLoaded_;
  27333. } else {
  27334. serverTime = Date.parse(req.responseHeaders.date);
  27335. }
  27336. } else {
  27337. serverTime = Date.parse(req.responseText);
  27338. }
  27339. this.mainPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  27340. done();
  27341. });
  27342. }
  27343. haveMain_() {
  27344. this.state = 'HAVE_MAIN_MANIFEST';
  27345. if (this.isMain_) {
  27346. // We have the main playlist at this point, so
  27347. // trigger this to allow PlaylistController
  27348. // to make an initial playlist selection
  27349. this.trigger('loadedplaylist');
  27350. } else if (!this.media_) {
  27351. // no media playlist was specifically selected so select
  27352. // the one the child playlist loader was created with
  27353. this.media(this.childPlaylist_);
  27354. }
  27355. }
  27356. handleMain_() {
  27357. // clear media request
  27358. this.mediaRequest_ = null;
  27359. const oldMain = this.mainPlaylistLoader_.main;
  27360. let newMain = parseMainXml({
  27361. mainXml: this.mainPlaylistLoader_.mainXml_,
  27362. srcUrl: this.mainPlaylistLoader_.srcUrl,
  27363. clientOffset: this.mainPlaylistLoader_.clientOffset_,
  27364. sidxMapping: this.mainPlaylistLoader_.sidxMapping_,
  27365. previousManifest: oldMain
  27366. }); // if we have an old main to compare the new main against
  27367. if (oldMain) {
  27368. newMain = updateMain(oldMain, newMain, this.mainPlaylistLoader_.sidxMapping_);
  27369. } // only update main if we have a new main
  27370. this.mainPlaylistLoader_.main = newMain ? newMain : oldMain;
  27371. const location = this.mainPlaylistLoader_.main.locations && this.mainPlaylistLoader_.main.locations[0];
  27372. if (location && location !== this.mainPlaylistLoader_.srcUrl) {
  27373. this.mainPlaylistLoader_.srcUrl = location;
  27374. }
  27375. if (!oldMain || newMain && newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  27376. this.updateMinimumUpdatePeriodTimeout_();
  27377. }
  27378. return Boolean(newMain);
  27379. }
  27380. updateMinimumUpdatePeriodTimeout_() {
  27381. const mpl = this.mainPlaylistLoader_; // cancel any pending creation of mup on media
  27382. // a new one will be added if needed.
  27383. if (mpl.createMupOnMedia_) {
  27384. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  27385. mpl.createMupOnMedia_ = null;
  27386. } // clear any pending timeouts
  27387. if (mpl.minimumUpdatePeriodTimeout_) {
  27388. window$1.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  27389. mpl.minimumUpdatePeriodTimeout_ = null;
  27390. }
  27391. let mup = mpl.main && mpl.main.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  27392. // MPD has no future validity, so a new one will need to be acquired when new
  27393. // media segments are to be made available. Thus, we use the target duration
  27394. // in this case
  27395. if (mup === 0) {
  27396. if (mpl.media()) {
  27397. mup = mpl.media().targetDuration * 1000;
  27398. } else {
  27399. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  27400. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  27401. }
  27402. } // if minimumUpdatePeriod is invalid or <= zero, which
  27403. // can happen when a live video becomes VOD. skip timeout
  27404. // creation.
  27405. if (typeof mup !== 'number' || mup <= 0) {
  27406. if (mup < 0) {
  27407. this.logger_(`found invalid minimumUpdatePeriod of ${mup}, not setting a timeout`);
  27408. }
  27409. return;
  27410. }
  27411. this.createMUPTimeout_(mup);
  27412. }
  27413. createMUPTimeout_(mup) {
  27414. const mpl = this.mainPlaylistLoader_;
  27415. mpl.minimumUpdatePeriodTimeout_ = window$1.setTimeout(() => {
  27416. mpl.minimumUpdatePeriodTimeout_ = null;
  27417. mpl.trigger('minimumUpdatePeriod');
  27418. mpl.createMUPTimeout_(mup);
  27419. }, mup);
  27420. }
  27421. /**
  27422. * Sends request to refresh the main xml and updates the parsed main manifest
  27423. */
  27424. refreshXml_() {
  27425. this.requestMain_((req, mainChanged) => {
  27426. if (!mainChanged) {
  27427. return;
  27428. }
  27429. if (this.media_) {
  27430. this.media_ = this.mainPlaylistLoader_.main.playlists[this.media_.id];
  27431. } // This will filter out updated sidx info from the mapping
  27432. this.mainPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.sidxMapping_);
  27433. this.addSidxSegments_(this.media(), this.state, sidxChanged => {
  27434. // TODO: do we need to reload the current playlist?
  27435. this.refreshMedia_(this.media().id);
  27436. });
  27437. });
  27438. }
  27439. /**
  27440. * Refreshes the media playlist by re-parsing the main xml and updating playlist
  27441. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  27442. * from the main loader.
  27443. */
  27444. refreshMedia_(mediaID) {
  27445. if (!mediaID) {
  27446. throw new Error('refreshMedia_ must take a media id');
  27447. } // for main we have to reparse the main xml
  27448. // to re-create segments based on current timing values
  27449. // which may change media. We only skip updating the main manifest
  27450. // if this is the first time this.media_ is being set.
  27451. // as main was just parsed in that case.
  27452. if (this.media_ && this.isMain_) {
  27453. this.handleMain_();
  27454. }
  27455. const playlists = this.mainPlaylistLoader_.main.playlists;
  27456. const mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  27457. if (mediaChanged) {
  27458. this.media_ = playlists[mediaID];
  27459. } else {
  27460. this.trigger('playlistunchanged');
  27461. }
  27462. if (!this.mediaUpdateTimeout) {
  27463. const createMediaUpdateTimeout = () => {
  27464. if (this.media().endList) {
  27465. return;
  27466. }
  27467. this.mediaUpdateTimeout = window$1.setTimeout(() => {
  27468. this.trigger('mediaupdatetimeout');
  27469. createMediaUpdateTimeout();
  27470. }, refreshDelay(this.media(), Boolean(mediaChanged)));
  27471. };
  27472. createMediaUpdateTimeout();
  27473. }
  27474. this.trigger('loadedplaylist');
  27475. }
  27476. }
  27477. var Config = {
  27478. GOAL_BUFFER_LENGTH: 30,
  27479. MAX_GOAL_BUFFER_LENGTH: 60,
  27480. BACK_BUFFER_LENGTH: 30,
  27481. GOAL_BUFFER_LENGTH_RATE: 1,
  27482. // 0.5 MB/s
  27483. INITIAL_BANDWIDTH: 4194304,
  27484. // A fudge factor to apply to advertised playlist bitrates to account for
  27485. // temporary flucations in client bandwidth
  27486. BANDWIDTH_VARIANCE: 1.2,
  27487. // How much of the buffer must be filled before we consider upswitching
  27488. BUFFER_LOW_WATER_LINE: 0,
  27489. MAX_BUFFER_LOW_WATER_LINE: 30,
  27490. // TODO: Remove this when experimentalBufferBasedABR is removed
  27491. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  27492. BUFFER_LOW_WATER_LINE_RATE: 1,
  27493. // If the buffer is greater than the high water line, we won't switch down
  27494. BUFFER_HIGH_WATER_LINE: 30
  27495. };
  27496. const stringToArrayBuffer = string => {
  27497. const view = new Uint8Array(new ArrayBuffer(string.length));
  27498. for (let i = 0; i < string.length; i++) {
  27499. view[i] = string.charCodeAt(i);
  27500. }
  27501. return view.buffer;
  27502. };
  27503. /* global Blob, BlobBuilder, Worker */
  27504. // unify worker interface
  27505. const browserWorkerPolyFill = function (workerObj) {
  27506. // node only supports on/off
  27507. workerObj.on = workerObj.addEventListener;
  27508. workerObj.off = workerObj.removeEventListener;
  27509. return workerObj;
  27510. };
  27511. const createObjectURL = function (str) {
  27512. try {
  27513. return URL.createObjectURL(new Blob([str], {
  27514. type: 'application/javascript'
  27515. }));
  27516. } catch (e) {
  27517. const blob = new BlobBuilder();
  27518. blob.append(str);
  27519. return URL.createObjectURL(blob.getBlob());
  27520. }
  27521. };
  27522. const factory = function (code) {
  27523. return function () {
  27524. const objectUrl = createObjectURL(code);
  27525. const worker = browserWorkerPolyFill(new Worker(objectUrl));
  27526. worker.objURL = objectUrl;
  27527. const terminate = worker.terminate;
  27528. worker.on = worker.addEventListener;
  27529. worker.off = worker.removeEventListener;
  27530. worker.terminate = function () {
  27531. URL.revokeObjectURL(objectUrl);
  27532. return terminate.call(this);
  27533. };
  27534. return worker;
  27535. };
  27536. };
  27537. const transform = function (code) {
  27538. return `var browserWorkerPolyFill = ${browserWorkerPolyFill.toString()};\n` + 'browserWorkerPolyFill(self);\n' + code;
  27539. };
  27540. const getWorkerString = function (fn) {
  27541. return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
  27542. };
  27543. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  27544. const workerCode$1 = transform(getWorkerString(function () {
  27545. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  27546. /**
  27547. * mux.js
  27548. *
  27549. * Copyright (c) Brightcove
  27550. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  27551. *
  27552. * A lightweight readable stream implemention that handles event dispatching.
  27553. * Objects that inherit from streams should call init in their constructors.
  27554. */
  27555. var Stream$8 = function () {
  27556. this.init = function () {
  27557. var listeners = {};
  27558. /**
  27559. * Add a listener for a specified event type.
  27560. * @param type {string} the event name
  27561. * @param listener {function} the callback to be invoked when an event of
  27562. * the specified type occurs
  27563. */
  27564. this.on = function (type, listener) {
  27565. if (!listeners[type]) {
  27566. listeners[type] = [];
  27567. }
  27568. listeners[type] = listeners[type].concat(listener);
  27569. };
  27570. /**
  27571. * Remove a listener for a specified event type.
  27572. * @param type {string} the event name
  27573. * @param listener {function} a function previously registered for this
  27574. * type of event through `on`
  27575. */
  27576. this.off = function (type, listener) {
  27577. var index;
  27578. if (!listeners[type]) {
  27579. return false;
  27580. }
  27581. index = listeners[type].indexOf(listener);
  27582. listeners[type] = listeners[type].slice();
  27583. listeners[type].splice(index, 1);
  27584. return index > -1;
  27585. };
  27586. /**
  27587. * Trigger an event of the specified type on this stream. Any additional
  27588. * arguments to this function are passed as parameters to event listeners.
  27589. * @param type {string} the event name
  27590. */
  27591. this.trigger = function (type) {
  27592. var callbacks, i, length, args;
  27593. callbacks = listeners[type];
  27594. if (!callbacks) {
  27595. return;
  27596. } // Slicing the arguments on every invocation of this method
  27597. // can add a significant amount of overhead. Avoid the
  27598. // intermediate object creation for the common case of a
  27599. // single callback argument
  27600. if (arguments.length === 2) {
  27601. length = callbacks.length;
  27602. for (i = 0; i < length; ++i) {
  27603. callbacks[i].call(this, arguments[1]);
  27604. }
  27605. } else {
  27606. args = [];
  27607. i = arguments.length;
  27608. for (i = 1; i < arguments.length; ++i) {
  27609. args.push(arguments[i]);
  27610. }
  27611. length = callbacks.length;
  27612. for (i = 0; i < length; ++i) {
  27613. callbacks[i].apply(this, args);
  27614. }
  27615. }
  27616. };
  27617. /**
  27618. * Destroys the stream and cleans up.
  27619. */
  27620. this.dispose = function () {
  27621. listeners = {};
  27622. };
  27623. };
  27624. };
  27625. /**
  27626. * Forwards all `data` events on this stream to the destination stream. The
  27627. * destination stream should provide a method `push` to receive the data
  27628. * events as they arrive.
  27629. * @param destination {stream} the stream that will receive all `data` events
  27630. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  27631. * when the current stream emits a 'done' event
  27632. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  27633. */
  27634. Stream$8.prototype.pipe = function (destination) {
  27635. this.on('data', function (data) {
  27636. destination.push(data);
  27637. });
  27638. this.on('done', function (flushSource) {
  27639. destination.flush(flushSource);
  27640. });
  27641. this.on('partialdone', function (flushSource) {
  27642. destination.partialFlush(flushSource);
  27643. });
  27644. this.on('endedtimeline', function (flushSource) {
  27645. destination.endTimeline(flushSource);
  27646. });
  27647. this.on('reset', function (flushSource) {
  27648. destination.reset(flushSource);
  27649. });
  27650. return destination;
  27651. }; // Default stream functions that are expected to be overridden to perform
  27652. // actual work. These are provided by the prototype as a sort of no-op
  27653. // implementation so that we don't have to check for their existence in the
  27654. // `pipe` function above.
  27655. Stream$8.prototype.push = function (data) {
  27656. this.trigger('data', data);
  27657. };
  27658. Stream$8.prototype.flush = function (flushSource) {
  27659. this.trigger('done', flushSource);
  27660. };
  27661. Stream$8.prototype.partialFlush = function (flushSource) {
  27662. this.trigger('partialdone', flushSource);
  27663. };
  27664. Stream$8.prototype.endTimeline = function (flushSource) {
  27665. this.trigger('endedtimeline', flushSource);
  27666. };
  27667. Stream$8.prototype.reset = function (flushSource) {
  27668. this.trigger('reset', flushSource);
  27669. };
  27670. var stream = Stream$8;
  27671. var MAX_UINT32$1 = Math.pow(2, 32);
  27672. var getUint64$3 = function (uint8) {
  27673. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  27674. var value;
  27675. if (dv.getBigUint64) {
  27676. value = dv.getBigUint64(0);
  27677. if (value < Number.MAX_SAFE_INTEGER) {
  27678. return Number(value);
  27679. }
  27680. return value;
  27681. }
  27682. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  27683. };
  27684. var numbers = {
  27685. getUint64: getUint64$3,
  27686. MAX_UINT32: MAX_UINT32$1
  27687. };
  27688. /**
  27689. * mux.js
  27690. *
  27691. * Copyright (c) Brightcove
  27692. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  27693. *
  27694. * Functions that generate fragmented MP4s suitable for use with Media
  27695. * Source Extensions.
  27696. */
  27697. var MAX_UINT32 = numbers.MAX_UINT32;
  27698. 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
  27699. (function () {
  27700. var i;
  27701. types = {
  27702. avc1: [],
  27703. // codingname
  27704. avcC: [],
  27705. btrt: [],
  27706. dinf: [],
  27707. dref: [],
  27708. esds: [],
  27709. ftyp: [],
  27710. hdlr: [],
  27711. mdat: [],
  27712. mdhd: [],
  27713. mdia: [],
  27714. mfhd: [],
  27715. minf: [],
  27716. moof: [],
  27717. moov: [],
  27718. mp4a: [],
  27719. // codingname
  27720. mvex: [],
  27721. mvhd: [],
  27722. pasp: [],
  27723. sdtp: [],
  27724. smhd: [],
  27725. stbl: [],
  27726. stco: [],
  27727. stsc: [],
  27728. stsd: [],
  27729. stsz: [],
  27730. stts: [],
  27731. styp: [],
  27732. tfdt: [],
  27733. tfhd: [],
  27734. traf: [],
  27735. trak: [],
  27736. trun: [],
  27737. trex: [],
  27738. tkhd: [],
  27739. vmhd: []
  27740. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  27741. // don't throw an error
  27742. if (typeof Uint8Array === 'undefined') {
  27743. return;
  27744. }
  27745. for (i in types) {
  27746. if (types.hasOwnProperty(i)) {
  27747. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  27748. }
  27749. }
  27750. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  27751. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  27752. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  27753. VIDEO_HDLR = new Uint8Array([0x00,
  27754. // version 0
  27755. 0x00, 0x00, 0x00,
  27756. // flags
  27757. 0x00, 0x00, 0x00, 0x00,
  27758. // pre_defined
  27759. 0x76, 0x69, 0x64, 0x65,
  27760. // handler_type: 'vide'
  27761. 0x00, 0x00, 0x00, 0x00,
  27762. // reserved
  27763. 0x00, 0x00, 0x00, 0x00,
  27764. // reserved
  27765. 0x00, 0x00, 0x00, 0x00,
  27766. // reserved
  27767. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  27768. ]);
  27769. AUDIO_HDLR = new Uint8Array([0x00,
  27770. // version 0
  27771. 0x00, 0x00, 0x00,
  27772. // flags
  27773. 0x00, 0x00, 0x00, 0x00,
  27774. // pre_defined
  27775. 0x73, 0x6f, 0x75, 0x6e,
  27776. // handler_type: 'soun'
  27777. 0x00, 0x00, 0x00, 0x00,
  27778. // reserved
  27779. 0x00, 0x00, 0x00, 0x00,
  27780. // reserved
  27781. 0x00, 0x00, 0x00, 0x00,
  27782. // reserved
  27783. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  27784. ]);
  27785. HDLR_TYPES = {
  27786. video: VIDEO_HDLR,
  27787. audio: AUDIO_HDLR
  27788. };
  27789. DREF = new Uint8Array([0x00,
  27790. // version 0
  27791. 0x00, 0x00, 0x00,
  27792. // flags
  27793. 0x00, 0x00, 0x00, 0x01,
  27794. // entry_count
  27795. 0x00, 0x00, 0x00, 0x0c,
  27796. // entry_size
  27797. 0x75, 0x72, 0x6c, 0x20,
  27798. // 'url' type
  27799. 0x00,
  27800. // version 0
  27801. 0x00, 0x00, 0x01 // entry_flags
  27802. ]);
  27803. SMHD = new Uint8Array([0x00,
  27804. // version
  27805. 0x00, 0x00, 0x00,
  27806. // flags
  27807. 0x00, 0x00,
  27808. // balance, 0 means centered
  27809. 0x00, 0x00 // reserved
  27810. ]);
  27811. STCO = new Uint8Array([0x00,
  27812. // version
  27813. 0x00, 0x00, 0x00,
  27814. // flags
  27815. 0x00, 0x00, 0x00, 0x00 // entry_count
  27816. ]);
  27817. STSC = STCO;
  27818. STSZ = new Uint8Array([0x00,
  27819. // version
  27820. 0x00, 0x00, 0x00,
  27821. // flags
  27822. 0x00, 0x00, 0x00, 0x00,
  27823. // sample_size
  27824. 0x00, 0x00, 0x00, 0x00 // sample_count
  27825. ]);
  27826. STTS = STCO;
  27827. VMHD = new Uint8Array([0x00,
  27828. // version
  27829. 0x00, 0x00, 0x01,
  27830. // flags
  27831. 0x00, 0x00,
  27832. // graphicsmode
  27833. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  27834. ]);
  27835. })();
  27836. box = function (type) {
  27837. var payload = [],
  27838. size = 0,
  27839. i,
  27840. result,
  27841. view;
  27842. for (i = 1; i < arguments.length; i++) {
  27843. payload.push(arguments[i]);
  27844. }
  27845. i = payload.length; // calculate the total size we need to allocate
  27846. while (i--) {
  27847. size += payload[i].byteLength;
  27848. }
  27849. result = new Uint8Array(size + 8);
  27850. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  27851. view.setUint32(0, result.byteLength);
  27852. result.set(type, 4); // copy the payload into the result
  27853. for (i = 0, size = 8; i < payload.length; i++) {
  27854. result.set(payload[i], size);
  27855. size += payload[i].byteLength;
  27856. }
  27857. return result;
  27858. };
  27859. dinf = function () {
  27860. return box(types.dinf, box(types.dref, DREF));
  27861. };
  27862. esds = function (track) {
  27863. return box(types.esds, new Uint8Array([0x00,
  27864. // version
  27865. 0x00, 0x00, 0x00,
  27866. // flags
  27867. // ES_Descriptor
  27868. 0x03,
  27869. // tag, ES_DescrTag
  27870. 0x19,
  27871. // length
  27872. 0x00, 0x00,
  27873. // ES_ID
  27874. 0x00,
  27875. // streamDependenceFlag, URL_flag, reserved, streamPriority
  27876. // DecoderConfigDescriptor
  27877. 0x04,
  27878. // tag, DecoderConfigDescrTag
  27879. 0x11,
  27880. // length
  27881. 0x40,
  27882. // object type
  27883. 0x15,
  27884. // streamType
  27885. 0x00, 0x06, 0x00,
  27886. // bufferSizeDB
  27887. 0x00, 0x00, 0xda, 0xc0,
  27888. // maxBitrate
  27889. 0x00, 0x00, 0xda, 0xc0,
  27890. // avgBitrate
  27891. // DecoderSpecificInfo
  27892. 0x05,
  27893. // tag, DecoderSpecificInfoTag
  27894. 0x02,
  27895. // length
  27896. // ISO/IEC 14496-3, AudioSpecificConfig
  27897. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  27898. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  27899. ]));
  27900. };
  27901. ftyp = function () {
  27902. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  27903. };
  27904. hdlr = function (type) {
  27905. return box(types.hdlr, HDLR_TYPES[type]);
  27906. };
  27907. mdat = function (data) {
  27908. return box(types.mdat, data);
  27909. };
  27910. mdhd = function (track) {
  27911. var result = new Uint8Array([0x00,
  27912. // version 0
  27913. 0x00, 0x00, 0x00,
  27914. // flags
  27915. 0x00, 0x00, 0x00, 0x02,
  27916. // creation_time
  27917. 0x00, 0x00, 0x00, 0x03,
  27918. // modification_time
  27919. 0x00, 0x01, 0x5f, 0x90,
  27920. // timescale, 90,000 "ticks" per second
  27921. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF,
  27922. // duration
  27923. 0x55, 0xc4,
  27924. // 'und' language (undetermined)
  27925. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  27926. // defined. The sample rate can be parsed out of an ADTS header, for
  27927. // instance.
  27928. if (track.samplerate) {
  27929. result[12] = track.samplerate >>> 24 & 0xFF;
  27930. result[13] = track.samplerate >>> 16 & 0xFF;
  27931. result[14] = track.samplerate >>> 8 & 0xFF;
  27932. result[15] = track.samplerate & 0xFF;
  27933. }
  27934. return box(types.mdhd, result);
  27935. };
  27936. mdia = function (track) {
  27937. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  27938. };
  27939. mfhd = function (sequenceNumber) {
  27940. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  27941. // flags
  27942. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  27943. ]));
  27944. };
  27945. minf = function (track) {
  27946. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  27947. };
  27948. moof = function (sequenceNumber, tracks) {
  27949. var trackFragments = [],
  27950. i = tracks.length; // build traf boxes for each track fragment
  27951. while (i--) {
  27952. trackFragments[i] = traf(tracks[i]);
  27953. }
  27954. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  27955. };
  27956. /**
  27957. * Returns a movie box.
  27958. * @param tracks {array} the tracks associated with this movie
  27959. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  27960. */
  27961. moov = function (tracks) {
  27962. var i = tracks.length,
  27963. boxes = [];
  27964. while (i--) {
  27965. boxes[i] = trak(tracks[i]);
  27966. }
  27967. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  27968. };
  27969. mvex = function (tracks) {
  27970. var i = tracks.length,
  27971. boxes = [];
  27972. while (i--) {
  27973. boxes[i] = trex(tracks[i]);
  27974. }
  27975. return box.apply(null, [types.mvex].concat(boxes));
  27976. };
  27977. mvhd = function (duration) {
  27978. var bytes = new Uint8Array([0x00,
  27979. // version 0
  27980. 0x00, 0x00, 0x00,
  27981. // flags
  27982. 0x00, 0x00, 0x00, 0x01,
  27983. // creation_time
  27984. 0x00, 0x00, 0x00, 0x02,
  27985. // modification_time
  27986. 0x00, 0x01, 0x5f, 0x90,
  27987. // timescale, 90,000 "ticks" per second
  27988. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF,
  27989. // duration
  27990. 0x00, 0x01, 0x00, 0x00,
  27991. // 1.0 rate
  27992. 0x01, 0x00,
  27993. // 1.0 volume
  27994. 0x00, 0x00,
  27995. // reserved
  27996. 0x00, 0x00, 0x00, 0x00,
  27997. // reserved
  27998. 0x00, 0x00, 0x00, 0x00,
  27999. // reserved
  28000. 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,
  28001. // transformation: unity matrix
  28002. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  28003. // pre_defined
  28004. 0xff, 0xff, 0xff, 0xff // next_track_ID
  28005. ]);
  28006. return box(types.mvhd, bytes);
  28007. };
  28008. sdtp = function (track) {
  28009. var samples = track.samples || [],
  28010. bytes = new Uint8Array(4 + samples.length),
  28011. flags,
  28012. i; // leave the full box header (4 bytes) all zero
  28013. // write the sample table
  28014. for (i = 0; i < samples.length; i++) {
  28015. flags = samples[i].flags;
  28016. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  28017. }
  28018. return box(types.sdtp, bytes);
  28019. };
  28020. stbl = function (track) {
  28021. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  28022. };
  28023. (function () {
  28024. var videoSample, audioSample;
  28025. stsd = function (track) {
  28026. return box(types.stsd, new Uint8Array([0x00,
  28027. // version 0
  28028. 0x00, 0x00, 0x00,
  28029. // flags
  28030. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  28031. };
  28032. videoSample = function (track) {
  28033. var sps = track.sps || [],
  28034. pps = track.pps || [],
  28035. sequenceParameterSets = [],
  28036. pictureParameterSets = [],
  28037. i,
  28038. avc1Box; // assemble the SPSs
  28039. for (i = 0; i < sps.length; i++) {
  28040. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  28041. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  28042. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  28043. } // assemble the PPSs
  28044. for (i = 0; i < pps.length; i++) {
  28045. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  28046. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  28047. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  28048. }
  28049. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  28050. // reserved
  28051. 0x00, 0x01,
  28052. // data_reference_index
  28053. 0x00, 0x00,
  28054. // pre_defined
  28055. 0x00, 0x00,
  28056. // reserved
  28057. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  28058. // pre_defined
  28059. (track.width & 0xff00) >> 8, track.width & 0xff,
  28060. // width
  28061. (track.height & 0xff00) >> 8, track.height & 0xff,
  28062. // height
  28063. 0x00, 0x48, 0x00, 0x00,
  28064. // horizresolution
  28065. 0x00, 0x48, 0x00, 0x00,
  28066. // vertresolution
  28067. 0x00, 0x00, 0x00, 0x00,
  28068. // reserved
  28069. 0x00, 0x01,
  28070. // frame_count
  28071. 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,
  28072. // compressorname
  28073. 0x00, 0x18,
  28074. // depth = 24
  28075. 0x11, 0x11 // pre_defined = -1
  28076. ]), box(types.avcC, new Uint8Array([0x01,
  28077. // configurationVersion
  28078. track.profileIdc,
  28079. // AVCProfileIndication
  28080. track.profileCompatibility,
  28081. // profile_compatibility
  28082. track.levelIdc,
  28083. // AVCLevelIndication
  28084. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  28085. ].concat([sps.length],
  28086. // numOfSequenceParameterSets
  28087. sequenceParameterSets,
  28088. // "SPS"
  28089. [pps.length],
  28090. // numOfPictureParameterSets
  28091. pictureParameterSets // "PPS"
  28092. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  28093. // bufferSizeDB
  28094. 0x00, 0x2d, 0xc6, 0xc0,
  28095. // maxBitrate
  28096. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  28097. ]))];
  28098. if (track.sarRatio) {
  28099. var hSpacing = track.sarRatio[0],
  28100. vSpacing = track.sarRatio[1];
  28101. 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])));
  28102. }
  28103. return box.apply(null, avc1Box);
  28104. };
  28105. audioSample = function (track) {
  28106. return box(types.mp4a, new Uint8Array([
  28107. // SampleEntry, ISO/IEC 14496-12
  28108. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  28109. // reserved
  28110. 0x00, 0x01,
  28111. // data_reference_index
  28112. // AudioSampleEntry, ISO/IEC 14496-12
  28113. 0x00, 0x00, 0x00, 0x00,
  28114. // reserved
  28115. 0x00, 0x00, 0x00, 0x00,
  28116. // reserved
  28117. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff,
  28118. // channelcount
  28119. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff,
  28120. // samplesize
  28121. 0x00, 0x00,
  28122. // pre_defined
  28123. 0x00, 0x00,
  28124. // reserved
  28125. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  28126. // MP4AudioSampleEntry, ISO/IEC 14496-14
  28127. ]), esds(track));
  28128. };
  28129. })();
  28130. tkhd = function (track) {
  28131. var result = new Uint8Array([0x00,
  28132. // version 0
  28133. 0x00, 0x00, 0x07,
  28134. // flags
  28135. 0x00, 0x00, 0x00, 0x00,
  28136. // creation_time
  28137. 0x00, 0x00, 0x00, 0x00,
  28138. // modification_time
  28139. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,
  28140. // track_ID
  28141. 0x00, 0x00, 0x00, 0x00,
  28142. // reserved
  28143. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF,
  28144. // duration
  28145. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  28146. // reserved
  28147. 0x00, 0x00,
  28148. // layer
  28149. 0x00, 0x00,
  28150. // alternate_group
  28151. 0x01, 0x00,
  28152. // non-audio track volume
  28153. 0x00, 0x00,
  28154. // reserved
  28155. 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,
  28156. // transformation: unity matrix
  28157. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00,
  28158. // width
  28159. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  28160. ]);
  28161. return box(types.tkhd, result);
  28162. };
  28163. /**
  28164. * Generate a track fragment (traf) box. A traf box collects metadata
  28165. * about tracks in a movie fragment (moof) box.
  28166. */
  28167. traf = function (track) {
  28168. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  28169. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00,
  28170. // version 0
  28171. 0x00, 0x00, 0x3a,
  28172. // flags
  28173. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,
  28174. // track_ID
  28175. 0x00, 0x00, 0x00, 0x01,
  28176. // sample_description_index
  28177. 0x00, 0x00, 0x00, 0x00,
  28178. // default_sample_duration
  28179. 0x00, 0x00, 0x00, 0x00,
  28180. // default_sample_size
  28181. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  28182. ]));
  28183. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  28184. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  28185. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01,
  28186. // version 1
  28187. 0x00, 0x00, 0x00,
  28188. // flags
  28189. // baseMediaDecodeTime
  28190. 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
  28191. // the containing moof to the first payload byte of the associated
  28192. // mdat
  28193. dataOffset = 32 +
  28194. // tfhd
  28195. 20 +
  28196. // tfdt
  28197. 8 +
  28198. // traf header
  28199. 16 +
  28200. // mfhd
  28201. 8 +
  28202. // moof header
  28203. 8; // mdat header
  28204. // audio tracks require less metadata
  28205. if (track.type === 'audio') {
  28206. trackFragmentRun = trun$1(track, dataOffset);
  28207. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  28208. } // video tracks should contain an independent and disposable samples
  28209. // box (sdtp)
  28210. // generate one and adjust offsets to match
  28211. sampleDependencyTable = sdtp(track);
  28212. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  28213. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  28214. };
  28215. /**
  28216. * Generate a track box.
  28217. * @param track {object} a track definition
  28218. * @return {Uint8Array} the track box
  28219. */
  28220. trak = function (track) {
  28221. track.duration = track.duration || 0xffffffff;
  28222. return box(types.trak, tkhd(track), mdia(track));
  28223. };
  28224. trex = function (track) {
  28225. var result = new Uint8Array([0x00,
  28226. // version 0
  28227. 0x00, 0x00, 0x00,
  28228. // flags
  28229. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,
  28230. // track_ID
  28231. 0x00, 0x00, 0x00, 0x01,
  28232. // default_sample_description_index
  28233. 0x00, 0x00, 0x00, 0x00,
  28234. // default_sample_duration
  28235. 0x00, 0x00, 0x00, 0x00,
  28236. // default_sample_size
  28237. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  28238. ]); // the last two bytes of default_sample_flags is the sample
  28239. // degradation priority, a hint about the importance of this sample
  28240. // relative to others. Lower the degradation priority for all sample
  28241. // types other than video.
  28242. if (track.type !== 'video') {
  28243. result[result.length - 1] = 0x00;
  28244. }
  28245. return box(types.trex, result);
  28246. };
  28247. (function () {
  28248. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  28249. // duration is present for the first sample, it will be present for
  28250. // all subsequent samples.
  28251. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  28252. trunHeader = function (samples, offset) {
  28253. var durationPresent = 0,
  28254. sizePresent = 0,
  28255. flagsPresent = 0,
  28256. compositionTimeOffset = 0; // trun flag constants
  28257. if (samples.length) {
  28258. if (samples[0].duration !== undefined) {
  28259. durationPresent = 0x1;
  28260. }
  28261. if (samples[0].size !== undefined) {
  28262. sizePresent = 0x2;
  28263. }
  28264. if (samples[0].flags !== undefined) {
  28265. flagsPresent = 0x4;
  28266. }
  28267. if (samples[0].compositionTimeOffset !== undefined) {
  28268. compositionTimeOffset = 0x8;
  28269. }
  28270. }
  28271. return [0x00,
  28272. // version 0
  28273. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01,
  28274. // flags
  28275. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF,
  28276. // sample_count
  28277. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  28278. ];
  28279. };
  28280. videoTrun = function (track, offset) {
  28281. var bytesOffest, bytes, header, samples, sample, i;
  28282. samples = track.samples || [];
  28283. offset += 8 + 12 + 16 * samples.length;
  28284. header = trunHeader(samples, offset);
  28285. bytes = new Uint8Array(header.length + samples.length * 16);
  28286. bytes.set(header);
  28287. bytesOffest = header.length;
  28288. for (i = 0; i < samples.length; i++) {
  28289. sample = samples[i];
  28290. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  28291. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  28292. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  28293. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  28294. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  28295. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  28296. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  28297. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  28298. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  28299. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  28300. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  28301. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  28302. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  28303. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  28304. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  28305. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  28306. }
  28307. return box(types.trun, bytes);
  28308. };
  28309. audioTrun = function (track, offset) {
  28310. var bytes, bytesOffest, header, samples, sample, i;
  28311. samples = track.samples || [];
  28312. offset += 8 + 12 + 8 * samples.length;
  28313. header = trunHeader(samples, offset);
  28314. bytes = new Uint8Array(header.length + samples.length * 8);
  28315. bytes.set(header);
  28316. bytesOffest = header.length;
  28317. for (i = 0; i < samples.length; i++) {
  28318. sample = samples[i];
  28319. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  28320. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  28321. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  28322. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  28323. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  28324. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  28325. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  28326. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  28327. }
  28328. return box(types.trun, bytes);
  28329. };
  28330. trun$1 = function (track, offset) {
  28331. if (track.type === 'audio') {
  28332. return audioTrun(track, offset);
  28333. }
  28334. return videoTrun(track, offset);
  28335. };
  28336. })();
  28337. var mp4Generator = {
  28338. ftyp: ftyp,
  28339. mdat: mdat,
  28340. moof: moof,
  28341. moov: moov,
  28342. initSegment: function (tracks) {
  28343. var fileType = ftyp(),
  28344. movie = moov(tracks),
  28345. result;
  28346. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  28347. result.set(fileType);
  28348. result.set(movie, fileType.byteLength);
  28349. return result;
  28350. }
  28351. };
  28352. /**
  28353. * mux.js
  28354. *
  28355. * Copyright (c) Brightcove
  28356. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28357. */
  28358. // composed of the nal units that make up that frame
  28359. // Also keep track of cummulative data about the frame from the nal units such
  28360. // as the frame duration, starting pts, etc.
  28361. var groupNalsIntoFrames = function (nalUnits) {
  28362. var i,
  28363. currentNal,
  28364. currentFrame = [],
  28365. frames = []; // TODO added for LHLS, make sure this is OK
  28366. frames.byteLength = 0;
  28367. frames.nalCount = 0;
  28368. frames.duration = 0;
  28369. currentFrame.byteLength = 0;
  28370. for (i = 0; i < nalUnits.length; i++) {
  28371. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  28372. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  28373. // Since the very first nal unit is expected to be an AUD
  28374. // only push to the frames array when currentFrame is not empty
  28375. if (currentFrame.length) {
  28376. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  28377. frames.byteLength += currentFrame.byteLength;
  28378. frames.nalCount += currentFrame.length;
  28379. frames.duration += currentFrame.duration;
  28380. frames.push(currentFrame);
  28381. }
  28382. currentFrame = [currentNal];
  28383. currentFrame.byteLength = currentNal.data.byteLength;
  28384. currentFrame.pts = currentNal.pts;
  28385. currentFrame.dts = currentNal.dts;
  28386. } else {
  28387. // Specifically flag key frames for ease of use later
  28388. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  28389. currentFrame.keyFrame = true;
  28390. }
  28391. currentFrame.duration = currentNal.dts - currentFrame.dts;
  28392. currentFrame.byteLength += currentNal.data.byteLength;
  28393. currentFrame.push(currentNal);
  28394. }
  28395. } // For the last frame, use the duration of the previous frame if we
  28396. // have nothing better to go on
  28397. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  28398. currentFrame.duration = frames[frames.length - 1].duration;
  28399. } // Push the final frame
  28400. // TODO added for LHLS, make sure this is OK
  28401. frames.byteLength += currentFrame.byteLength;
  28402. frames.nalCount += currentFrame.length;
  28403. frames.duration += currentFrame.duration;
  28404. frames.push(currentFrame);
  28405. return frames;
  28406. }; // Convert an array of frames into an array of Gop with each Gop being composed
  28407. // of the frames that make up that Gop
  28408. // Also keep track of cummulative data about the Gop from the frames such as the
  28409. // Gop duration, starting pts, etc.
  28410. var groupFramesIntoGops = function (frames) {
  28411. var i,
  28412. currentFrame,
  28413. currentGop = [],
  28414. gops = []; // We must pre-set some of the values on the Gop since we
  28415. // keep running totals of these values
  28416. currentGop.byteLength = 0;
  28417. currentGop.nalCount = 0;
  28418. currentGop.duration = 0;
  28419. currentGop.pts = frames[0].pts;
  28420. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  28421. gops.byteLength = 0;
  28422. gops.nalCount = 0;
  28423. gops.duration = 0;
  28424. gops.pts = frames[0].pts;
  28425. gops.dts = frames[0].dts;
  28426. for (i = 0; i < frames.length; i++) {
  28427. currentFrame = frames[i];
  28428. if (currentFrame.keyFrame) {
  28429. // Since the very first frame is expected to be an keyframe
  28430. // only push to the gops array when currentGop is not empty
  28431. if (currentGop.length) {
  28432. gops.push(currentGop);
  28433. gops.byteLength += currentGop.byteLength;
  28434. gops.nalCount += currentGop.nalCount;
  28435. gops.duration += currentGop.duration;
  28436. }
  28437. currentGop = [currentFrame];
  28438. currentGop.nalCount = currentFrame.length;
  28439. currentGop.byteLength = currentFrame.byteLength;
  28440. currentGop.pts = currentFrame.pts;
  28441. currentGop.dts = currentFrame.dts;
  28442. currentGop.duration = currentFrame.duration;
  28443. } else {
  28444. currentGop.duration += currentFrame.duration;
  28445. currentGop.nalCount += currentFrame.length;
  28446. currentGop.byteLength += currentFrame.byteLength;
  28447. currentGop.push(currentFrame);
  28448. }
  28449. }
  28450. if (gops.length && currentGop.duration <= 0) {
  28451. currentGop.duration = gops[gops.length - 1].duration;
  28452. }
  28453. gops.byteLength += currentGop.byteLength;
  28454. gops.nalCount += currentGop.nalCount;
  28455. gops.duration += currentGop.duration; // push the final Gop
  28456. gops.push(currentGop);
  28457. return gops;
  28458. };
  28459. /*
  28460. * Search for the first keyframe in the GOPs and throw away all frames
  28461. * until that keyframe. Then extend the duration of the pulled keyframe
  28462. * and pull the PTS and DTS of the keyframe so that it covers the time
  28463. * range of the frames that were disposed.
  28464. *
  28465. * @param {Array} gops video GOPs
  28466. * @returns {Array} modified video GOPs
  28467. */
  28468. var extendFirstKeyFrame = function (gops) {
  28469. var currentGop;
  28470. if (!gops[0][0].keyFrame && gops.length > 1) {
  28471. // Remove the first GOP
  28472. currentGop = gops.shift();
  28473. gops.byteLength -= currentGop.byteLength;
  28474. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  28475. // first gop to cover the time period of the
  28476. // frames we just removed
  28477. gops[0][0].dts = currentGop.dts;
  28478. gops[0][0].pts = currentGop.pts;
  28479. gops[0][0].duration += currentGop.duration;
  28480. }
  28481. return gops;
  28482. };
  28483. /**
  28484. * Default sample object
  28485. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  28486. */
  28487. var createDefaultSample = function () {
  28488. return {
  28489. size: 0,
  28490. flags: {
  28491. isLeading: 0,
  28492. dependsOn: 1,
  28493. isDependedOn: 0,
  28494. hasRedundancy: 0,
  28495. degradationPriority: 0,
  28496. isNonSyncSample: 1
  28497. }
  28498. };
  28499. };
  28500. /*
  28501. * Collates information from a video frame into an object for eventual
  28502. * entry into an MP4 sample table.
  28503. *
  28504. * @param {Object} frame the video frame
  28505. * @param {Number} dataOffset the byte offset to position the sample
  28506. * @return {Object} object containing sample table info for a frame
  28507. */
  28508. var sampleForFrame = function (frame, dataOffset) {
  28509. var sample = createDefaultSample();
  28510. sample.dataOffset = dataOffset;
  28511. sample.compositionTimeOffset = frame.pts - frame.dts;
  28512. sample.duration = frame.duration;
  28513. sample.size = 4 * frame.length; // Space for nal unit size
  28514. sample.size += frame.byteLength;
  28515. if (frame.keyFrame) {
  28516. sample.flags.dependsOn = 2;
  28517. sample.flags.isNonSyncSample = 0;
  28518. }
  28519. return sample;
  28520. }; // generate the track's sample table from an array of gops
  28521. var generateSampleTable$1 = function (gops, baseDataOffset) {
  28522. var h,
  28523. i,
  28524. sample,
  28525. currentGop,
  28526. currentFrame,
  28527. dataOffset = baseDataOffset || 0,
  28528. samples = [];
  28529. for (h = 0; h < gops.length; h++) {
  28530. currentGop = gops[h];
  28531. for (i = 0; i < currentGop.length; i++) {
  28532. currentFrame = currentGop[i];
  28533. sample = sampleForFrame(currentFrame, dataOffset);
  28534. dataOffset += sample.size;
  28535. samples.push(sample);
  28536. }
  28537. }
  28538. return samples;
  28539. }; // generate the track's raw mdat data from an array of gops
  28540. var concatenateNalData = function (gops) {
  28541. var h,
  28542. i,
  28543. j,
  28544. currentGop,
  28545. currentFrame,
  28546. currentNal,
  28547. dataOffset = 0,
  28548. nalsByteLength = gops.byteLength,
  28549. numberOfNals = gops.nalCount,
  28550. totalByteLength = nalsByteLength + 4 * numberOfNals,
  28551. data = new Uint8Array(totalByteLength),
  28552. view = new DataView(data.buffer); // For each Gop..
  28553. for (h = 0; h < gops.length; h++) {
  28554. currentGop = gops[h]; // For each Frame..
  28555. for (i = 0; i < currentGop.length; i++) {
  28556. currentFrame = currentGop[i]; // For each NAL..
  28557. for (j = 0; j < currentFrame.length; j++) {
  28558. currentNal = currentFrame[j];
  28559. view.setUint32(dataOffset, currentNal.data.byteLength);
  28560. dataOffset += 4;
  28561. data.set(currentNal.data, dataOffset);
  28562. dataOffset += currentNal.data.byteLength;
  28563. }
  28564. }
  28565. }
  28566. return data;
  28567. }; // generate the track's sample table from a frame
  28568. var generateSampleTableForFrame = function (frame, baseDataOffset) {
  28569. var sample,
  28570. dataOffset = baseDataOffset || 0,
  28571. samples = [];
  28572. sample = sampleForFrame(frame, dataOffset);
  28573. samples.push(sample);
  28574. return samples;
  28575. }; // generate the track's raw mdat data from a frame
  28576. var concatenateNalDataForFrame = function (frame) {
  28577. var i,
  28578. currentNal,
  28579. dataOffset = 0,
  28580. nalsByteLength = frame.byteLength,
  28581. numberOfNals = frame.length,
  28582. totalByteLength = nalsByteLength + 4 * numberOfNals,
  28583. data = new Uint8Array(totalByteLength),
  28584. view = new DataView(data.buffer); // For each NAL..
  28585. for (i = 0; i < frame.length; i++) {
  28586. currentNal = frame[i];
  28587. view.setUint32(dataOffset, currentNal.data.byteLength);
  28588. dataOffset += 4;
  28589. data.set(currentNal.data, dataOffset);
  28590. dataOffset += currentNal.data.byteLength;
  28591. }
  28592. return data;
  28593. };
  28594. var frameUtils$1 = {
  28595. groupNalsIntoFrames: groupNalsIntoFrames,
  28596. groupFramesIntoGops: groupFramesIntoGops,
  28597. extendFirstKeyFrame: extendFirstKeyFrame,
  28598. generateSampleTable: generateSampleTable$1,
  28599. concatenateNalData: concatenateNalData,
  28600. generateSampleTableForFrame: generateSampleTableForFrame,
  28601. concatenateNalDataForFrame: concatenateNalDataForFrame
  28602. };
  28603. /**
  28604. * mux.js
  28605. *
  28606. * Copyright (c) Brightcove
  28607. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28608. */
  28609. var highPrefix = [33, 16, 5, 32, 164, 27];
  28610. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  28611. var zeroFill = function (count) {
  28612. var a = [];
  28613. while (count--) {
  28614. a.push(0);
  28615. }
  28616. return a;
  28617. };
  28618. var makeTable = function (metaTable) {
  28619. return Object.keys(metaTable).reduce(function (obj, key) {
  28620. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  28621. return arr.concat(part);
  28622. }, []));
  28623. return obj;
  28624. }, {});
  28625. };
  28626. var silence;
  28627. var silence_1 = function () {
  28628. if (!silence) {
  28629. // Frames-of-silence to use for filling in missing AAC frames
  28630. var coneOfSilence = {
  28631. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  28632. 88200: [highPrefix, [231], zeroFill(170), [56]],
  28633. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  28634. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  28635. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  28636. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  28637. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  28638. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  28639. 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]],
  28640. 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]],
  28641. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  28642. };
  28643. silence = makeTable(coneOfSilence);
  28644. }
  28645. return silence;
  28646. };
  28647. /**
  28648. * mux.js
  28649. *
  28650. * Copyright (c) Brightcove
  28651. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28652. */
  28653. var ONE_SECOND_IN_TS$4 = 90000,
  28654. // 90kHz clock
  28655. secondsToVideoTs,
  28656. secondsToAudioTs,
  28657. videoTsToSeconds,
  28658. audioTsToSeconds,
  28659. audioTsToVideoTs,
  28660. videoTsToAudioTs,
  28661. metadataTsToSeconds;
  28662. secondsToVideoTs = function (seconds) {
  28663. return seconds * ONE_SECOND_IN_TS$4;
  28664. };
  28665. secondsToAudioTs = function (seconds, sampleRate) {
  28666. return seconds * sampleRate;
  28667. };
  28668. videoTsToSeconds = function (timestamp) {
  28669. return timestamp / ONE_SECOND_IN_TS$4;
  28670. };
  28671. audioTsToSeconds = function (timestamp, sampleRate) {
  28672. return timestamp / sampleRate;
  28673. };
  28674. audioTsToVideoTs = function (timestamp, sampleRate) {
  28675. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  28676. };
  28677. videoTsToAudioTs = function (timestamp, sampleRate) {
  28678. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  28679. };
  28680. /**
  28681. * Adjust ID3 tag or caption timing information by the timeline pts values
  28682. * (if keepOriginalTimestamps is false) and convert to seconds
  28683. */
  28684. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  28685. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  28686. };
  28687. var clock$2 = {
  28688. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  28689. secondsToVideoTs: secondsToVideoTs,
  28690. secondsToAudioTs: secondsToAudioTs,
  28691. videoTsToSeconds: videoTsToSeconds,
  28692. audioTsToSeconds: audioTsToSeconds,
  28693. audioTsToVideoTs: audioTsToVideoTs,
  28694. videoTsToAudioTs: videoTsToAudioTs,
  28695. metadataTsToSeconds: metadataTsToSeconds
  28696. };
  28697. /**
  28698. * mux.js
  28699. *
  28700. * Copyright (c) Brightcove
  28701. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28702. */
  28703. var coneOfSilence = silence_1;
  28704. var clock$1 = clock$2;
  28705. /**
  28706. * Sum the `byteLength` properties of the data in each AAC frame
  28707. */
  28708. var sumFrameByteLengths = function (array) {
  28709. var i,
  28710. currentObj,
  28711. sum = 0; // sum the byteLength's all each nal unit in the frame
  28712. for (i = 0; i < array.length; i++) {
  28713. currentObj = array[i];
  28714. sum += currentObj.data.byteLength;
  28715. }
  28716. return sum;
  28717. }; // Possibly pad (prefix) the audio track with silence if appending this track
  28718. // would lead to the introduction of a gap in the audio buffer
  28719. var prefixWithSilence = function (track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  28720. var baseMediaDecodeTimeTs,
  28721. frameDuration = 0,
  28722. audioGapDuration = 0,
  28723. audioFillFrameCount = 0,
  28724. audioFillDuration = 0,
  28725. silentFrame,
  28726. i,
  28727. firstFrame;
  28728. if (!frames.length) {
  28729. return;
  28730. }
  28731. baseMediaDecodeTimeTs = clock$1.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  28732. frameDuration = Math.ceil(clock$1.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  28733. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  28734. // insert the shortest possible amount (audio gap or audio to video gap)
  28735. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  28736. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  28737. audioFillDuration = audioFillFrameCount * frameDuration;
  28738. } // don't attempt to fill gaps smaller than a single frame or larger
  28739. // than a half second
  28740. if (audioFillFrameCount < 1 || audioFillDuration > clock$1.ONE_SECOND_IN_TS / 2) {
  28741. return;
  28742. }
  28743. silentFrame = coneOfSilence()[track.samplerate];
  28744. if (!silentFrame) {
  28745. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  28746. // from the content instead
  28747. silentFrame = frames[0].data;
  28748. }
  28749. for (i = 0; i < audioFillFrameCount; i++) {
  28750. firstFrame = frames[0];
  28751. frames.splice(0, 0, {
  28752. data: silentFrame,
  28753. dts: firstFrame.dts - frameDuration,
  28754. pts: firstFrame.pts - frameDuration
  28755. });
  28756. }
  28757. track.baseMediaDecodeTime -= Math.floor(clock$1.videoTsToAudioTs(audioFillDuration, track.samplerate));
  28758. return audioFillDuration;
  28759. }; // If the audio segment extends before the earliest allowed dts
  28760. // value, remove AAC frames until starts at or after the earliest
  28761. // allowed DTS so that we don't end up with a negative baseMedia-
  28762. // DecodeTime for the audio track
  28763. var trimAdtsFramesByEarliestDts = function (adtsFrames, track, earliestAllowedDts) {
  28764. if (track.minSegmentDts >= earliestAllowedDts) {
  28765. return adtsFrames;
  28766. } // We will need to recalculate the earliest segment Dts
  28767. track.minSegmentDts = Infinity;
  28768. return adtsFrames.filter(function (currentFrame) {
  28769. // If this is an allowed frame, keep it and record it's Dts
  28770. if (currentFrame.dts >= earliestAllowedDts) {
  28771. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  28772. track.minSegmentPts = track.minSegmentDts;
  28773. return true;
  28774. } // Otherwise, discard it
  28775. return false;
  28776. });
  28777. }; // generate the track's raw mdat data from an array of frames
  28778. var generateSampleTable = function (frames) {
  28779. var i,
  28780. currentFrame,
  28781. samples = [];
  28782. for (i = 0; i < frames.length; i++) {
  28783. currentFrame = frames[i];
  28784. samples.push({
  28785. size: currentFrame.data.byteLength,
  28786. duration: 1024 // For AAC audio, all samples contain 1024 samples
  28787. });
  28788. }
  28789. return samples;
  28790. }; // generate the track's sample table from an array of frames
  28791. var concatenateFrameData = function (frames) {
  28792. var i,
  28793. currentFrame,
  28794. dataOffset = 0,
  28795. data = new Uint8Array(sumFrameByteLengths(frames));
  28796. for (i = 0; i < frames.length; i++) {
  28797. currentFrame = frames[i];
  28798. data.set(currentFrame.data, dataOffset);
  28799. dataOffset += currentFrame.data.byteLength;
  28800. }
  28801. return data;
  28802. };
  28803. var audioFrameUtils$1 = {
  28804. prefixWithSilence: prefixWithSilence,
  28805. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  28806. generateSampleTable: generateSampleTable,
  28807. concatenateFrameData: concatenateFrameData
  28808. };
  28809. /**
  28810. * mux.js
  28811. *
  28812. * Copyright (c) Brightcove
  28813. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28814. */
  28815. var ONE_SECOND_IN_TS$3 = clock$2.ONE_SECOND_IN_TS;
  28816. /**
  28817. * Store information about the start and end of the track and the
  28818. * duration for each frame/sample we process in order to calculate
  28819. * the baseMediaDecodeTime
  28820. */
  28821. var collectDtsInfo = function (track, data) {
  28822. if (typeof data.pts === 'number') {
  28823. if (track.timelineStartInfo.pts === undefined) {
  28824. track.timelineStartInfo.pts = data.pts;
  28825. }
  28826. if (track.minSegmentPts === undefined) {
  28827. track.minSegmentPts = data.pts;
  28828. } else {
  28829. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  28830. }
  28831. if (track.maxSegmentPts === undefined) {
  28832. track.maxSegmentPts = data.pts;
  28833. } else {
  28834. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  28835. }
  28836. }
  28837. if (typeof data.dts === 'number') {
  28838. if (track.timelineStartInfo.dts === undefined) {
  28839. track.timelineStartInfo.dts = data.dts;
  28840. }
  28841. if (track.minSegmentDts === undefined) {
  28842. track.minSegmentDts = data.dts;
  28843. } else {
  28844. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  28845. }
  28846. if (track.maxSegmentDts === undefined) {
  28847. track.maxSegmentDts = data.dts;
  28848. } else {
  28849. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  28850. }
  28851. }
  28852. };
  28853. /**
  28854. * Clear values used to calculate the baseMediaDecodeTime between
  28855. * tracks
  28856. */
  28857. var clearDtsInfo = function (track) {
  28858. delete track.minSegmentDts;
  28859. delete track.maxSegmentDts;
  28860. delete track.minSegmentPts;
  28861. delete track.maxSegmentPts;
  28862. };
  28863. /**
  28864. * Calculate the track's baseMediaDecodeTime based on the earliest
  28865. * DTS the transmuxer has ever seen and the minimum DTS for the
  28866. * current track
  28867. * @param track {object} track metadata configuration
  28868. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  28869. * in the source; false to adjust the first segment to start at 0.
  28870. */
  28871. var calculateTrackBaseMediaDecodeTime = function (track, keepOriginalTimestamps) {
  28872. var baseMediaDecodeTime,
  28873. scale,
  28874. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  28875. if (!keepOriginalTimestamps) {
  28876. minSegmentDts -= track.timelineStartInfo.dts;
  28877. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  28878. // we want the start of the first segment to be placed
  28879. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  28880. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  28881. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  28882. if (track.type === 'audio') {
  28883. // Audio has a different clock equal to the sampling_rate so we need to
  28884. // scale the PTS values into the clock rate of the track
  28885. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  28886. baseMediaDecodeTime *= scale;
  28887. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  28888. }
  28889. return baseMediaDecodeTime;
  28890. };
  28891. var trackDecodeInfo$1 = {
  28892. clearDtsInfo: clearDtsInfo,
  28893. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  28894. collectDtsInfo: collectDtsInfo
  28895. };
  28896. /**
  28897. * mux.js
  28898. *
  28899. * Copyright (c) Brightcove
  28900. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28901. *
  28902. * Reads in-band caption information from a video elementary
  28903. * stream. Captions must follow the CEA-708 standard for injection
  28904. * into an MPEG-2 transport streams.
  28905. * @see https://en.wikipedia.org/wiki/CEA-708
  28906. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  28907. */
  28908. // payload type field to indicate how they are to be
  28909. // interpreted. CEAS-708 caption content is always transmitted with
  28910. // payload type 0x04.
  28911. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  28912. RBSP_TRAILING_BITS = 128;
  28913. /**
  28914. * Parse a supplemental enhancement information (SEI) NAL unit.
  28915. * Stops parsing once a message of type ITU T T35 has been found.
  28916. *
  28917. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  28918. * @return {object} the parsed SEI payload
  28919. * @see Rec. ITU-T H.264, 7.3.2.3.1
  28920. */
  28921. var parseSei = function (bytes) {
  28922. var i = 0,
  28923. result = {
  28924. payloadType: -1,
  28925. payloadSize: 0
  28926. },
  28927. payloadType = 0,
  28928. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  28929. while (i < bytes.byteLength) {
  28930. // stop once we have hit the end of the sei_rbsp
  28931. if (bytes[i] === RBSP_TRAILING_BITS) {
  28932. break;
  28933. } // Parse payload type
  28934. while (bytes[i] === 0xFF) {
  28935. payloadType += 255;
  28936. i++;
  28937. }
  28938. payloadType += bytes[i++]; // Parse payload size
  28939. while (bytes[i] === 0xFF) {
  28940. payloadSize += 255;
  28941. i++;
  28942. }
  28943. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  28944. // there can only ever be one caption message in a frame's sei
  28945. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  28946. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  28947. if (userIdentifier === 'GA94') {
  28948. result.payloadType = payloadType;
  28949. result.payloadSize = payloadSize;
  28950. result.payload = bytes.subarray(i, i + payloadSize);
  28951. break;
  28952. } else {
  28953. result.payload = void 0;
  28954. }
  28955. } // skip the payload and parse the next message
  28956. i += payloadSize;
  28957. payloadType = 0;
  28958. payloadSize = 0;
  28959. }
  28960. return result;
  28961. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  28962. var parseUserData = function (sei) {
  28963. // itu_t_t35_contry_code must be 181 (United States) for
  28964. // captions
  28965. if (sei.payload[0] !== 181) {
  28966. return null;
  28967. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  28968. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  28969. return null;
  28970. } // the user_identifier should be "GA94" to indicate ATSC1 data
  28971. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  28972. return null;
  28973. } // finally, user_data_type_code should be 0x03 for caption data
  28974. if (sei.payload[7] !== 0x03) {
  28975. return null;
  28976. } // return the user_data_type_structure and strip the trailing
  28977. // marker bits
  28978. return sei.payload.subarray(8, sei.payload.length - 1);
  28979. }; // see CEA-708-D, section 4.4
  28980. var parseCaptionPackets = function (pts, userData) {
  28981. var results = [],
  28982. i,
  28983. count,
  28984. offset,
  28985. data; // if this is just filler, return immediately
  28986. if (!(userData[0] & 0x40)) {
  28987. return results;
  28988. } // parse out the cc_data_1 and cc_data_2 fields
  28989. count = userData[0] & 0x1f;
  28990. for (i = 0; i < count; i++) {
  28991. offset = i * 3;
  28992. data = {
  28993. type: userData[offset + 2] & 0x03,
  28994. pts: pts
  28995. }; // capture cc data when cc_valid is 1
  28996. if (userData[offset + 2] & 0x04) {
  28997. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  28998. results.push(data);
  28999. }
  29000. }
  29001. return results;
  29002. };
  29003. var discardEmulationPreventionBytes$1 = function (data) {
  29004. var length = data.byteLength,
  29005. emulationPreventionBytesPositions = [],
  29006. i = 1,
  29007. newLength,
  29008. newData; // Find all `Emulation Prevention Bytes`
  29009. while (i < length - 2) {
  29010. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  29011. emulationPreventionBytesPositions.push(i + 2);
  29012. i += 2;
  29013. } else {
  29014. i++;
  29015. }
  29016. } // If no Emulation Prevention Bytes were found just return the original
  29017. // array
  29018. if (emulationPreventionBytesPositions.length === 0) {
  29019. return data;
  29020. } // Create a new array to hold the NAL unit data
  29021. newLength = length - emulationPreventionBytesPositions.length;
  29022. newData = new Uint8Array(newLength);
  29023. var sourceIndex = 0;
  29024. for (i = 0; i < newLength; sourceIndex++, i++) {
  29025. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  29026. // Skip this byte
  29027. sourceIndex++; // Remove this position index
  29028. emulationPreventionBytesPositions.shift();
  29029. }
  29030. newData[i] = data[sourceIndex];
  29031. }
  29032. return newData;
  29033. }; // exports
  29034. var captionPacketParser = {
  29035. parseSei: parseSei,
  29036. parseUserData: parseUserData,
  29037. parseCaptionPackets: parseCaptionPackets,
  29038. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  29039. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  29040. };
  29041. /**
  29042. * mux.js
  29043. *
  29044. * Copyright (c) Brightcove
  29045. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  29046. *
  29047. * Reads in-band caption information from a video elementary
  29048. * stream. Captions must follow the CEA-708 standard for injection
  29049. * into an MPEG-2 transport streams.
  29050. * @see https://en.wikipedia.org/wiki/CEA-708
  29051. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  29052. */
  29053. // Link To Transport
  29054. // -----------------
  29055. var Stream$7 = stream;
  29056. var cea708Parser = captionPacketParser;
  29057. var CaptionStream$2 = function (options) {
  29058. options = options || {};
  29059. CaptionStream$2.prototype.init.call(this); // parse708captions flag, default to true
  29060. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  29061. this.captionPackets_ = [];
  29062. this.ccStreams_ = [new Cea608Stream(0, 0),
  29063. // eslint-disable-line no-use-before-define
  29064. new Cea608Stream(0, 1),
  29065. // eslint-disable-line no-use-before-define
  29066. new Cea608Stream(1, 0),
  29067. // eslint-disable-line no-use-before-define
  29068. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  29069. ];
  29070. if (this.parse708captions_) {
  29071. this.cc708Stream_ = new Cea708Stream({
  29072. captionServices: options.captionServices
  29073. }); // eslint-disable-line no-use-before-define
  29074. }
  29075. this.reset(); // forward data and done events from CCs to this CaptionStream
  29076. this.ccStreams_.forEach(function (cc) {
  29077. cc.on('data', this.trigger.bind(this, 'data'));
  29078. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  29079. cc.on('done', this.trigger.bind(this, 'done'));
  29080. }, this);
  29081. if (this.parse708captions_) {
  29082. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  29083. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  29084. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  29085. }
  29086. };
  29087. CaptionStream$2.prototype = new Stream$7();
  29088. CaptionStream$2.prototype.push = function (event) {
  29089. var sei, userData, newCaptionPackets; // only examine SEI NALs
  29090. if (event.nalUnitType !== 'sei_rbsp') {
  29091. return;
  29092. } // parse the sei
  29093. sei = cea708Parser.parseSei(event.escapedRBSP); // no payload data, skip
  29094. if (!sei.payload) {
  29095. return;
  29096. } // ignore everything but user_data_registered_itu_t_t35
  29097. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  29098. return;
  29099. } // parse out the user data payload
  29100. userData = cea708Parser.parseUserData(sei); // ignore unrecognized userData
  29101. if (!userData) {
  29102. return;
  29103. } // Sometimes, the same segment # will be downloaded twice. To stop the
  29104. // caption data from being processed twice, we track the latest dts we've
  29105. // received and ignore everything with a dts before that. However, since
  29106. // data for a specific dts can be split across packets on either side of
  29107. // a segment boundary, we need to make sure we *don't* ignore the packets
  29108. // from the *next* segment that have dts === this.latestDts_. By constantly
  29109. // tracking the number of packets received with dts === this.latestDts_, we
  29110. // know how many should be ignored once we start receiving duplicates.
  29111. if (event.dts < this.latestDts_) {
  29112. // We've started getting older data, so set the flag.
  29113. this.ignoreNextEqualDts_ = true;
  29114. return;
  29115. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  29116. this.numSameDts_--;
  29117. if (!this.numSameDts_) {
  29118. // We've received the last duplicate packet, time to start processing again
  29119. this.ignoreNextEqualDts_ = false;
  29120. }
  29121. return;
  29122. } // parse out CC data packets and save them for later
  29123. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  29124. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  29125. if (this.latestDts_ !== event.dts) {
  29126. this.numSameDts_ = 0;
  29127. }
  29128. this.numSameDts_++;
  29129. this.latestDts_ = event.dts;
  29130. };
  29131. CaptionStream$2.prototype.flushCCStreams = function (flushType) {
  29132. this.ccStreams_.forEach(function (cc) {
  29133. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  29134. }, this);
  29135. };
  29136. CaptionStream$2.prototype.flushStream = function (flushType) {
  29137. // make sure we actually parsed captions before proceeding
  29138. if (!this.captionPackets_.length) {
  29139. this.flushCCStreams(flushType);
  29140. return;
  29141. } // In Chrome, the Array#sort function is not stable so add a
  29142. // presortIndex that we can use to ensure we get a stable-sort
  29143. this.captionPackets_.forEach(function (elem, idx) {
  29144. elem.presortIndex = idx;
  29145. }); // sort caption byte-pairs based on their PTS values
  29146. this.captionPackets_.sort(function (a, b) {
  29147. if (a.pts === b.pts) {
  29148. return a.presortIndex - b.presortIndex;
  29149. }
  29150. return a.pts - b.pts;
  29151. });
  29152. this.captionPackets_.forEach(function (packet) {
  29153. if (packet.type < 2) {
  29154. // Dispatch packet to the right Cea608Stream
  29155. this.dispatchCea608Packet(packet);
  29156. } else {
  29157. // Dispatch packet to the Cea708Stream
  29158. this.dispatchCea708Packet(packet);
  29159. }
  29160. }, this);
  29161. this.captionPackets_.length = 0;
  29162. this.flushCCStreams(flushType);
  29163. };
  29164. CaptionStream$2.prototype.flush = function () {
  29165. return this.flushStream('flush');
  29166. }; // Only called if handling partial data
  29167. CaptionStream$2.prototype.partialFlush = function () {
  29168. return this.flushStream('partialFlush');
  29169. };
  29170. CaptionStream$2.prototype.reset = function () {
  29171. this.latestDts_ = null;
  29172. this.ignoreNextEqualDts_ = false;
  29173. this.numSameDts_ = 0;
  29174. this.activeCea608Channel_ = [null, null];
  29175. this.ccStreams_.forEach(function (ccStream) {
  29176. ccStream.reset();
  29177. });
  29178. }; // From the CEA-608 spec:
  29179. /*
  29180. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  29181. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  29182. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  29183. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  29184. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  29185. * to switch to captioning or Text.
  29186. */
  29187. // With that in mind, we ignore any data between an XDS control code and a
  29188. // subsequent closed-captioning control code.
  29189. CaptionStream$2.prototype.dispatchCea608Packet = function (packet) {
  29190. // NOTE: packet.type is the CEA608 field
  29191. if (this.setsTextOrXDSActive(packet)) {
  29192. this.activeCea608Channel_[packet.type] = null;
  29193. } else if (this.setsChannel1Active(packet)) {
  29194. this.activeCea608Channel_[packet.type] = 0;
  29195. } else if (this.setsChannel2Active(packet)) {
  29196. this.activeCea608Channel_[packet.type] = 1;
  29197. }
  29198. if (this.activeCea608Channel_[packet.type] === null) {
  29199. // If we haven't received anything to set the active channel, or the
  29200. // packets are Text/XDS data, discard the data; we don't want jumbled
  29201. // captions
  29202. return;
  29203. }
  29204. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  29205. };
  29206. CaptionStream$2.prototype.setsChannel1Active = function (packet) {
  29207. return (packet.ccData & 0x7800) === 0x1000;
  29208. };
  29209. CaptionStream$2.prototype.setsChannel2Active = function (packet) {
  29210. return (packet.ccData & 0x7800) === 0x1800;
  29211. };
  29212. CaptionStream$2.prototype.setsTextOrXDSActive = function (packet) {
  29213. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  29214. };
  29215. CaptionStream$2.prototype.dispatchCea708Packet = function (packet) {
  29216. if (this.parse708captions_) {
  29217. this.cc708Stream_.push(packet);
  29218. }
  29219. }; // ----------------------
  29220. // Session to Application
  29221. // ----------------------
  29222. // This hash maps special and extended character codes to their
  29223. // proper Unicode equivalent. The first one-byte key is just a
  29224. // non-standard character code. The two-byte keys that follow are
  29225. // the extended CEA708 character codes, along with the preceding
  29226. // 0x10 extended character byte to distinguish these codes from
  29227. // non-extended character codes. Every CEA708 character code that
  29228. // is not in this object maps directly to a standard unicode
  29229. // character code.
  29230. // The transparent space and non-breaking transparent space are
  29231. // technically not fully supported since there is no code to
  29232. // make them transparent, so they have normal non-transparent
  29233. // stand-ins.
  29234. // The special closed caption (CC) character isn't a standard
  29235. // unicode character, so a fairly similar unicode character was
  29236. // chosen in it's place.
  29237. var CHARACTER_TRANSLATION_708 = {
  29238. 0x7f: 0x266a,
  29239. // ♪
  29240. 0x1020: 0x20,
  29241. // Transparent Space
  29242. 0x1021: 0xa0,
  29243. // Nob-breaking Transparent Space
  29244. 0x1025: 0x2026,
  29245. // …
  29246. 0x102a: 0x0160,
  29247. // Š
  29248. 0x102c: 0x0152,
  29249. // Œ
  29250. 0x1030: 0x2588,
  29251. // █
  29252. 0x1031: 0x2018,
  29253. // ‘
  29254. 0x1032: 0x2019,
  29255. // ’
  29256. 0x1033: 0x201c,
  29257. // “
  29258. 0x1034: 0x201d,
  29259. // ”
  29260. 0x1035: 0x2022,
  29261. // •
  29262. 0x1039: 0x2122,
  29263. // ™
  29264. 0x103a: 0x0161,
  29265. // š
  29266. 0x103c: 0x0153,
  29267. // œ
  29268. 0x103d: 0x2120,
  29269. // ℠
  29270. 0x103f: 0x0178,
  29271. // Ÿ
  29272. 0x1076: 0x215b,
  29273. // ⅛
  29274. 0x1077: 0x215c,
  29275. // ⅜
  29276. 0x1078: 0x215d,
  29277. // ⅝
  29278. 0x1079: 0x215e,
  29279. // ⅞
  29280. 0x107a: 0x23d0,
  29281. // ⏐
  29282. 0x107b: 0x23a4,
  29283. // ⎤
  29284. 0x107c: 0x23a3,
  29285. // ⎣
  29286. 0x107d: 0x23af,
  29287. // ⎯
  29288. 0x107e: 0x23a6,
  29289. // ⎦
  29290. 0x107f: 0x23a1,
  29291. // ⎡
  29292. 0x10a0: 0x3138 // ㄸ (CC char)
  29293. };
  29294. var get708CharFromCode = function (code) {
  29295. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  29296. if (code & 0x1000 && code === newCode) {
  29297. // Invalid extended code
  29298. return '';
  29299. }
  29300. return String.fromCharCode(newCode);
  29301. };
  29302. var within708TextBlock = function (b) {
  29303. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  29304. };
  29305. var Cea708Window = function (windowNum) {
  29306. this.windowNum = windowNum;
  29307. this.reset();
  29308. };
  29309. Cea708Window.prototype.reset = function () {
  29310. this.clearText();
  29311. this.pendingNewLine = false;
  29312. this.winAttr = {};
  29313. this.penAttr = {};
  29314. this.penLoc = {};
  29315. this.penColor = {}; // These default values are arbitrary,
  29316. // defineWindow will usually override them
  29317. this.visible = 0;
  29318. this.rowLock = 0;
  29319. this.columnLock = 0;
  29320. this.priority = 0;
  29321. this.relativePositioning = 0;
  29322. this.anchorVertical = 0;
  29323. this.anchorHorizontal = 0;
  29324. this.anchorPoint = 0;
  29325. this.rowCount = 1;
  29326. this.virtualRowCount = this.rowCount + 1;
  29327. this.columnCount = 41;
  29328. this.windowStyle = 0;
  29329. this.penStyle = 0;
  29330. };
  29331. Cea708Window.prototype.getText = function () {
  29332. return this.rows.join('\n');
  29333. };
  29334. Cea708Window.prototype.clearText = function () {
  29335. this.rows = [''];
  29336. this.rowIdx = 0;
  29337. };
  29338. Cea708Window.prototype.newLine = function (pts) {
  29339. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  29340. this.beforeRowOverflow(pts);
  29341. }
  29342. if (this.rows.length > 0) {
  29343. this.rows.push('');
  29344. this.rowIdx++;
  29345. } // Show all virtual rows since there's no visible scrolling
  29346. while (this.rows.length > this.virtualRowCount) {
  29347. this.rows.shift();
  29348. this.rowIdx--;
  29349. }
  29350. };
  29351. Cea708Window.prototype.isEmpty = function () {
  29352. if (this.rows.length === 0) {
  29353. return true;
  29354. } else if (this.rows.length === 1) {
  29355. return this.rows[0] === '';
  29356. }
  29357. return false;
  29358. };
  29359. Cea708Window.prototype.addText = function (text) {
  29360. this.rows[this.rowIdx] += text;
  29361. };
  29362. Cea708Window.prototype.backspace = function () {
  29363. if (!this.isEmpty()) {
  29364. var row = this.rows[this.rowIdx];
  29365. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  29366. }
  29367. };
  29368. var Cea708Service = function (serviceNum, encoding, stream) {
  29369. this.serviceNum = serviceNum;
  29370. this.text = '';
  29371. this.currentWindow = new Cea708Window(-1);
  29372. this.windows = [];
  29373. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  29374. if (typeof encoding === 'string') {
  29375. this.createTextDecoder(encoding);
  29376. }
  29377. };
  29378. /**
  29379. * Initialize service windows
  29380. * Must be run before service use
  29381. *
  29382. * @param {Integer} pts PTS value
  29383. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  29384. */
  29385. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  29386. this.startPts = pts;
  29387. for (var win = 0; win < 8; win++) {
  29388. this.windows[win] = new Cea708Window(win);
  29389. if (typeof beforeRowOverflow === 'function') {
  29390. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  29391. }
  29392. }
  29393. };
  29394. /**
  29395. * Set current window of service to be affected by commands
  29396. *
  29397. * @param {Integer} windowNum Window number
  29398. */
  29399. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  29400. this.currentWindow = this.windows[windowNum];
  29401. };
  29402. /**
  29403. * Try to create a TextDecoder if it is natively supported
  29404. */
  29405. Cea708Service.prototype.createTextDecoder = function (encoding) {
  29406. if (typeof TextDecoder === 'undefined') {
  29407. this.stream.trigger('log', {
  29408. level: 'warn',
  29409. message: 'The `encoding` option is unsupported without TextDecoder support'
  29410. });
  29411. } else {
  29412. try {
  29413. this.textDecoder_ = new TextDecoder(encoding);
  29414. } catch (error) {
  29415. this.stream.trigger('log', {
  29416. level: 'warn',
  29417. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  29418. });
  29419. }
  29420. }
  29421. };
  29422. var Cea708Stream = function (options) {
  29423. options = options || {};
  29424. Cea708Stream.prototype.init.call(this);
  29425. var self = this;
  29426. var captionServices = options.captionServices || {};
  29427. var captionServiceEncodings = {};
  29428. var serviceProps; // Get service encodings from captionServices option block
  29429. Object.keys(captionServices).forEach(serviceName => {
  29430. serviceProps = captionServices[serviceName];
  29431. if (/^SERVICE/.test(serviceName)) {
  29432. captionServiceEncodings[serviceName] = serviceProps.encoding;
  29433. }
  29434. });
  29435. this.serviceEncodings = captionServiceEncodings;
  29436. this.current708Packet = null;
  29437. this.services = {};
  29438. this.push = function (packet) {
  29439. if (packet.type === 3) {
  29440. // 708 packet start
  29441. self.new708Packet();
  29442. self.add708Bytes(packet);
  29443. } else {
  29444. if (self.current708Packet === null) {
  29445. // This should only happen at the start of a file if there's no packet start.
  29446. self.new708Packet();
  29447. }
  29448. self.add708Bytes(packet);
  29449. }
  29450. };
  29451. };
  29452. Cea708Stream.prototype = new Stream$7();
  29453. /**
  29454. * Push current 708 packet, create new 708 packet.
  29455. */
  29456. Cea708Stream.prototype.new708Packet = function () {
  29457. if (this.current708Packet !== null) {
  29458. this.push708Packet();
  29459. }
  29460. this.current708Packet = {
  29461. data: [],
  29462. ptsVals: []
  29463. };
  29464. };
  29465. /**
  29466. * Add pts and both bytes from packet into current 708 packet.
  29467. */
  29468. Cea708Stream.prototype.add708Bytes = function (packet) {
  29469. var data = packet.ccData;
  29470. var byte0 = data >>> 8;
  29471. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  29472. // that service blocks will always line up with byte pairs.
  29473. this.current708Packet.ptsVals.push(packet.pts);
  29474. this.current708Packet.data.push(byte0);
  29475. this.current708Packet.data.push(byte1);
  29476. };
  29477. /**
  29478. * Parse completed 708 packet into service blocks and push each service block.
  29479. */
  29480. Cea708Stream.prototype.push708Packet = function () {
  29481. var packet708 = this.current708Packet;
  29482. var packetData = packet708.data;
  29483. var serviceNum = null;
  29484. var blockSize = null;
  29485. var i = 0;
  29486. var b = packetData[i++];
  29487. packet708.seq = b >> 6;
  29488. packet708.sizeCode = b & 0x3f; // 0b00111111;
  29489. for (; i < packetData.length; i++) {
  29490. b = packetData[i++];
  29491. serviceNum = b >> 5;
  29492. blockSize = b & 0x1f; // 0b00011111
  29493. if (serviceNum === 7 && blockSize > 0) {
  29494. // Extended service num
  29495. b = packetData[i++];
  29496. serviceNum = b;
  29497. }
  29498. this.pushServiceBlock(serviceNum, i, blockSize);
  29499. if (blockSize > 0) {
  29500. i += blockSize - 1;
  29501. }
  29502. }
  29503. };
  29504. /**
  29505. * Parse service block, execute commands, read text.
  29506. *
  29507. * Note: While many of these commands serve important purposes,
  29508. * many others just parse out the parameters or attributes, but
  29509. * nothing is done with them because this is not a full and complete
  29510. * implementation of the entire 708 spec.
  29511. *
  29512. * @param {Integer} serviceNum Service number
  29513. * @param {Integer} start Start index of the 708 packet data
  29514. * @param {Integer} size Block size
  29515. */
  29516. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  29517. var b;
  29518. var i = start;
  29519. var packetData = this.current708Packet.data;
  29520. var service = this.services[serviceNum];
  29521. if (!service) {
  29522. service = this.initService(serviceNum, i);
  29523. }
  29524. for (; i < start + size && i < packetData.length; i++) {
  29525. b = packetData[i];
  29526. if (within708TextBlock(b)) {
  29527. i = this.handleText(i, service);
  29528. } else if (b === 0x18) {
  29529. i = this.multiByteCharacter(i, service);
  29530. } else if (b === 0x10) {
  29531. i = this.extendedCommands(i, service);
  29532. } else if (0x80 <= b && b <= 0x87) {
  29533. i = this.setCurrentWindow(i, service);
  29534. } else if (0x98 <= b && b <= 0x9f) {
  29535. i = this.defineWindow(i, service);
  29536. } else if (b === 0x88) {
  29537. i = this.clearWindows(i, service);
  29538. } else if (b === 0x8c) {
  29539. i = this.deleteWindows(i, service);
  29540. } else if (b === 0x89) {
  29541. i = this.displayWindows(i, service);
  29542. } else if (b === 0x8a) {
  29543. i = this.hideWindows(i, service);
  29544. } else if (b === 0x8b) {
  29545. i = this.toggleWindows(i, service);
  29546. } else if (b === 0x97) {
  29547. i = this.setWindowAttributes(i, service);
  29548. } else if (b === 0x90) {
  29549. i = this.setPenAttributes(i, service);
  29550. } else if (b === 0x91) {
  29551. i = this.setPenColor(i, service);
  29552. } else if (b === 0x92) {
  29553. i = this.setPenLocation(i, service);
  29554. } else if (b === 0x8f) {
  29555. service = this.reset(i, service);
  29556. } else if (b === 0x08) {
  29557. // BS: Backspace
  29558. service.currentWindow.backspace();
  29559. } else if (b === 0x0c) {
  29560. // FF: Form feed
  29561. service.currentWindow.clearText();
  29562. } else if (b === 0x0d) {
  29563. // CR: Carriage return
  29564. service.currentWindow.pendingNewLine = true;
  29565. } else if (b === 0x0e) {
  29566. // HCR: Horizontal carriage return
  29567. service.currentWindow.clearText();
  29568. } else if (b === 0x8d) {
  29569. // DLY: Delay, nothing to do
  29570. i++;
  29571. } else ;
  29572. }
  29573. };
  29574. /**
  29575. * Execute an extended command
  29576. *
  29577. * @param {Integer} i Current index in the 708 packet
  29578. * @param {Service} service The service object to be affected
  29579. * @return {Integer} New index after parsing
  29580. */
  29581. Cea708Stream.prototype.extendedCommands = function (i, service) {
  29582. var packetData = this.current708Packet.data;
  29583. var b = packetData[++i];
  29584. if (within708TextBlock(b)) {
  29585. i = this.handleText(i, service, {
  29586. isExtended: true
  29587. });
  29588. }
  29589. return i;
  29590. };
  29591. /**
  29592. * Get PTS value of a given byte index
  29593. *
  29594. * @param {Integer} byteIndex Index of the byte
  29595. * @return {Integer} PTS
  29596. */
  29597. Cea708Stream.prototype.getPts = function (byteIndex) {
  29598. // There's 1 pts value per 2 bytes
  29599. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  29600. };
  29601. /**
  29602. * Initializes a service
  29603. *
  29604. * @param {Integer} serviceNum Service number
  29605. * @return {Service} Initialized service object
  29606. */
  29607. Cea708Stream.prototype.initService = function (serviceNum, i) {
  29608. var serviceName = 'SERVICE' + serviceNum;
  29609. var self = this;
  29610. var serviceName;
  29611. var encoding;
  29612. if (serviceName in this.serviceEncodings) {
  29613. encoding = this.serviceEncodings[serviceName];
  29614. }
  29615. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  29616. this.services[serviceNum].init(this.getPts(i), function (pts) {
  29617. self.flushDisplayed(pts, self.services[serviceNum]);
  29618. });
  29619. return this.services[serviceNum];
  29620. };
  29621. /**
  29622. * Execute text writing to current window
  29623. *
  29624. * @param {Integer} i Current index in the 708 packet
  29625. * @param {Service} service The service object to be affected
  29626. * @return {Integer} New index after parsing
  29627. */
  29628. Cea708Stream.prototype.handleText = function (i, service, options) {
  29629. var isExtended = options && options.isExtended;
  29630. var isMultiByte = options && options.isMultiByte;
  29631. var packetData = this.current708Packet.data;
  29632. var extended = isExtended ? 0x1000 : 0x0000;
  29633. var currentByte = packetData[i];
  29634. var nextByte = packetData[i + 1];
  29635. var win = service.currentWindow;
  29636. var char;
  29637. var charCodeArray; // Use the TextDecoder if one was created for this service
  29638. if (service.textDecoder_ && !isExtended) {
  29639. if (isMultiByte) {
  29640. charCodeArray = [currentByte, nextByte];
  29641. i++;
  29642. } else {
  29643. charCodeArray = [currentByte];
  29644. }
  29645. char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  29646. } else {
  29647. char = get708CharFromCode(extended | currentByte);
  29648. }
  29649. if (win.pendingNewLine && !win.isEmpty()) {
  29650. win.newLine(this.getPts(i));
  29651. }
  29652. win.pendingNewLine = false;
  29653. win.addText(char);
  29654. return i;
  29655. };
  29656. /**
  29657. * Handle decoding of multibyte character
  29658. *
  29659. * @param {Integer} i Current index in the 708 packet
  29660. * @param {Service} service The service object to be affected
  29661. * @return {Integer} New index after parsing
  29662. */
  29663. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  29664. var packetData = this.current708Packet.data;
  29665. var firstByte = packetData[i + 1];
  29666. var secondByte = packetData[i + 2];
  29667. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  29668. i = this.handleText(++i, service, {
  29669. isMultiByte: true
  29670. });
  29671. }
  29672. return i;
  29673. };
  29674. /**
  29675. * Parse and execute the CW# command.
  29676. *
  29677. * Set the current window.
  29678. *
  29679. * @param {Integer} i Current index in the 708 packet
  29680. * @param {Service} service The service object to be affected
  29681. * @return {Integer} New index after parsing
  29682. */
  29683. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  29684. var packetData = this.current708Packet.data;
  29685. var b = packetData[i];
  29686. var windowNum = b & 0x07;
  29687. service.setCurrentWindow(windowNum);
  29688. return i;
  29689. };
  29690. /**
  29691. * Parse and execute the DF# command.
  29692. *
  29693. * Define a window and set it as the current window.
  29694. *
  29695. * @param {Integer} i Current index in the 708 packet
  29696. * @param {Service} service The service object to be affected
  29697. * @return {Integer} New index after parsing
  29698. */
  29699. Cea708Stream.prototype.defineWindow = function (i, service) {
  29700. var packetData = this.current708Packet.data;
  29701. var b = packetData[i];
  29702. var windowNum = b & 0x07;
  29703. service.setCurrentWindow(windowNum);
  29704. var win = service.currentWindow;
  29705. b = packetData[++i];
  29706. win.visible = (b & 0x20) >> 5; // v
  29707. win.rowLock = (b & 0x10) >> 4; // rl
  29708. win.columnLock = (b & 0x08) >> 3; // cl
  29709. win.priority = b & 0x07; // p
  29710. b = packetData[++i];
  29711. win.relativePositioning = (b & 0x80) >> 7; // rp
  29712. win.anchorVertical = b & 0x7f; // av
  29713. b = packetData[++i];
  29714. win.anchorHorizontal = b; // ah
  29715. b = packetData[++i];
  29716. win.anchorPoint = (b & 0xf0) >> 4; // ap
  29717. win.rowCount = b & 0x0f; // rc
  29718. b = packetData[++i];
  29719. win.columnCount = b & 0x3f; // cc
  29720. b = packetData[++i];
  29721. win.windowStyle = (b & 0x38) >> 3; // ws
  29722. win.penStyle = b & 0x07; // ps
  29723. // The spec says there are (rowCount+1) "virtual rows"
  29724. win.virtualRowCount = win.rowCount + 1;
  29725. return i;
  29726. };
  29727. /**
  29728. * Parse and execute the SWA command.
  29729. *
  29730. * Set attributes of the current window.
  29731. *
  29732. * @param {Integer} i Current index in the 708 packet
  29733. * @param {Service} service The service object to be affected
  29734. * @return {Integer} New index after parsing
  29735. */
  29736. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  29737. var packetData = this.current708Packet.data;
  29738. var b = packetData[i];
  29739. var winAttr = service.currentWindow.winAttr;
  29740. b = packetData[++i];
  29741. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  29742. winAttr.fillRed = (b & 0x30) >> 4; // fr
  29743. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  29744. winAttr.fillBlue = b & 0x03; // fb
  29745. b = packetData[++i];
  29746. winAttr.borderType = (b & 0xc0) >> 6; // bt
  29747. winAttr.borderRed = (b & 0x30) >> 4; // br
  29748. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  29749. winAttr.borderBlue = b & 0x03; // bb
  29750. b = packetData[++i];
  29751. winAttr.borderType += (b & 0x80) >> 5; // bt
  29752. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  29753. winAttr.printDirection = (b & 0x30) >> 4; // pd
  29754. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  29755. winAttr.justify = b & 0x03; // j
  29756. b = packetData[++i];
  29757. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  29758. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  29759. winAttr.displayEffect = b & 0x03; // de
  29760. return i;
  29761. };
  29762. /**
  29763. * Gather text from all displayed windows and push a caption to output.
  29764. *
  29765. * @param {Integer} i Current index in the 708 packet
  29766. * @param {Service} service The service object to be affected
  29767. */
  29768. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  29769. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  29770. // display text in the correct order, but sample files so far have not shown any issue.
  29771. for (var winId = 0; winId < 8; winId++) {
  29772. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  29773. displayedText.push(service.windows[winId].getText());
  29774. }
  29775. }
  29776. service.endPts = pts;
  29777. service.text = displayedText.join('\n\n');
  29778. this.pushCaption(service);
  29779. service.startPts = pts;
  29780. };
  29781. /**
  29782. * Push a caption to output if the caption contains text.
  29783. *
  29784. * @param {Service} service The service object to be affected
  29785. */
  29786. Cea708Stream.prototype.pushCaption = function (service) {
  29787. if (service.text !== '') {
  29788. this.trigger('data', {
  29789. startPts: service.startPts,
  29790. endPts: service.endPts,
  29791. text: service.text,
  29792. stream: 'cc708_' + service.serviceNum
  29793. });
  29794. service.text = '';
  29795. service.startPts = service.endPts;
  29796. }
  29797. };
  29798. /**
  29799. * Parse and execute the DSW command.
  29800. *
  29801. * Set visible property of windows based on the parsed bitmask.
  29802. *
  29803. * @param {Integer} i Current index in the 708 packet
  29804. * @param {Service} service The service object to be affected
  29805. * @return {Integer} New index after parsing
  29806. */
  29807. Cea708Stream.prototype.displayWindows = function (i, service) {
  29808. var packetData = this.current708Packet.data;
  29809. var b = packetData[++i];
  29810. var pts = this.getPts(i);
  29811. this.flushDisplayed(pts, service);
  29812. for (var winId = 0; winId < 8; winId++) {
  29813. if (b & 0x01 << winId) {
  29814. service.windows[winId].visible = 1;
  29815. }
  29816. }
  29817. return i;
  29818. };
  29819. /**
  29820. * Parse and execute the HDW command.
  29821. *
  29822. * Set visible property of windows based on the parsed bitmask.
  29823. *
  29824. * @param {Integer} i Current index in the 708 packet
  29825. * @param {Service} service The service object to be affected
  29826. * @return {Integer} New index after parsing
  29827. */
  29828. Cea708Stream.prototype.hideWindows = function (i, service) {
  29829. var packetData = this.current708Packet.data;
  29830. var b = packetData[++i];
  29831. var pts = this.getPts(i);
  29832. this.flushDisplayed(pts, service);
  29833. for (var winId = 0; winId < 8; winId++) {
  29834. if (b & 0x01 << winId) {
  29835. service.windows[winId].visible = 0;
  29836. }
  29837. }
  29838. return i;
  29839. };
  29840. /**
  29841. * Parse and execute the TGW command.
  29842. *
  29843. * Set visible property of windows based on the parsed bitmask.
  29844. *
  29845. * @param {Integer} i Current index in the 708 packet
  29846. * @param {Service} service The service object to be affected
  29847. * @return {Integer} New index after parsing
  29848. */
  29849. Cea708Stream.prototype.toggleWindows = function (i, service) {
  29850. var packetData = this.current708Packet.data;
  29851. var b = packetData[++i];
  29852. var pts = this.getPts(i);
  29853. this.flushDisplayed(pts, service);
  29854. for (var winId = 0; winId < 8; winId++) {
  29855. if (b & 0x01 << winId) {
  29856. service.windows[winId].visible ^= 1;
  29857. }
  29858. }
  29859. return i;
  29860. };
  29861. /**
  29862. * Parse and execute the CLW command.
  29863. *
  29864. * Clear text of windows based on the parsed bitmask.
  29865. *
  29866. * @param {Integer} i Current index in the 708 packet
  29867. * @param {Service} service The service object to be affected
  29868. * @return {Integer} New index after parsing
  29869. */
  29870. Cea708Stream.prototype.clearWindows = function (i, service) {
  29871. var packetData = this.current708Packet.data;
  29872. var b = packetData[++i];
  29873. var pts = this.getPts(i);
  29874. this.flushDisplayed(pts, service);
  29875. for (var winId = 0; winId < 8; winId++) {
  29876. if (b & 0x01 << winId) {
  29877. service.windows[winId].clearText();
  29878. }
  29879. }
  29880. return i;
  29881. };
  29882. /**
  29883. * Parse and execute the DLW command.
  29884. *
  29885. * Re-initialize windows based on the parsed bitmask.
  29886. *
  29887. * @param {Integer} i Current index in the 708 packet
  29888. * @param {Service} service The service object to be affected
  29889. * @return {Integer} New index after parsing
  29890. */
  29891. Cea708Stream.prototype.deleteWindows = function (i, service) {
  29892. var packetData = this.current708Packet.data;
  29893. var b = packetData[++i];
  29894. var pts = this.getPts(i);
  29895. this.flushDisplayed(pts, service);
  29896. for (var winId = 0; winId < 8; winId++) {
  29897. if (b & 0x01 << winId) {
  29898. service.windows[winId].reset();
  29899. }
  29900. }
  29901. return i;
  29902. };
  29903. /**
  29904. * Parse and execute the SPA command.
  29905. *
  29906. * Set pen attributes of the current window.
  29907. *
  29908. * @param {Integer} i Current index in the 708 packet
  29909. * @param {Service} service The service object to be affected
  29910. * @return {Integer} New index after parsing
  29911. */
  29912. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  29913. var packetData = this.current708Packet.data;
  29914. var b = packetData[i];
  29915. var penAttr = service.currentWindow.penAttr;
  29916. b = packetData[++i];
  29917. penAttr.textTag = (b & 0xf0) >> 4; // tt
  29918. penAttr.offset = (b & 0x0c) >> 2; // o
  29919. penAttr.penSize = b & 0x03; // s
  29920. b = packetData[++i];
  29921. penAttr.italics = (b & 0x80) >> 7; // i
  29922. penAttr.underline = (b & 0x40) >> 6; // u
  29923. penAttr.edgeType = (b & 0x38) >> 3; // et
  29924. penAttr.fontStyle = b & 0x07; // fs
  29925. return i;
  29926. };
  29927. /**
  29928. * Parse and execute the SPC command.
  29929. *
  29930. * Set pen color of the current window.
  29931. *
  29932. * @param {Integer} i Current index in the 708 packet
  29933. * @param {Service} service The service object to be affected
  29934. * @return {Integer} New index after parsing
  29935. */
  29936. Cea708Stream.prototype.setPenColor = function (i, service) {
  29937. var packetData = this.current708Packet.data;
  29938. var b = packetData[i];
  29939. var penColor = service.currentWindow.penColor;
  29940. b = packetData[++i];
  29941. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  29942. penColor.fgRed = (b & 0x30) >> 4; // fr
  29943. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  29944. penColor.fgBlue = b & 0x03; // fb
  29945. b = packetData[++i];
  29946. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  29947. penColor.bgRed = (b & 0x30) >> 4; // br
  29948. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  29949. penColor.bgBlue = b & 0x03; // bb
  29950. b = packetData[++i];
  29951. penColor.edgeRed = (b & 0x30) >> 4; // er
  29952. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  29953. penColor.edgeBlue = b & 0x03; // eb
  29954. return i;
  29955. };
  29956. /**
  29957. * Parse and execute the SPL command.
  29958. *
  29959. * Set pen location of the current window.
  29960. *
  29961. * @param {Integer} i Current index in the 708 packet
  29962. * @param {Service} service The service object to be affected
  29963. * @return {Integer} New index after parsing
  29964. */
  29965. Cea708Stream.prototype.setPenLocation = function (i, service) {
  29966. var packetData = this.current708Packet.data;
  29967. var b = packetData[i];
  29968. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  29969. service.currentWindow.pendingNewLine = true;
  29970. b = packetData[++i];
  29971. penLoc.row = b & 0x0f; // r
  29972. b = packetData[++i];
  29973. penLoc.column = b & 0x3f; // c
  29974. return i;
  29975. };
  29976. /**
  29977. * Execute the RST command.
  29978. *
  29979. * Reset service to a clean slate. Re-initialize.
  29980. *
  29981. * @param {Integer} i Current index in the 708 packet
  29982. * @param {Service} service The service object to be affected
  29983. * @return {Service} Re-initialized service
  29984. */
  29985. Cea708Stream.prototype.reset = function (i, service) {
  29986. var pts = this.getPts(i);
  29987. this.flushDisplayed(pts, service);
  29988. return this.initService(service.serviceNum, i);
  29989. }; // This hash maps non-ASCII, special, and extended character codes to their
  29990. // proper Unicode equivalent. The first keys that are only a single byte
  29991. // are the non-standard ASCII characters, which simply map the CEA608 byte
  29992. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  29993. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  29994. // can be performed regardless of the field and data channel on which the
  29995. // character code was received.
  29996. var CHARACTER_TRANSLATION = {
  29997. 0x2a: 0xe1,
  29998. // á
  29999. 0x5c: 0xe9,
  30000. // é
  30001. 0x5e: 0xed,
  30002. // í
  30003. 0x5f: 0xf3,
  30004. // ó
  30005. 0x60: 0xfa,
  30006. // ú
  30007. 0x7b: 0xe7,
  30008. // ç
  30009. 0x7c: 0xf7,
  30010. // ÷
  30011. 0x7d: 0xd1,
  30012. // Ñ
  30013. 0x7e: 0xf1,
  30014. // ñ
  30015. 0x7f: 0x2588,
  30016. // █
  30017. 0x0130: 0xae,
  30018. // ®
  30019. 0x0131: 0xb0,
  30020. // °
  30021. 0x0132: 0xbd,
  30022. // ½
  30023. 0x0133: 0xbf,
  30024. // ¿
  30025. 0x0134: 0x2122,
  30026. // ™
  30027. 0x0135: 0xa2,
  30028. // ¢
  30029. 0x0136: 0xa3,
  30030. // £
  30031. 0x0137: 0x266a,
  30032. // ♪
  30033. 0x0138: 0xe0,
  30034. // à
  30035. 0x0139: 0xa0,
  30036. //
  30037. 0x013a: 0xe8,
  30038. // è
  30039. 0x013b: 0xe2,
  30040. // â
  30041. 0x013c: 0xea,
  30042. // ê
  30043. 0x013d: 0xee,
  30044. // î
  30045. 0x013e: 0xf4,
  30046. // ô
  30047. 0x013f: 0xfb,
  30048. // û
  30049. 0x0220: 0xc1,
  30050. // Á
  30051. 0x0221: 0xc9,
  30052. // É
  30053. 0x0222: 0xd3,
  30054. // Ó
  30055. 0x0223: 0xda,
  30056. // Ú
  30057. 0x0224: 0xdc,
  30058. // Ü
  30059. 0x0225: 0xfc,
  30060. // ü
  30061. 0x0226: 0x2018,
  30062. // ‘
  30063. 0x0227: 0xa1,
  30064. // ¡
  30065. 0x0228: 0x2a,
  30066. // *
  30067. 0x0229: 0x27,
  30068. // '
  30069. 0x022a: 0x2014,
  30070. // —
  30071. 0x022b: 0xa9,
  30072. // ©
  30073. 0x022c: 0x2120,
  30074. // ℠
  30075. 0x022d: 0x2022,
  30076. // •
  30077. 0x022e: 0x201c,
  30078. // “
  30079. 0x022f: 0x201d,
  30080. // ”
  30081. 0x0230: 0xc0,
  30082. // À
  30083. 0x0231: 0xc2,
  30084. // Â
  30085. 0x0232: 0xc7,
  30086. // Ç
  30087. 0x0233: 0xc8,
  30088. // È
  30089. 0x0234: 0xca,
  30090. // Ê
  30091. 0x0235: 0xcb,
  30092. // Ë
  30093. 0x0236: 0xeb,
  30094. // ë
  30095. 0x0237: 0xce,
  30096. // Î
  30097. 0x0238: 0xcf,
  30098. // Ï
  30099. 0x0239: 0xef,
  30100. // ï
  30101. 0x023a: 0xd4,
  30102. // Ô
  30103. 0x023b: 0xd9,
  30104. // Ù
  30105. 0x023c: 0xf9,
  30106. // ù
  30107. 0x023d: 0xdb,
  30108. // Û
  30109. 0x023e: 0xab,
  30110. // «
  30111. 0x023f: 0xbb,
  30112. // »
  30113. 0x0320: 0xc3,
  30114. // Ã
  30115. 0x0321: 0xe3,
  30116. // ã
  30117. 0x0322: 0xcd,
  30118. // Í
  30119. 0x0323: 0xcc,
  30120. // Ì
  30121. 0x0324: 0xec,
  30122. // ì
  30123. 0x0325: 0xd2,
  30124. // Ò
  30125. 0x0326: 0xf2,
  30126. // ò
  30127. 0x0327: 0xd5,
  30128. // Õ
  30129. 0x0328: 0xf5,
  30130. // õ
  30131. 0x0329: 0x7b,
  30132. // {
  30133. 0x032a: 0x7d,
  30134. // }
  30135. 0x032b: 0x5c,
  30136. // \
  30137. 0x032c: 0x5e,
  30138. // ^
  30139. 0x032d: 0x5f,
  30140. // _
  30141. 0x032e: 0x7c,
  30142. // |
  30143. 0x032f: 0x7e,
  30144. // ~
  30145. 0x0330: 0xc4,
  30146. // Ä
  30147. 0x0331: 0xe4,
  30148. // ä
  30149. 0x0332: 0xd6,
  30150. // Ö
  30151. 0x0333: 0xf6,
  30152. // ö
  30153. 0x0334: 0xdf,
  30154. // ß
  30155. 0x0335: 0xa5,
  30156. // ¥
  30157. 0x0336: 0xa4,
  30158. // ¤
  30159. 0x0337: 0x2502,
  30160. // │
  30161. 0x0338: 0xc5,
  30162. // Å
  30163. 0x0339: 0xe5,
  30164. // å
  30165. 0x033a: 0xd8,
  30166. // Ø
  30167. 0x033b: 0xf8,
  30168. // ø
  30169. 0x033c: 0x250c,
  30170. // ┌
  30171. 0x033d: 0x2510,
  30172. // ┐
  30173. 0x033e: 0x2514,
  30174. // └
  30175. 0x033f: 0x2518 // ┘
  30176. };
  30177. var getCharFromCode = function (code) {
  30178. if (code === null) {
  30179. return '';
  30180. }
  30181. code = CHARACTER_TRANSLATION[code] || code;
  30182. return String.fromCharCode(code);
  30183. }; // the index of the last row in a CEA-608 display buffer
  30184. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  30185. // getting it through bit logic.
  30186. 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
  30187. // cells. The "bottom" row is the last element in the outer array.
  30188. var createDisplayBuffer = function () {
  30189. var result = [],
  30190. i = BOTTOM_ROW + 1;
  30191. while (i--) {
  30192. result.push('');
  30193. }
  30194. return result;
  30195. };
  30196. var Cea608Stream = function (field, dataChannel) {
  30197. Cea608Stream.prototype.init.call(this);
  30198. this.field_ = field || 0;
  30199. this.dataChannel_ = dataChannel || 0;
  30200. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  30201. this.setConstants();
  30202. this.reset();
  30203. this.push = function (packet) {
  30204. var data, swap, char0, char1, text; // remove the parity bits
  30205. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  30206. if (data === this.lastControlCode_) {
  30207. this.lastControlCode_ = null;
  30208. return;
  30209. } // Store control codes
  30210. if ((data & 0xf000) === 0x1000) {
  30211. this.lastControlCode_ = data;
  30212. } else if (data !== this.PADDING_) {
  30213. this.lastControlCode_ = null;
  30214. }
  30215. char0 = data >>> 8;
  30216. char1 = data & 0xff;
  30217. if (data === this.PADDING_) {
  30218. return;
  30219. } else if (data === this.RESUME_CAPTION_LOADING_) {
  30220. this.mode_ = 'popOn';
  30221. } else if (data === this.END_OF_CAPTION_) {
  30222. // If an EOC is received while in paint-on mode, the displayed caption
  30223. // text should be swapped to non-displayed memory as if it was a pop-on
  30224. // caption. Because of that, we should explicitly switch back to pop-on
  30225. // mode
  30226. this.mode_ = 'popOn';
  30227. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  30228. this.flushDisplayed(packet.pts); // flip memory
  30229. swap = this.displayed_;
  30230. this.displayed_ = this.nonDisplayed_;
  30231. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  30232. this.startPts_ = packet.pts;
  30233. } else if (data === this.ROLL_UP_2_ROWS_) {
  30234. this.rollUpRows_ = 2;
  30235. this.setRollUp(packet.pts);
  30236. } else if (data === this.ROLL_UP_3_ROWS_) {
  30237. this.rollUpRows_ = 3;
  30238. this.setRollUp(packet.pts);
  30239. } else if (data === this.ROLL_UP_4_ROWS_) {
  30240. this.rollUpRows_ = 4;
  30241. this.setRollUp(packet.pts);
  30242. } else if (data === this.CARRIAGE_RETURN_) {
  30243. this.clearFormatting(packet.pts);
  30244. this.flushDisplayed(packet.pts);
  30245. this.shiftRowsUp_();
  30246. this.startPts_ = packet.pts;
  30247. } else if (data === this.BACKSPACE_) {
  30248. if (this.mode_ === 'popOn') {
  30249. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  30250. } else {
  30251. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  30252. }
  30253. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  30254. this.flushDisplayed(packet.pts);
  30255. this.displayed_ = createDisplayBuffer();
  30256. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  30257. this.nonDisplayed_ = createDisplayBuffer();
  30258. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  30259. if (this.mode_ !== 'paintOn') {
  30260. // NOTE: This should be removed when proper caption positioning is
  30261. // implemented
  30262. this.flushDisplayed(packet.pts);
  30263. this.displayed_ = createDisplayBuffer();
  30264. }
  30265. this.mode_ = 'paintOn';
  30266. this.startPts_ = packet.pts; // Append special characters to caption text
  30267. } else if (this.isSpecialCharacter(char0, char1)) {
  30268. // Bitmask char0 so that we can apply character transformations
  30269. // regardless of field and data channel.
  30270. // Then byte-shift to the left and OR with char1 so we can pass the
  30271. // entire character code to `getCharFromCode`.
  30272. char0 = (char0 & 0x03) << 8;
  30273. text = getCharFromCode(char0 | char1);
  30274. this[this.mode_](packet.pts, text);
  30275. this.column_++; // Append extended characters to caption text
  30276. } else if (this.isExtCharacter(char0, char1)) {
  30277. // Extended characters always follow their "non-extended" equivalents.
  30278. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  30279. // decoders are supposed to drop the "è", while compliant decoders
  30280. // backspace the "e" and insert "è".
  30281. // Delete the previous character
  30282. if (this.mode_ === 'popOn') {
  30283. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  30284. } else {
  30285. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  30286. } // Bitmask char0 so that we can apply character transformations
  30287. // regardless of field and data channel.
  30288. // Then byte-shift to the left and OR with char1 so we can pass the
  30289. // entire character code to `getCharFromCode`.
  30290. char0 = (char0 & 0x03) << 8;
  30291. text = getCharFromCode(char0 | char1);
  30292. this[this.mode_](packet.pts, text);
  30293. this.column_++; // Process mid-row codes
  30294. } else if (this.isMidRowCode(char0, char1)) {
  30295. // Attributes are not additive, so clear all formatting
  30296. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  30297. // should be replaced with spaces, so add one now
  30298. this[this.mode_](packet.pts, ' ');
  30299. this.column_++;
  30300. if ((char1 & 0xe) === 0xe) {
  30301. this.addFormatting(packet.pts, ['i']);
  30302. }
  30303. if ((char1 & 0x1) === 0x1) {
  30304. this.addFormatting(packet.pts, ['u']);
  30305. } // Detect offset control codes and adjust cursor
  30306. } else if (this.isOffsetControlCode(char0, char1)) {
  30307. // Cursor position is set by indent PAC (see below) in 4-column
  30308. // increments, with an additional offset code of 1-3 to reach any
  30309. // of the 32 columns specified by CEA-608. So all we need to do
  30310. // here is increment the column cursor by the given offset.
  30311. this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
  30312. } else if (this.isPAC(char0, char1)) {
  30313. // There's no logic for PAC -> row mapping, so we have to just
  30314. // find the row code in an array and use its index :(
  30315. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  30316. if (this.mode_ === 'rollUp') {
  30317. // This implies that the base row is incorrectly set.
  30318. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  30319. // of roll-up rows set.
  30320. if (row - this.rollUpRows_ + 1 < 0) {
  30321. row = this.rollUpRows_ - 1;
  30322. }
  30323. this.setRollUp(packet.pts, row);
  30324. }
  30325. if (row !== this.row_) {
  30326. // formatting is only persistent for current row
  30327. this.clearFormatting(packet.pts);
  30328. this.row_ = row;
  30329. } // All PACs can apply underline, so detect and apply
  30330. // (All odd-numbered second bytes set underline)
  30331. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  30332. this.addFormatting(packet.pts, ['u']);
  30333. }
  30334. if ((data & 0x10) === 0x10) {
  30335. // We've got an indent level code. Each successive even number
  30336. // increments the column cursor by 4, so we can get the desired
  30337. // column position by bit-shifting to the right (to get n/2)
  30338. // and multiplying by 4.
  30339. this.column_ = ((data & 0xe) >> 1) * 4;
  30340. }
  30341. if (this.isColorPAC(char1)) {
  30342. // it's a color code, though we only support white, which
  30343. // can be either normal or italicized. white italics can be
  30344. // either 0x4e or 0x6e depending on the row, so we just
  30345. // bitwise-and with 0xe to see if italics should be turned on
  30346. if ((char1 & 0xe) === 0xe) {
  30347. this.addFormatting(packet.pts, ['i']);
  30348. }
  30349. } // We have a normal character in char0, and possibly one in char1
  30350. } else if (this.isNormalChar(char0)) {
  30351. if (char1 === 0x00) {
  30352. char1 = null;
  30353. }
  30354. text = getCharFromCode(char0);
  30355. text += getCharFromCode(char1);
  30356. this[this.mode_](packet.pts, text);
  30357. this.column_ += text.length;
  30358. } // finish data processing
  30359. };
  30360. };
  30361. Cea608Stream.prototype = new Stream$7(); // Trigger a cue point that captures the current state of the
  30362. // display buffer
  30363. Cea608Stream.prototype.flushDisplayed = function (pts) {
  30364. var content = this.displayed_ // remove spaces from the start and end of the string
  30365. .map(function (row, index) {
  30366. try {
  30367. return row.trim();
  30368. } catch (e) {
  30369. // Ordinarily, this shouldn't happen. However, caption
  30370. // parsing errors should not throw exceptions and
  30371. // break playback.
  30372. this.trigger('log', {
  30373. level: 'warn',
  30374. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  30375. });
  30376. return '';
  30377. }
  30378. }, this) // combine all text rows to display in one cue
  30379. .join('\n') // and remove blank rows from the start and end, but not the middle
  30380. .replace(/^\n+|\n+$/g, '');
  30381. if (content.length) {
  30382. this.trigger('data', {
  30383. startPts: this.startPts_,
  30384. endPts: pts,
  30385. text: content,
  30386. stream: this.name_
  30387. });
  30388. }
  30389. };
  30390. /**
  30391. * Zero out the data, used for startup and on seek
  30392. */
  30393. Cea608Stream.prototype.reset = function () {
  30394. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  30395. // actually display captions. If a caption is shifted to a row
  30396. // with a lower index than this, it is cleared from the display
  30397. // buffer
  30398. this.topRow_ = 0;
  30399. this.startPts_ = 0;
  30400. this.displayed_ = createDisplayBuffer();
  30401. this.nonDisplayed_ = createDisplayBuffer();
  30402. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  30403. this.column_ = 0;
  30404. this.row_ = BOTTOM_ROW;
  30405. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  30406. this.formatting_ = [];
  30407. };
  30408. /**
  30409. * Sets up control code and related constants for this instance
  30410. */
  30411. Cea608Stream.prototype.setConstants = function () {
  30412. // The following attributes have these uses:
  30413. // ext_ : char0 for mid-row codes, and the base for extended
  30414. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  30415. // extended codes)
  30416. // control_: char0 for control codes, except byte-shifted to the
  30417. // left so that we can do this.control_ | CONTROL_CODE
  30418. // offset_: char0 for tab offset codes
  30419. //
  30420. // It's also worth noting that control codes, and _only_ control codes,
  30421. // differ between field 1 and field2. Field 2 control codes are always
  30422. // their field 1 value plus 1. That's why there's the "| field" on the
  30423. // control value.
  30424. if (this.dataChannel_ === 0) {
  30425. this.BASE_ = 0x10;
  30426. this.EXT_ = 0x11;
  30427. this.CONTROL_ = (0x14 | this.field_) << 8;
  30428. this.OFFSET_ = 0x17;
  30429. } else if (this.dataChannel_ === 1) {
  30430. this.BASE_ = 0x18;
  30431. this.EXT_ = 0x19;
  30432. this.CONTROL_ = (0x1c | this.field_) << 8;
  30433. this.OFFSET_ = 0x1f;
  30434. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  30435. // list is not exhaustive. For a more comprehensive listing and semantics see
  30436. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  30437. // Padding
  30438. this.PADDING_ = 0x0000; // Pop-on Mode
  30439. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  30440. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  30441. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  30442. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  30443. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  30444. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  30445. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  30446. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  30447. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  30448. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  30449. };
  30450. /**
  30451. * Detects if the 2-byte packet data is a special character
  30452. *
  30453. * Special characters have a second byte in the range 0x30 to 0x3f,
  30454. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  30455. * data channel 2).
  30456. *
  30457. * @param {Integer} char0 The first byte
  30458. * @param {Integer} char1 The second byte
  30459. * @return {Boolean} Whether the 2 bytes are an special character
  30460. */
  30461. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  30462. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  30463. };
  30464. /**
  30465. * Detects if the 2-byte packet data is an extended character
  30466. *
  30467. * Extended characters have a second byte in the range 0x20 to 0x3f,
  30468. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  30469. * 0x1a or 0x1b (for data channel 2).
  30470. *
  30471. * @param {Integer} char0 The first byte
  30472. * @param {Integer} char1 The second byte
  30473. * @return {Boolean} Whether the 2 bytes are an extended character
  30474. */
  30475. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  30476. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  30477. };
  30478. /**
  30479. * Detects if the 2-byte packet is a mid-row code
  30480. *
  30481. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  30482. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  30483. * channel 2).
  30484. *
  30485. * @param {Integer} char0 The first byte
  30486. * @param {Integer} char1 The second byte
  30487. * @return {Boolean} Whether the 2 bytes are a mid-row code
  30488. */
  30489. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  30490. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  30491. };
  30492. /**
  30493. * Detects if the 2-byte packet is an offset control code
  30494. *
  30495. * Offset control codes have a second byte in the range 0x21 to 0x23,
  30496. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  30497. * data channel 2).
  30498. *
  30499. * @param {Integer} char0 The first byte
  30500. * @param {Integer} char1 The second byte
  30501. * @return {Boolean} Whether the 2 bytes are an offset control code
  30502. */
  30503. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  30504. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  30505. };
  30506. /**
  30507. * Detects if the 2-byte packet is a Preamble Address Code
  30508. *
  30509. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  30510. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  30511. * range 0x40 to 0x7f.
  30512. *
  30513. * @param {Integer} char0 The first byte
  30514. * @param {Integer} char1 The second byte
  30515. * @return {Boolean} Whether the 2 bytes are a PAC
  30516. */
  30517. Cea608Stream.prototype.isPAC = function (char0, char1) {
  30518. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  30519. };
  30520. /**
  30521. * Detects if a packet's second byte is in the range of a PAC color code
  30522. *
  30523. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  30524. * 0x60 to 0x6f.
  30525. *
  30526. * @param {Integer} char1 The second byte
  30527. * @return {Boolean} Whether the byte is a color PAC
  30528. */
  30529. Cea608Stream.prototype.isColorPAC = function (char1) {
  30530. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  30531. };
  30532. /**
  30533. * Detects if a single byte is in the range of a normal character
  30534. *
  30535. * Normal text bytes are in the range 0x20 to 0x7f.
  30536. *
  30537. * @param {Integer} char The byte
  30538. * @return {Boolean} Whether the byte is a normal character
  30539. */
  30540. Cea608Stream.prototype.isNormalChar = function (char) {
  30541. return char >= 0x20 && char <= 0x7f;
  30542. };
  30543. /**
  30544. * Configures roll-up
  30545. *
  30546. * @param {Integer} pts Current PTS
  30547. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  30548. * a new position
  30549. */
  30550. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  30551. // Reset the base row to the bottom row when switching modes
  30552. if (this.mode_ !== 'rollUp') {
  30553. this.row_ = BOTTOM_ROW;
  30554. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  30555. this.flushDisplayed(pts);
  30556. this.nonDisplayed_ = createDisplayBuffer();
  30557. this.displayed_ = createDisplayBuffer();
  30558. }
  30559. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  30560. // move currently displayed captions (up or down) to the new base row
  30561. for (var i = 0; i < this.rollUpRows_; i++) {
  30562. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  30563. this.displayed_[this.row_ - i] = '';
  30564. }
  30565. }
  30566. if (newBaseRow === undefined) {
  30567. newBaseRow = this.row_;
  30568. }
  30569. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  30570. }; // Adds the opening HTML tag for the passed character to the caption text,
  30571. // and keeps track of it for later closing
  30572. Cea608Stream.prototype.addFormatting = function (pts, format) {
  30573. this.formatting_ = this.formatting_.concat(format);
  30574. var text = format.reduce(function (text, format) {
  30575. return text + '<' + format + '>';
  30576. }, '');
  30577. this[this.mode_](pts, text);
  30578. }; // Adds HTML closing tags for current formatting to caption text and
  30579. // clears remembered formatting
  30580. Cea608Stream.prototype.clearFormatting = function (pts) {
  30581. if (!this.formatting_.length) {
  30582. return;
  30583. }
  30584. var text = this.formatting_.reverse().reduce(function (text, format) {
  30585. return text + '</' + format + '>';
  30586. }, '');
  30587. this.formatting_ = [];
  30588. this[this.mode_](pts, text);
  30589. }; // Mode Implementations
  30590. Cea608Stream.prototype.popOn = function (pts, text) {
  30591. var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
  30592. baseRow += text;
  30593. this.nonDisplayed_[this.row_] = baseRow;
  30594. };
  30595. Cea608Stream.prototype.rollUp = function (pts, text) {
  30596. var baseRow = this.displayed_[this.row_];
  30597. baseRow += text;
  30598. this.displayed_[this.row_] = baseRow;
  30599. };
  30600. Cea608Stream.prototype.shiftRowsUp_ = function () {
  30601. var i; // clear out inactive rows
  30602. for (i = 0; i < this.topRow_; i++) {
  30603. this.displayed_[i] = '';
  30604. }
  30605. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  30606. this.displayed_[i] = '';
  30607. } // shift displayed rows up
  30608. for (i = this.topRow_; i < this.row_; i++) {
  30609. this.displayed_[i] = this.displayed_[i + 1];
  30610. } // clear out the bottom row
  30611. this.displayed_[this.row_] = '';
  30612. };
  30613. Cea608Stream.prototype.paintOn = function (pts, text) {
  30614. var baseRow = this.displayed_[this.row_];
  30615. baseRow += text;
  30616. this.displayed_[this.row_] = baseRow;
  30617. }; // exports
  30618. var captionStream = {
  30619. CaptionStream: CaptionStream$2,
  30620. Cea608Stream: Cea608Stream,
  30621. Cea708Stream: Cea708Stream
  30622. };
  30623. /**
  30624. * mux.js
  30625. *
  30626. * Copyright (c) Brightcove
  30627. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  30628. */
  30629. var streamTypes = {
  30630. H264_STREAM_TYPE: 0x1B,
  30631. ADTS_STREAM_TYPE: 0x0F,
  30632. METADATA_STREAM_TYPE: 0x15
  30633. };
  30634. /**
  30635. * mux.js
  30636. *
  30637. * Copyright (c) Brightcove
  30638. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  30639. *
  30640. * Accepts program elementary stream (PES) data events and corrects
  30641. * decode and presentation time stamps to account for a rollover
  30642. * of the 33 bit value.
  30643. */
  30644. var Stream$6 = stream;
  30645. var MAX_TS = 8589934592;
  30646. var RO_THRESH = 4294967296;
  30647. var TYPE_SHARED = 'shared';
  30648. var handleRollover$1 = function (value, reference) {
  30649. var direction = 1;
  30650. if (value > reference) {
  30651. // If the current timestamp value is greater than our reference timestamp and we detect a
  30652. // timestamp rollover, this means the roll over is happening in the opposite direction.
  30653. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  30654. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  30655. // rollover point. In loading this segment, the timestamp values will be very large,
  30656. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  30657. // the time stamp to be `value - 2^33`.
  30658. direction = -1;
  30659. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  30660. // cause an incorrect adjustment.
  30661. while (Math.abs(reference - value) > RO_THRESH) {
  30662. value += direction * MAX_TS;
  30663. }
  30664. return value;
  30665. };
  30666. var TimestampRolloverStream$1 = function (type) {
  30667. var lastDTS, referenceDTS;
  30668. TimestampRolloverStream$1.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  30669. // video and audio. We could use `undefined` here, but having a string
  30670. // makes debugging a little clearer.
  30671. this.type_ = type || TYPE_SHARED;
  30672. this.push = function (data) {
  30673. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  30674. // streams will only accept data that matches their type.
  30675. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  30676. return;
  30677. }
  30678. if (referenceDTS === undefined) {
  30679. referenceDTS = data.dts;
  30680. }
  30681. data.dts = handleRollover$1(data.dts, referenceDTS);
  30682. data.pts = handleRollover$1(data.pts, referenceDTS);
  30683. lastDTS = data.dts;
  30684. this.trigger('data', data);
  30685. };
  30686. this.flush = function () {
  30687. referenceDTS = lastDTS;
  30688. this.trigger('done');
  30689. };
  30690. this.endTimeline = function () {
  30691. this.flush();
  30692. this.trigger('endedtimeline');
  30693. };
  30694. this.discontinuity = function () {
  30695. referenceDTS = void 0;
  30696. lastDTS = void 0;
  30697. };
  30698. this.reset = function () {
  30699. this.discontinuity();
  30700. this.trigger('reset');
  30701. };
  30702. };
  30703. TimestampRolloverStream$1.prototype = new Stream$6();
  30704. var timestampRolloverStream = {
  30705. TimestampRolloverStream: TimestampRolloverStream$1,
  30706. handleRollover: handleRollover$1
  30707. }; // Once IE11 support is dropped, this function should be removed.
  30708. var typedArrayIndexOf$1 = (typedArray, element, fromIndex) => {
  30709. if (!typedArray) {
  30710. return -1;
  30711. }
  30712. var currentIndex = fromIndex;
  30713. for (; currentIndex < typedArray.length; currentIndex++) {
  30714. if (typedArray[currentIndex] === element) {
  30715. return currentIndex;
  30716. }
  30717. }
  30718. return -1;
  30719. };
  30720. var typedArray = {
  30721. typedArrayIndexOf: typedArrayIndexOf$1
  30722. };
  30723. /**
  30724. * mux.js
  30725. *
  30726. * Copyright (c) Brightcove
  30727. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  30728. *
  30729. * Tools for parsing ID3 frame data
  30730. * @see http://id3.org/id3v2.3.0
  30731. */
  30732. var typedArrayIndexOf = typedArray.typedArrayIndexOf,
  30733. // Frames that allow different types of text encoding contain a text
  30734. // encoding description byte [ID3v2.4.0 section 4.]
  30735. textEncodingDescriptionByte = {
  30736. Iso88591: 0x00,
  30737. // ISO-8859-1, terminated with \0.
  30738. Utf16: 0x01,
  30739. // UTF-16 encoded Unicode BOM, terminated with \0\0
  30740. Utf16be: 0x02,
  30741. // UTF-16BE encoded Unicode, without BOM, terminated with \0\0
  30742. Utf8: 0x03 // UTF-8 encoded Unicode, terminated with \0
  30743. },
  30744. // return a percent-encoded representation of the specified byte range
  30745. // @see http://en.wikipedia.org/wiki/Percent-encoding
  30746. percentEncode$1 = function (bytes, start, end) {
  30747. var i,
  30748. result = '';
  30749. for (i = start; i < end; i++) {
  30750. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  30751. }
  30752. return result;
  30753. },
  30754. // return the string representation of the specified byte range,
  30755. // interpreted as UTf-8.
  30756. parseUtf8 = function (bytes, start, end) {
  30757. return decodeURIComponent(percentEncode$1(bytes, start, end));
  30758. },
  30759. // return the string representation of the specified byte range,
  30760. // interpreted as ISO-8859-1.
  30761. parseIso88591$1 = function (bytes, start, end) {
  30762. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  30763. },
  30764. parseSyncSafeInteger$1 = function (data) {
  30765. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  30766. },
  30767. frameParsers = {
  30768. 'APIC': function (frame) {
  30769. var i = 1,
  30770. mimeTypeEndIndex,
  30771. descriptionEndIndex,
  30772. LINK_MIME_TYPE = '-->';
  30773. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  30774. // ignore frames with unrecognized character encodings
  30775. return;
  30776. } // parsing fields [ID3v2.4.0 section 4.14.]
  30777. mimeTypeEndIndex = typedArrayIndexOf(frame.data, 0, i);
  30778. if (mimeTypeEndIndex < 0) {
  30779. // malformed frame
  30780. return;
  30781. } // parsing Mime type field (terminated with \0)
  30782. frame.mimeType = parseIso88591$1(frame.data, i, mimeTypeEndIndex);
  30783. i = mimeTypeEndIndex + 1; // parsing 1-byte Picture Type field
  30784. frame.pictureType = frame.data[i];
  30785. i++;
  30786. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, i);
  30787. if (descriptionEndIndex < 0) {
  30788. // malformed frame
  30789. return;
  30790. } // parsing Description field (terminated with \0)
  30791. frame.description = parseUtf8(frame.data, i, descriptionEndIndex);
  30792. i = descriptionEndIndex + 1;
  30793. if (frame.mimeType === LINK_MIME_TYPE) {
  30794. // parsing Picture Data field as URL (always represented as ISO-8859-1 [ID3v2.4.0 section 4.])
  30795. frame.url = parseIso88591$1(frame.data, i, frame.data.length);
  30796. } else {
  30797. // parsing Picture Data field as binary data
  30798. frame.pictureData = frame.data.subarray(i, frame.data.length);
  30799. }
  30800. },
  30801. 'T*': function (frame) {
  30802. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  30803. // ignore frames with unrecognized character encodings
  30804. return;
  30805. } // parse text field, do not include null terminator in the frame value
  30806. // frames that allow different types of encoding contain terminated text [ID3v2.4.0 section 4.]
  30807. 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.]
  30808. frame.values = frame.value.split('\0');
  30809. },
  30810. 'TXXX': function (frame) {
  30811. var descriptionEndIndex;
  30812. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  30813. // ignore frames with unrecognized character encodings
  30814. return;
  30815. }
  30816. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  30817. if (descriptionEndIndex === -1) {
  30818. return;
  30819. } // parse the text fields
  30820. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // do not include the null terminator in the tag value
  30821. // frames that allow different types of encoding contain terminated text
  30822. // [ID3v2.4.0 section 4.]
  30823. frame.value = parseUtf8(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0*$/, '');
  30824. frame.data = frame.value;
  30825. },
  30826. 'W*': function (frame) {
  30827. // parse URL field; URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  30828. // if the value is followed by a string termination all the following information should be ignored [ID3v2.4.0 section 4.3]
  30829. frame.url = parseIso88591$1(frame.data, 0, frame.data.length).replace(/\0.*$/, '');
  30830. },
  30831. 'WXXX': function (frame) {
  30832. var descriptionEndIndex;
  30833. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  30834. // ignore frames with unrecognized character encodings
  30835. return;
  30836. }
  30837. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  30838. if (descriptionEndIndex === -1) {
  30839. return;
  30840. } // parse the description and URL fields
  30841. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  30842. // if the value is followed by a string termination all the following information
  30843. // should be ignored [ID3v2.4.0 section 4.3]
  30844. frame.url = parseIso88591$1(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0.*$/, '');
  30845. },
  30846. 'PRIV': function (frame) {
  30847. var i;
  30848. for (i = 0; i < frame.data.length; i++) {
  30849. if (frame.data[i] === 0) {
  30850. // parse the description and URL fields
  30851. frame.owner = parseIso88591$1(frame.data, 0, i);
  30852. break;
  30853. }
  30854. }
  30855. frame.privateData = frame.data.subarray(i + 1);
  30856. frame.data = frame.privateData;
  30857. }
  30858. };
  30859. var parseId3Frames$1 = function (data) {
  30860. var frameSize,
  30861. frameHeader,
  30862. frameStart = 10,
  30863. tagSize = 0,
  30864. frames = []; // If we don't have enough data for a header, 10 bytes,
  30865. // or 'ID3' in the first 3 bytes this is not a valid ID3 tag.
  30866. if (data.length < 10 || data[0] !== 'I'.charCodeAt(0) || data[1] !== 'D'.charCodeAt(0) || data[2] !== '3'.charCodeAt(0)) {
  30867. return;
  30868. } // the frame size is transmitted as a 28-bit integer in the
  30869. // last four bytes of the ID3 header.
  30870. // The most significant bit of each byte is dropped and the
  30871. // results concatenated to recover the actual value.
  30872. tagSize = parseSyncSafeInteger$1(data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  30873. // convenient for our comparisons to include it
  30874. tagSize += 10; // check bit 6 of byte 5 for the extended header flag.
  30875. var hasExtendedHeader = data[5] & 0x40;
  30876. if (hasExtendedHeader) {
  30877. // advance the frame start past the extended header
  30878. frameStart += 4; // header size field
  30879. frameStart += parseSyncSafeInteger$1(data.subarray(10, 14));
  30880. tagSize -= parseSyncSafeInteger$1(data.subarray(16, 20)); // clip any padding off the end
  30881. } // parse one or more ID3 frames
  30882. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  30883. do {
  30884. // determine the number of bytes in this frame
  30885. frameSize = parseSyncSafeInteger$1(data.subarray(frameStart + 4, frameStart + 8));
  30886. if (frameSize < 1) {
  30887. break;
  30888. }
  30889. frameHeader = String.fromCharCode(data[frameStart], data[frameStart + 1], data[frameStart + 2], data[frameStart + 3]);
  30890. var frame = {
  30891. id: frameHeader,
  30892. data: data.subarray(frameStart + 10, frameStart + frameSize + 10)
  30893. };
  30894. frame.key = frame.id; // parse frame values
  30895. if (frameParsers[frame.id]) {
  30896. // use frame specific parser
  30897. frameParsers[frame.id](frame);
  30898. } else if (frame.id[0] === 'T') {
  30899. // use text frame generic parser
  30900. frameParsers['T*'](frame);
  30901. } else if (frame.id[0] === 'W') {
  30902. // use URL link frame generic parser
  30903. frameParsers['W*'](frame);
  30904. }
  30905. frames.push(frame);
  30906. frameStart += 10; // advance past the frame header
  30907. frameStart += frameSize; // advance past the frame body
  30908. } while (frameStart < tagSize);
  30909. return frames;
  30910. };
  30911. var parseId3 = {
  30912. parseId3Frames: parseId3Frames$1,
  30913. parseSyncSafeInteger: parseSyncSafeInteger$1,
  30914. frameParsers: frameParsers
  30915. };
  30916. /**
  30917. * mux.js
  30918. *
  30919. * Copyright (c) Brightcove
  30920. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  30921. *
  30922. * Accepts program elementary stream (PES) data events and parses out
  30923. * ID3 metadata from them, if present.
  30924. * @see http://id3.org/id3v2.3.0
  30925. */
  30926. var Stream$5 = stream,
  30927. StreamTypes$3 = streamTypes,
  30928. id3 = parseId3,
  30929. MetadataStream;
  30930. MetadataStream = function (options) {
  30931. var settings = {
  30932. // the bytes of the program-level descriptor field in MP2T
  30933. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  30934. // program element descriptors"
  30935. descriptor: options && options.descriptor
  30936. },
  30937. // the total size in bytes of the ID3 tag being parsed
  30938. tagSize = 0,
  30939. // tag data that is not complete enough to be parsed
  30940. buffer = [],
  30941. // the total number of bytes currently in the buffer
  30942. bufferSize = 0,
  30943. i;
  30944. MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  30945. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  30946. this.dispatchType = StreamTypes$3.METADATA_STREAM_TYPE.toString(16);
  30947. if (settings.descriptor) {
  30948. for (i = 0; i < settings.descriptor.length; i++) {
  30949. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  30950. }
  30951. }
  30952. this.push = function (chunk) {
  30953. var tag, frameStart, frameSize, frame, i, frameHeader;
  30954. if (chunk.type !== 'timed-metadata') {
  30955. return;
  30956. } // if data_alignment_indicator is set in the PES header,
  30957. // we must have the start of a new ID3 tag. Assume anything
  30958. // remaining in the buffer was malformed and throw it out
  30959. if (chunk.dataAlignmentIndicator) {
  30960. bufferSize = 0;
  30961. buffer.length = 0;
  30962. } // ignore events that don't look like ID3 data
  30963. 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))) {
  30964. this.trigger('log', {
  30965. level: 'warn',
  30966. message: 'Skipping unrecognized metadata packet'
  30967. });
  30968. return;
  30969. } // add this chunk to the data we've collected so far
  30970. buffer.push(chunk);
  30971. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  30972. if (buffer.length === 1) {
  30973. // the frame size is transmitted as a 28-bit integer in the
  30974. // last four bytes of the ID3 header.
  30975. // The most significant bit of each byte is dropped and the
  30976. // results concatenated to recover the actual value.
  30977. tagSize = id3.parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  30978. // convenient for our comparisons to include it
  30979. tagSize += 10;
  30980. } // if the entire frame has not arrived, wait for more data
  30981. if (bufferSize < tagSize) {
  30982. return;
  30983. } // collect the entire frame so it can be parsed
  30984. tag = {
  30985. data: new Uint8Array(tagSize),
  30986. frames: [],
  30987. pts: buffer[0].pts,
  30988. dts: buffer[0].dts
  30989. };
  30990. for (i = 0; i < tagSize;) {
  30991. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  30992. i += buffer[0].data.byteLength;
  30993. bufferSize -= buffer[0].data.byteLength;
  30994. buffer.shift();
  30995. } // find the start of the first frame and the end of the tag
  30996. frameStart = 10;
  30997. if (tag.data[5] & 0x40) {
  30998. // advance the frame start past the extended header
  30999. frameStart += 4; // header size field
  31000. frameStart += id3.parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end
  31001. tagSize -= id3.parseSyncSafeInteger(tag.data.subarray(16, 20));
  31002. } // parse one or more ID3 frames
  31003. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  31004. do {
  31005. // determine the number of bytes in this frame
  31006. frameSize = id3.parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  31007. if (frameSize < 1) {
  31008. this.trigger('log', {
  31009. level: 'warn',
  31010. message: 'Malformed ID3 frame encountered. Skipping remaining metadata parsing.'
  31011. }); // If the frame is malformed, don't parse any further frames but allow previous valid parsed frames
  31012. // to be sent along.
  31013. break;
  31014. }
  31015. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  31016. frame = {
  31017. id: frameHeader,
  31018. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  31019. };
  31020. frame.key = frame.id; // parse frame values
  31021. if (id3.frameParsers[frame.id]) {
  31022. // use frame specific parser
  31023. id3.frameParsers[frame.id](frame);
  31024. } else if (frame.id[0] === 'T') {
  31025. // use text frame generic parser
  31026. id3.frameParsers['T*'](frame);
  31027. } else if (frame.id[0] === 'W') {
  31028. // use URL link frame generic parser
  31029. id3.frameParsers['W*'](frame);
  31030. } // handle the special PRIV frame used to indicate the start
  31031. // time for raw AAC data
  31032. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  31033. var d = frame.data,
  31034. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  31035. size *= 4;
  31036. size += d[7] & 0x03;
  31037. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  31038. // on the value of this frame
  31039. // we couldn't have known the appropriate pts and dts before
  31040. // parsing this ID3 tag so set those values now
  31041. if (tag.pts === undefined && tag.dts === undefined) {
  31042. tag.pts = frame.timeStamp;
  31043. tag.dts = frame.timeStamp;
  31044. }
  31045. this.trigger('timestamp', frame);
  31046. }
  31047. tag.frames.push(frame);
  31048. frameStart += 10; // advance past the frame header
  31049. frameStart += frameSize; // advance past the frame body
  31050. } while (frameStart < tagSize);
  31051. this.trigger('data', tag);
  31052. };
  31053. };
  31054. MetadataStream.prototype = new Stream$5();
  31055. var metadataStream = MetadataStream;
  31056. /**
  31057. * mux.js
  31058. *
  31059. * Copyright (c) Brightcove
  31060. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  31061. *
  31062. * A stream-based mp2t to mp4 converter. This utility can be used to
  31063. * deliver mp4s to a SourceBuffer on platforms that support native
  31064. * Media Source Extensions.
  31065. */
  31066. var Stream$4 = stream,
  31067. CaptionStream$1 = captionStream,
  31068. StreamTypes$2 = streamTypes,
  31069. TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  31070. var TransportPacketStream, TransportParseStream, ElementaryStream; // constants
  31071. var MP2T_PACKET_LENGTH$1 = 188,
  31072. // bytes
  31073. SYNC_BYTE$1 = 0x47;
  31074. /**
  31075. * Splits an incoming stream of binary data into MPEG-2 Transport
  31076. * Stream packets.
  31077. */
  31078. TransportPacketStream = function () {
  31079. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  31080. bytesInBuffer = 0;
  31081. TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  31082. /**
  31083. * Split a stream of data into M2TS packets
  31084. **/
  31085. this.push = function (bytes) {
  31086. var startIndex = 0,
  31087. endIndex = MP2T_PACKET_LENGTH$1,
  31088. everything; // If there are bytes remaining from the last segment, prepend them to the
  31089. // bytes that were pushed in
  31090. if (bytesInBuffer) {
  31091. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  31092. everything.set(buffer.subarray(0, bytesInBuffer));
  31093. everything.set(bytes, bytesInBuffer);
  31094. bytesInBuffer = 0;
  31095. } else {
  31096. everything = bytes;
  31097. } // While we have enough data for a packet
  31098. while (endIndex < everything.byteLength) {
  31099. // Look for a pair of start and end sync bytes in the data..
  31100. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  31101. // We found a packet so emit it and jump one whole packet forward in
  31102. // the stream
  31103. this.trigger('data', everything.subarray(startIndex, endIndex));
  31104. startIndex += MP2T_PACKET_LENGTH$1;
  31105. endIndex += MP2T_PACKET_LENGTH$1;
  31106. continue;
  31107. } // If we get here, we have somehow become de-synchronized and we need to step
  31108. // forward one byte at a time until we find a pair of sync bytes that denote
  31109. // a packet
  31110. startIndex++;
  31111. endIndex++;
  31112. } // If there was some data left over at the end of the segment that couldn't
  31113. // possibly be a whole packet, keep it because it might be the start of a packet
  31114. // that continues in the next segment
  31115. if (startIndex < everything.byteLength) {
  31116. buffer.set(everything.subarray(startIndex), 0);
  31117. bytesInBuffer = everything.byteLength - startIndex;
  31118. }
  31119. };
  31120. /**
  31121. * Passes identified M2TS packets to the TransportParseStream to be parsed
  31122. **/
  31123. this.flush = function () {
  31124. // If the buffer contains a whole packet when we are being flushed, emit it
  31125. // and empty the buffer. Otherwise hold onto the data because it may be
  31126. // important for decoding the next segment
  31127. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  31128. this.trigger('data', buffer);
  31129. bytesInBuffer = 0;
  31130. }
  31131. this.trigger('done');
  31132. };
  31133. this.endTimeline = function () {
  31134. this.flush();
  31135. this.trigger('endedtimeline');
  31136. };
  31137. this.reset = function () {
  31138. bytesInBuffer = 0;
  31139. this.trigger('reset');
  31140. };
  31141. };
  31142. TransportPacketStream.prototype = new Stream$4();
  31143. /**
  31144. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  31145. * forms of the individual transport stream packets.
  31146. */
  31147. TransportParseStream = function () {
  31148. var parsePsi, parsePat, parsePmt, self;
  31149. TransportParseStream.prototype.init.call(this);
  31150. self = this;
  31151. this.packetsWaitingForPmt = [];
  31152. this.programMapTable = undefined;
  31153. parsePsi = function (payload, psi) {
  31154. var offset = 0; // PSI packets may be split into multiple sections and those
  31155. // sections may be split into multiple packets. If a PSI
  31156. // section starts in this packet, the payload_unit_start_indicator
  31157. // will be true and the first byte of the payload will indicate
  31158. // the offset from the current position to the start of the
  31159. // section.
  31160. if (psi.payloadUnitStartIndicator) {
  31161. offset += payload[offset] + 1;
  31162. }
  31163. if (psi.type === 'pat') {
  31164. parsePat(payload.subarray(offset), psi);
  31165. } else {
  31166. parsePmt(payload.subarray(offset), psi);
  31167. }
  31168. };
  31169. parsePat = function (payload, pat) {
  31170. pat.section_number = payload[7]; // eslint-disable-line camelcase
  31171. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  31172. // skip the PSI header and parse the first PMT entry
  31173. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  31174. pat.pmtPid = self.pmtPid;
  31175. };
  31176. /**
  31177. * Parse out the relevant fields of a Program Map Table (PMT).
  31178. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  31179. * packet. The first byte in this array should be the table_id
  31180. * field.
  31181. * @param pmt {object} the object that should be decorated with
  31182. * fields parsed from the PMT.
  31183. */
  31184. parsePmt = function (payload, pmt) {
  31185. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  31186. // take effect. We don't believe this should ever be the case
  31187. // for HLS but we'll ignore "forward" PMT declarations if we see
  31188. // them. Future PMT declarations have the current_next_indicator
  31189. // set to zero.
  31190. if (!(payload[5] & 0x01)) {
  31191. return;
  31192. } // overwrite any existing program map table
  31193. self.programMapTable = {
  31194. video: null,
  31195. audio: null,
  31196. 'timed-metadata': {}
  31197. }; // the mapping table ends at the end of the current section
  31198. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  31199. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  31200. // long the program info descriptors are
  31201. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  31202. offset = 12 + programInfoLength;
  31203. while (offset < tableEnd) {
  31204. var streamType = payload[offset];
  31205. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  31206. // TODO: should this be done for metadata too? for now maintain behavior of
  31207. // multiple metadata streams
  31208. if (streamType === StreamTypes$2.H264_STREAM_TYPE && self.programMapTable.video === null) {
  31209. self.programMapTable.video = pid;
  31210. } else if (streamType === StreamTypes$2.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  31211. self.programMapTable.audio = pid;
  31212. } else if (streamType === StreamTypes$2.METADATA_STREAM_TYPE) {
  31213. // map pid to stream type for metadata streams
  31214. self.programMapTable['timed-metadata'][pid] = streamType;
  31215. } // move to the next table entry
  31216. // skip past the elementary stream descriptors, if present
  31217. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  31218. } // record the map on the packet as well
  31219. pmt.programMapTable = self.programMapTable;
  31220. };
  31221. /**
  31222. * Deliver a new MP2T packet to the next stream in the pipeline.
  31223. */
  31224. this.push = function (packet) {
  31225. var result = {},
  31226. offset = 4;
  31227. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  31228. result.pid = packet[1] & 0x1f;
  31229. result.pid <<= 8;
  31230. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  31231. // fifth byte of the TS packet header. The adaptation field is
  31232. // used to add stuffing to PES packets that don't fill a complete
  31233. // TS packet, and to specify some forms of timing and control data
  31234. // that we do not currently use.
  31235. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  31236. offset += packet[offset] + 1;
  31237. } // parse the rest of the packet based on the type
  31238. if (result.pid === 0) {
  31239. result.type = 'pat';
  31240. parsePsi(packet.subarray(offset), result);
  31241. this.trigger('data', result);
  31242. } else if (result.pid === this.pmtPid) {
  31243. result.type = 'pmt';
  31244. parsePsi(packet.subarray(offset), result);
  31245. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  31246. while (this.packetsWaitingForPmt.length) {
  31247. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  31248. }
  31249. } else if (this.programMapTable === undefined) {
  31250. // When we have not seen a PMT yet, defer further processing of
  31251. // PES packets until one has been parsed
  31252. this.packetsWaitingForPmt.push([packet, offset, result]);
  31253. } else {
  31254. this.processPes_(packet, offset, result);
  31255. }
  31256. };
  31257. this.processPes_ = function (packet, offset, result) {
  31258. // set the appropriate stream type
  31259. if (result.pid === this.programMapTable.video) {
  31260. result.streamType = StreamTypes$2.H264_STREAM_TYPE;
  31261. } else if (result.pid === this.programMapTable.audio) {
  31262. result.streamType = StreamTypes$2.ADTS_STREAM_TYPE;
  31263. } else {
  31264. // if not video or audio, it is timed-metadata or unknown
  31265. // if unknown, streamType will be undefined
  31266. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  31267. }
  31268. result.type = 'pes';
  31269. result.data = packet.subarray(offset);
  31270. this.trigger('data', result);
  31271. };
  31272. };
  31273. TransportParseStream.prototype = new Stream$4();
  31274. TransportParseStream.STREAM_TYPES = {
  31275. h264: 0x1b,
  31276. adts: 0x0f
  31277. };
  31278. /**
  31279. * Reconsistutes program elementary stream (PES) packets from parsed
  31280. * transport stream packets. That is, if you pipe an
  31281. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  31282. * events will be events which capture the bytes for individual PES
  31283. * packets plus relevant metadata that has been extracted from the
  31284. * container.
  31285. */
  31286. ElementaryStream = function () {
  31287. var self = this,
  31288. segmentHadPmt = false,
  31289. // PES packet fragments
  31290. video = {
  31291. data: [],
  31292. size: 0
  31293. },
  31294. audio = {
  31295. data: [],
  31296. size: 0
  31297. },
  31298. timedMetadata = {
  31299. data: [],
  31300. size: 0
  31301. },
  31302. programMapTable,
  31303. parsePes = function (payload, pes) {
  31304. var ptsDtsFlags;
  31305. const startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  31306. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  31307. // that are frame data that is continuing from the previous fragment. This
  31308. // is to check that the pes data is the start of a new pes payload
  31309. if (startPrefix !== 1) {
  31310. return;
  31311. } // get the packet length, this will be 0 for video
  31312. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  31313. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  31314. // and a DTS value. Determine what combination of values is
  31315. // available to work with.
  31316. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  31317. // performs all bitwise operations on 32-bit integers but javascript
  31318. // supports a much greater range (52-bits) of integer using standard
  31319. // mathematical operations.
  31320. // We construct a 31-bit value using bitwise operators over the 31
  31321. // most significant bits and then multiply by 4 (equal to a left-shift
  31322. // of 2) before we add the final 2 least significant bits of the
  31323. // timestamp (equal to an OR.)
  31324. if (ptsDtsFlags & 0xC0) {
  31325. // the PTS and DTS are not written out directly. For information
  31326. // on how they are encoded, see
  31327. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  31328. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  31329. pes.pts *= 4; // Left shift by 2
  31330. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  31331. pes.dts = pes.pts;
  31332. if (ptsDtsFlags & 0x40) {
  31333. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  31334. pes.dts *= 4; // Left shift by 2
  31335. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  31336. }
  31337. } // the data section starts immediately after the PES header.
  31338. // pes_header_data_length specifies the number of header bytes
  31339. // that follow the last byte of the field.
  31340. pes.data = payload.subarray(9 + payload[8]);
  31341. },
  31342. /**
  31343. * Pass completely parsed PES packets to the next stream in the pipeline
  31344. **/
  31345. flushStream = function (stream, type, forceFlush) {
  31346. var packetData = new Uint8Array(stream.size),
  31347. event = {
  31348. type: type
  31349. },
  31350. i = 0,
  31351. offset = 0,
  31352. packetFlushable = false,
  31353. fragment; // do nothing if there is not enough buffered data for a complete
  31354. // PES header
  31355. if (!stream.data.length || stream.size < 9) {
  31356. return;
  31357. }
  31358. event.trackId = stream.data[0].pid; // reassemble the packet
  31359. for (i = 0; i < stream.data.length; i++) {
  31360. fragment = stream.data[i];
  31361. packetData.set(fragment.data, offset);
  31362. offset += fragment.data.byteLength;
  31363. } // parse assembled packet's PES header
  31364. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  31365. // check that there is enough stream data to fill the packet
  31366. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  31367. if (forceFlush || packetFlushable) {
  31368. stream.size = 0;
  31369. stream.data.length = 0;
  31370. } // only emit packets that are complete. this is to avoid assembling
  31371. // incomplete PES packets due to poor segmentation
  31372. if (packetFlushable) {
  31373. self.trigger('data', event);
  31374. }
  31375. };
  31376. ElementaryStream.prototype.init.call(this);
  31377. /**
  31378. * Identifies M2TS packet types and parses PES packets using metadata
  31379. * parsed from the PMT
  31380. **/
  31381. this.push = function (data) {
  31382. ({
  31383. pat: function () {// we have to wait for the PMT to arrive as well before we
  31384. // have any meaningful metadata
  31385. },
  31386. pes: function () {
  31387. var stream, streamType;
  31388. switch (data.streamType) {
  31389. case StreamTypes$2.H264_STREAM_TYPE:
  31390. stream = video;
  31391. streamType = 'video';
  31392. break;
  31393. case StreamTypes$2.ADTS_STREAM_TYPE:
  31394. stream = audio;
  31395. streamType = 'audio';
  31396. break;
  31397. case StreamTypes$2.METADATA_STREAM_TYPE:
  31398. stream = timedMetadata;
  31399. streamType = 'timed-metadata';
  31400. break;
  31401. default:
  31402. // ignore unknown stream types
  31403. return;
  31404. } // if a new packet is starting, we can flush the completed
  31405. // packet
  31406. if (data.payloadUnitStartIndicator) {
  31407. flushStream(stream, streamType, true);
  31408. } // buffer this fragment until we are sure we've received the
  31409. // complete payload
  31410. stream.data.push(data);
  31411. stream.size += data.data.byteLength;
  31412. },
  31413. pmt: function () {
  31414. var event = {
  31415. type: 'metadata',
  31416. tracks: []
  31417. };
  31418. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  31419. if (programMapTable.video !== null) {
  31420. event.tracks.push({
  31421. timelineStartInfo: {
  31422. baseMediaDecodeTime: 0
  31423. },
  31424. id: +programMapTable.video,
  31425. codec: 'avc',
  31426. type: 'video'
  31427. });
  31428. }
  31429. if (programMapTable.audio !== null) {
  31430. event.tracks.push({
  31431. timelineStartInfo: {
  31432. baseMediaDecodeTime: 0
  31433. },
  31434. id: +programMapTable.audio,
  31435. codec: 'adts',
  31436. type: 'audio'
  31437. });
  31438. }
  31439. segmentHadPmt = true;
  31440. self.trigger('data', event);
  31441. }
  31442. })[data.type]();
  31443. };
  31444. this.reset = function () {
  31445. video.size = 0;
  31446. video.data.length = 0;
  31447. audio.size = 0;
  31448. audio.data.length = 0;
  31449. this.trigger('reset');
  31450. };
  31451. /**
  31452. * Flush any remaining input. Video PES packets may be of variable
  31453. * length. Normally, the start of a new video packet can trigger the
  31454. * finalization of the previous packet. That is not possible if no
  31455. * more video is forthcoming, however. In that case, some other
  31456. * mechanism (like the end of the file) has to be employed. When it is
  31457. * clear that no additional data is forthcoming, calling this method
  31458. * will flush the buffered packets.
  31459. */
  31460. this.flushStreams_ = function () {
  31461. // !!THIS ORDER IS IMPORTANT!!
  31462. // video first then audio
  31463. flushStream(video, 'video');
  31464. flushStream(audio, 'audio');
  31465. flushStream(timedMetadata, 'timed-metadata');
  31466. };
  31467. this.flush = function () {
  31468. // if on flush we haven't had a pmt emitted
  31469. // and we have a pmt to emit. emit the pmt
  31470. // so that we trigger a trackinfo downstream.
  31471. if (!segmentHadPmt && programMapTable) {
  31472. var pmt = {
  31473. type: 'metadata',
  31474. tracks: []
  31475. }; // translate audio and video streams to tracks
  31476. if (programMapTable.video !== null) {
  31477. pmt.tracks.push({
  31478. timelineStartInfo: {
  31479. baseMediaDecodeTime: 0
  31480. },
  31481. id: +programMapTable.video,
  31482. codec: 'avc',
  31483. type: 'video'
  31484. });
  31485. }
  31486. if (programMapTable.audio !== null) {
  31487. pmt.tracks.push({
  31488. timelineStartInfo: {
  31489. baseMediaDecodeTime: 0
  31490. },
  31491. id: +programMapTable.audio,
  31492. codec: 'adts',
  31493. type: 'audio'
  31494. });
  31495. }
  31496. self.trigger('data', pmt);
  31497. }
  31498. segmentHadPmt = false;
  31499. this.flushStreams_();
  31500. this.trigger('done');
  31501. };
  31502. };
  31503. ElementaryStream.prototype = new Stream$4();
  31504. var m2ts$1 = {
  31505. PAT_PID: 0x0000,
  31506. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  31507. TransportPacketStream: TransportPacketStream,
  31508. TransportParseStream: TransportParseStream,
  31509. ElementaryStream: ElementaryStream,
  31510. TimestampRolloverStream: TimestampRolloverStream,
  31511. CaptionStream: CaptionStream$1.CaptionStream,
  31512. Cea608Stream: CaptionStream$1.Cea608Stream,
  31513. Cea708Stream: CaptionStream$1.Cea708Stream,
  31514. MetadataStream: metadataStream
  31515. };
  31516. for (var type in StreamTypes$2) {
  31517. if (StreamTypes$2.hasOwnProperty(type)) {
  31518. m2ts$1[type] = StreamTypes$2[type];
  31519. }
  31520. }
  31521. var m2ts_1 = m2ts$1;
  31522. /**
  31523. * mux.js
  31524. *
  31525. * Copyright (c) Brightcove
  31526. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  31527. */
  31528. var Stream$3 = stream;
  31529. var ONE_SECOND_IN_TS$2 = clock$2.ONE_SECOND_IN_TS;
  31530. var AdtsStream$1;
  31531. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  31532. /*
  31533. * Accepts a ElementaryStream and emits data events with parsed
  31534. * AAC Audio Frames of the individual packets. Input audio in ADTS
  31535. * format is unpacked and re-emitted as AAC frames.
  31536. *
  31537. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  31538. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  31539. */
  31540. AdtsStream$1 = function (handlePartialSegments) {
  31541. var buffer,
  31542. frameNum = 0;
  31543. AdtsStream$1.prototype.init.call(this);
  31544. this.skipWarn_ = function (start, end) {
  31545. this.trigger('log', {
  31546. level: 'warn',
  31547. message: `adts skiping bytes ${start} to ${end} in frame ${frameNum} outside syncword`
  31548. });
  31549. };
  31550. this.push = function (packet) {
  31551. var i = 0,
  31552. frameLength,
  31553. protectionSkipBytes,
  31554. oldBuffer,
  31555. sampleCount,
  31556. adtsFrameDuration;
  31557. if (!handlePartialSegments) {
  31558. frameNum = 0;
  31559. }
  31560. if (packet.type !== 'audio') {
  31561. // ignore non-audio data
  31562. return;
  31563. } // Prepend any data in the buffer to the input data so that we can parse
  31564. // aac frames the cross a PES packet boundary
  31565. if (buffer && buffer.length) {
  31566. oldBuffer = buffer;
  31567. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  31568. buffer.set(oldBuffer);
  31569. buffer.set(packet.data, oldBuffer.byteLength);
  31570. } else {
  31571. buffer = packet.data;
  31572. } // unpack any ADTS frames which have been fully received
  31573. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  31574. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  31575. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  31576. while (i + 7 < buffer.length) {
  31577. // Look for the start of an ADTS header..
  31578. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  31579. if (typeof skip !== 'number') {
  31580. skip = i;
  31581. } // If a valid header was not found, jump one forward and attempt to
  31582. // find a valid ADTS header starting at the next byte
  31583. i++;
  31584. continue;
  31585. }
  31586. if (typeof skip === 'number') {
  31587. this.skipWarn_(skip, i);
  31588. skip = null;
  31589. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  31590. // end of the ADTS header
  31591. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  31592. // end of the sync sequence
  31593. // NOTE: frame length includes the size of the header
  31594. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  31595. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  31596. 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,
  31597. // then we have to wait for more data
  31598. if (buffer.byteLength - i < frameLength) {
  31599. break;
  31600. } // Otherwise, deliver the complete AAC frame
  31601. this.trigger('data', {
  31602. pts: packet.pts + frameNum * adtsFrameDuration,
  31603. dts: packet.dts + frameNum * adtsFrameDuration,
  31604. sampleCount: sampleCount,
  31605. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  31606. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  31607. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  31608. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  31609. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  31610. samplesize: 16,
  31611. // data is the frame without it's header
  31612. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  31613. });
  31614. frameNum++;
  31615. i += frameLength;
  31616. }
  31617. if (typeof skip === 'number') {
  31618. this.skipWarn_(skip, i);
  31619. skip = null;
  31620. } // remove processed bytes from the buffer.
  31621. buffer = buffer.subarray(i);
  31622. };
  31623. this.flush = function () {
  31624. frameNum = 0;
  31625. this.trigger('done');
  31626. };
  31627. this.reset = function () {
  31628. buffer = void 0;
  31629. this.trigger('reset');
  31630. };
  31631. this.endTimeline = function () {
  31632. buffer = void 0;
  31633. this.trigger('endedtimeline');
  31634. };
  31635. };
  31636. AdtsStream$1.prototype = new Stream$3();
  31637. var adts = AdtsStream$1;
  31638. /**
  31639. * mux.js
  31640. *
  31641. * Copyright (c) Brightcove
  31642. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  31643. */
  31644. var ExpGolomb$1;
  31645. /**
  31646. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  31647. * scheme used by h264.
  31648. */
  31649. ExpGolomb$1 = function (workingData) {
  31650. var
  31651. // the number of bytes left to examine in workingData
  31652. workingBytesAvailable = workingData.byteLength,
  31653. // the current word being examined
  31654. workingWord = 0,
  31655. // :uint
  31656. // the number of bits left to examine in the current word
  31657. workingBitsAvailable = 0; // :uint;
  31658. // ():uint
  31659. this.length = function () {
  31660. return 8 * workingBytesAvailable;
  31661. }; // ():uint
  31662. this.bitsAvailable = function () {
  31663. return 8 * workingBytesAvailable + workingBitsAvailable;
  31664. }; // ():void
  31665. this.loadWord = function () {
  31666. var position = workingData.byteLength - workingBytesAvailable,
  31667. workingBytes = new Uint8Array(4),
  31668. availableBytes = Math.min(4, workingBytesAvailable);
  31669. if (availableBytes === 0) {
  31670. throw new Error('no bytes available');
  31671. }
  31672. workingBytes.set(workingData.subarray(position, position + availableBytes));
  31673. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  31674. workingBitsAvailable = availableBytes * 8;
  31675. workingBytesAvailable -= availableBytes;
  31676. }; // (count:int):void
  31677. this.skipBits = function (count) {
  31678. var skipBytes; // :int
  31679. if (workingBitsAvailable > count) {
  31680. workingWord <<= count;
  31681. workingBitsAvailable -= count;
  31682. } else {
  31683. count -= workingBitsAvailable;
  31684. skipBytes = Math.floor(count / 8);
  31685. count -= skipBytes * 8;
  31686. workingBytesAvailable -= skipBytes;
  31687. this.loadWord();
  31688. workingWord <<= count;
  31689. workingBitsAvailable -= count;
  31690. }
  31691. }; // (size:int):uint
  31692. this.readBits = function (size) {
  31693. var bits = Math.min(workingBitsAvailable, size),
  31694. // :uint
  31695. valu = workingWord >>> 32 - bits; // :uint
  31696. // if size > 31, handle error
  31697. workingBitsAvailable -= bits;
  31698. if (workingBitsAvailable > 0) {
  31699. workingWord <<= bits;
  31700. } else if (workingBytesAvailable > 0) {
  31701. this.loadWord();
  31702. }
  31703. bits = size - bits;
  31704. if (bits > 0) {
  31705. return valu << bits | this.readBits(bits);
  31706. }
  31707. return valu;
  31708. }; // ():uint
  31709. this.skipLeadingZeros = function () {
  31710. var leadingZeroCount; // :uint
  31711. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  31712. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  31713. // the first bit of working word is 1
  31714. workingWord <<= leadingZeroCount;
  31715. workingBitsAvailable -= leadingZeroCount;
  31716. return leadingZeroCount;
  31717. }
  31718. } // we exhausted workingWord and still have not found a 1
  31719. this.loadWord();
  31720. return leadingZeroCount + this.skipLeadingZeros();
  31721. }; // ():void
  31722. this.skipUnsignedExpGolomb = function () {
  31723. this.skipBits(1 + this.skipLeadingZeros());
  31724. }; // ():void
  31725. this.skipExpGolomb = function () {
  31726. this.skipBits(1 + this.skipLeadingZeros());
  31727. }; // ():uint
  31728. this.readUnsignedExpGolomb = function () {
  31729. var clz = this.skipLeadingZeros(); // :uint
  31730. return this.readBits(clz + 1) - 1;
  31731. }; // ():int
  31732. this.readExpGolomb = function () {
  31733. var valu = this.readUnsignedExpGolomb(); // :int
  31734. if (0x01 & valu) {
  31735. // the number is odd if the low order bit is set
  31736. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  31737. }
  31738. return -1 * (valu >>> 1); // divide by two then make it negative
  31739. }; // Some convenience functions
  31740. // :Boolean
  31741. this.readBoolean = function () {
  31742. return this.readBits(1) === 1;
  31743. }; // ():int
  31744. this.readUnsignedByte = function () {
  31745. return this.readBits(8);
  31746. };
  31747. this.loadWord();
  31748. };
  31749. var expGolomb = ExpGolomb$1;
  31750. /**
  31751. * mux.js
  31752. *
  31753. * Copyright (c) Brightcove
  31754. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  31755. */
  31756. var Stream$2 = stream;
  31757. var ExpGolomb = expGolomb;
  31758. var H264Stream$1, NalByteStream;
  31759. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  31760. /**
  31761. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  31762. */
  31763. NalByteStream = function () {
  31764. var syncPoint = 0,
  31765. i,
  31766. buffer;
  31767. NalByteStream.prototype.init.call(this);
  31768. /*
  31769. * Scans a byte stream and triggers a data event with the NAL units found.
  31770. * @param {Object} data Event received from H264Stream
  31771. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  31772. *
  31773. * @see H264Stream.push
  31774. */
  31775. this.push = function (data) {
  31776. var swapBuffer;
  31777. if (!buffer) {
  31778. buffer = data.data;
  31779. } else {
  31780. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  31781. swapBuffer.set(buffer);
  31782. swapBuffer.set(data.data, buffer.byteLength);
  31783. buffer = swapBuffer;
  31784. }
  31785. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  31786. // scan for NAL unit boundaries
  31787. // a match looks like this:
  31788. // 0 0 1 .. NAL .. 0 0 1
  31789. // ^ sync point ^ i
  31790. // or this:
  31791. // 0 0 1 .. NAL .. 0 0 0
  31792. // ^ sync point ^ i
  31793. // advance the sync point to a NAL start, if necessary
  31794. for (; syncPoint < len - 3; syncPoint++) {
  31795. if (buffer[syncPoint + 2] === 1) {
  31796. // the sync point is properly aligned
  31797. i = syncPoint + 5;
  31798. break;
  31799. }
  31800. }
  31801. while (i < len) {
  31802. // look at the current byte to determine if we've hit the end of
  31803. // a NAL unit boundary
  31804. switch (buffer[i]) {
  31805. case 0:
  31806. // skip past non-sync sequences
  31807. if (buffer[i - 1] !== 0) {
  31808. i += 2;
  31809. break;
  31810. } else if (buffer[i - 2] !== 0) {
  31811. i++;
  31812. break;
  31813. } // deliver the NAL unit if it isn't empty
  31814. if (syncPoint + 3 !== i - 2) {
  31815. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  31816. } // drop trailing zeroes
  31817. do {
  31818. i++;
  31819. } while (buffer[i] !== 1 && i < len);
  31820. syncPoint = i - 2;
  31821. i += 3;
  31822. break;
  31823. case 1:
  31824. // skip past non-sync sequences
  31825. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  31826. i += 3;
  31827. break;
  31828. } // deliver the NAL unit
  31829. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  31830. syncPoint = i - 2;
  31831. i += 3;
  31832. break;
  31833. default:
  31834. // the current byte isn't a one or zero, so it cannot be part
  31835. // of a sync sequence
  31836. i += 3;
  31837. break;
  31838. }
  31839. } // filter out the NAL units that were delivered
  31840. buffer = buffer.subarray(syncPoint);
  31841. i -= syncPoint;
  31842. syncPoint = 0;
  31843. };
  31844. this.reset = function () {
  31845. buffer = null;
  31846. syncPoint = 0;
  31847. this.trigger('reset');
  31848. };
  31849. this.flush = function () {
  31850. // deliver the last buffered NAL unit
  31851. if (buffer && buffer.byteLength > 3) {
  31852. this.trigger('data', buffer.subarray(syncPoint + 3));
  31853. } // reset the stream state
  31854. buffer = null;
  31855. syncPoint = 0;
  31856. this.trigger('done');
  31857. };
  31858. this.endTimeline = function () {
  31859. this.flush();
  31860. this.trigger('endedtimeline');
  31861. };
  31862. };
  31863. NalByteStream.prototype = new Stream$2(); // values of profile_idc that indicate additional fields are included in the SPS
  31864. // see Recommendation ITU-T H.264 (4/2013),
  31865. // 7.3.2.1.1 Sequence parameter set data syntax
  31866. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  31867. 100: true,
  31868. 110: true,
  31869. 122: true,
  31870. 244: true,
  31871. 44: true,
  31872. 83: true,
  31873. 86: true,
  31874. 118: true,
  31875. 128: true,
  31876. // TODO: the three profiles below don't
  31877. // appear to have sps data in the specificiation anymore?
  31878. 138: true,
  31879. 139: true,
  31880. 134: true
  31881. };
  31882. /**
  31883. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  31884. * events.
  31885. */
  31886. H264Stream$1 = function () {
  31887. var nalByteStream = new NalByteStream(),
  31888. self,
  31889. trackId,
  31890. currentPts,
  31891. currentDts,
  31892. discardEmulationPreventionBytes,
  31893. readSequenceParameterSet,
  31894. skipScalingList;
  31895. H264Stream$1.prototype.init.call(this);
  31896. self = this;
  31897. /*
  31898. * Pushes a packet from a stream onto the NalByteStream
  31899. *
  31900. * @param {Object} packet - A packet received from a stream
  31901. * @param {Uint8Array} packet.data - The raw bytes of the packet
  31902. * @param {Number} packet.dts - Decode timestamp of the packet
  31903. * @param {Number} packet.pts - Presentation timestamp of the packet
  31904. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  31905. * @param {('video'|'audio')} packet.type - The type of packet
  31906. *
  31907. */
  31908. this.push = function (packet) {
  31909. if (packet.type !== 'video') {
  31910. return;
  31911. }
  31912. trackId = packet.trackId;
  31913. currentPts = packet.pts;
  31914. currentDts = packet.dts;
  31915. nalByteStream.push(packet);
  31916. };
  31917. /*
  31918. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  31919. * for the NALUs to the next stream component.
  31920. * Also, preprocess caption and sequence parameter NALUs.
  31921. *
  31922. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  31923. * @see NalByteStream.push
  31924. */
  31925. nalByteStream.on('data', function (data) {
  31926. var event = {
  31927. trackId: trackId,
  31928. pts: currentPts,
  31929. dts: currentDts,
  31930. data: data,
  31931. nalUnitTypeCode: data[0] & 0x1f
  31932. };
  31933. switch (event.nalUnitTypeCode) {
  31934. case 0x05:
  31935. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  31936. break;
  31937. case 0x06:
  31938. event.nalUnitType = 'sei_rbsp';
  31939. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  31940. break;
  31941. case 0x07:
  31942. event.nalUnitType = 'seq_parameter_set_rbsp';
  31943. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  31944. event.config = readSequenceParameterSet(event.escapedRBSP);
  31945. break;
  31946. case 0x08:
  31947. event.nalUnitType = 'pic_parameter_set_rbsp';
  31948. break;
  31949. case 0x09:
  31950. event.nalUnitType = 'access_unit_delimiter_rbsp';
  31951. break;
  31952. } // This triggers data on the H264Stream
  31953. self.trigger('data', event);
  31954. });
  31955. nalByteStream.on('done', function () {
  31956. self.trigger('done');
  31957. });
  31958. nalByteStream.on('partialdone', function () {
  31959. self.trigger('partialdone');
  31960. });
  31961. nalByteStream.on('reset', function () {
  31962. self.trigger('reset');
  31963. });
  31964. nalByteStream.on('endedtimeline', function () {
  31965. self.trigger('endedtimeline');
  31966. });
  31967. this.flush = function () {
  31968. nalByteStream.flush();
  31969. };
  31970. this.partialFlush = function () {
  31971. nalByteStream.partialFlush();
  31972. };
  31973. this.reset = function () {
  31974. nalByteStream.reset();
  31975. };
  31976. this.endTimeline = function () {
  31977. nalByteStream.endTimeline();
  31978. };
  31979. /**
  31980. * Advance the ExpGolomb decoder past a scaling list. The scaling
  31981. * list is optionally transmitted as part of a sequence parameter
  31982. * set and is not relevant to transmuxing.
  31983. * @param count {number} the number of entries in this scaling list
  31984. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  31985. * start of a scaling list
  31986. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  31987. */
  31988. skipScalingList = function (count, expGolombDecoder) {
  31989. var lastScale = 8,
  31990. nextScale = 8,
  31991. j,
  31992. deltaScale;
  31993. for (j = 0; j < count; j++) {
  31994. if (nextScale !== 0) {
  31995. deltaScale = expGolombDecoder.readExpGolomb();
  31996. nextScale = (lastScale + deltaScale + 256) % 256;
  31997. }
  31998. lastScale = nextScale === 0 ? lastScale : nextScale;
  31999. }
  32000. };
  32001. /**
  32002. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  32003. * Sequence Payload"
  32004. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  32005. * unit
  32006. * @return {Uint8Array} the RBSP without any Emulation
  32007. * Prevention Bytes
  32008. */
  32009. discardEmulationPreventionBytes = function (data) {
  32010. var length = data.byteLength,
  32011. emulationPreventionBytesPositions = [],
  32012. i = 1,
  32013. newLength,
  32014. newData; // Find all `Emulation Prevention Bytes`
  32015. while (i < length - 2) {
  32016. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  32017. emulationPreventionBytesPositions.push(i + 2);
  32018. i += 2;
  32019. } else {
  32020. i++;
  32021. }
  32022. } // If no Emulation Prevention Bytes were found just return the original
  32023. // array
  32024. if (emulationPreventionBytesPositions.length === 0) {
  32025. return data;
  32026. } // Create a new array to hold the NAL unit data
  32027. newLength = length - emulationPreventionBytesPositions.length;
  32028. newData = new Uint8Array(newLength);
  32029. var sourceIndex = 0;
  32030. for (i = 0; i < newLength; sourceIndex++, i++) {
  32031. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  32032. // Skip this byte
  32033. sourceIndex++; // Remove this position index
  32034. emulationPreventionBytesPositions.shift();
  32035. }
  32036. newData[i] = data[sourceIndex];
  32037. }
  32038. return newData;
  32039. };
  32040. /**
  32041. * Read a sequence parameter set and return some interesting video
  32042. * properties. A sequence parameter set is the H264 metadata that
  32043. * describes the properties of upcoming video frames.
  32044. * @param data {Uint8Array} the bytes of a sequence parameter set
  32045. * @return {object} an object with configuration parsed from the
  32046. * sequence parameter set, including the dimensions of the
  32047. * associated video frames.
  32048. */
  32049. readSequenceParameterSet = function (data) {
  32050. var frameCropLeftOffset = 0,
  32051. frameCropRightOffset = 0,
  32052. frameCropTopOffset = 0,
  32053. frameCropBottomOffset = 0,
  32054. expGolombDecoder,
  32055. profileIdc,
  32056. levelIdc,
  32057. profileCompatibility,
  32058. chromaFormatIdc,
  32059. picOrderCntType,
  32060. numRefFramesInPicOrderCntCycle,
  32061. picWidthInMbsMinus1,
  32062. picHeightInMapUnitsMinus1,
  32063. frameMbsOnlyFlag,
  32064. scalingListCount,
  32065. sarRatio = [1, 1],
  32066. aspectRatioIdc,
  32067. i;
  32068. expGolombDecoder = new ExpGolomb(data);
  32069. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  32070. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  32071. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  32072. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  32073. // some profiles have more optional data we don't need
  32074. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  32075. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  32076. if (chromaFormatIdc === 3) {
  32077. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  32078. }
  32079. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  32080. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  32081. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  32082. if (expGolombDecoder.readBoolean()) {
  32083. // seq_scaling_matrix_present_flag
  32084. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  32085. for (i = 0; i < scalingListCount; i++) {
  32086. if (expGolombDecoder.readBoolean()) {
  32087. // seq_scaling_list_present_flag[ i ]
  32088. if (i < 6) {
  32089. skipScalingList(16, expGolombDecoder);
  32090. } else {
  32091. skipScalingList(64, expGolombDecoder);
  32092. }
  32093. }
  32094. }
  32095. }
  32096. }
  32097. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  32098. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  32099. if (picOrderCntType === 0) {
  32100. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  32101. } else if (picOrderCntType === 1) {
  32102. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  32103. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  32104. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  32105. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  32106. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  32107. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  32108. }
  32109. }
  32110. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  32111. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  32112. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  32113. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  32114. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  32115. if (frameMbsOnlyFlag === 0) {
  32116. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  32117. }
  32118. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  32119. if (expGolombDecoder.readBoolean()) {
  32120. // frame_cropping_flag
  32121. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  32122. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  32123. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  32124. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  32125. }
  32126. if (expGolombDecoder.readBoolean()) {
  32127. // vui_parameters_present_flag
  32128. if (expGolombDecoder.readBoolean()) {
  32129. // aspect_ratio_info_present_flag
  32130. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  32131. switch (aspectRatioIdc) {
  32132. case 1:
  32133. sarRatio = [1, 1];
  32134. break;
  32135. case 2:
  32136. sarRatio = [12, 11];
  32137. break;
  32138. case 3:
  32139. sarRatio = [10, 11];
  32140. break;
  32141. case 4:
  32142. sarRatio = [16, 11];
  32143. break;
  32144. case 5:
  32145. sarRatio = [40, 33];
  32146. break;
  32147. case 6:
  32148. sarRatio = [24, 11];
  32149. break;
  32150. case 7:
  32151. sarRatio = [20, 11];
  32152. break;
  32153. case 8:
  32154. sarRatio = [32, 11];
  32155. break;
  32156. case 9:
  32157. sarRatio = [80, 33];
  32158. break;
  32159. case 10:
  32160. sarRatio = [18, 11];
  32161. break;
  32162. case 11:
  32163. sarRatio = [15, 11];
  32164. break;
  32165. case 12:
  32166. sarRatio = [64, 33];
  32167. break;
  32168. case 13:
  32169. sarRatio = [160, 99];
  32170. break;
  32171. case 14:
  32172. sarRatio = [4, 3];
  32173. break;
  32174. case 15:
  32175. sarRatio = [3, 2];
  32176. break;
  32177. case 16:
  32178. sarRatio = [2, 1];
  32179. break;
  32180. case 255:
  32181. {
  32182. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  32183. break;
  32184. }
  32185. }
  32186. if (sarRatio) {
  32187. sarRatio[0] / sarRatio[1];
  32188. }
  32189. }
  32190. }
  32191. return {
  32192. profileIdc: profileIdc,
  32193. levelIdc: levelIdc,
  32194. profileCompatibility: profileCompatibility,
  32195. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  32196. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  32197. // sar is sample aspect ratio
  32198. sarRatio: sarRatio
  32199. };
  32200. };
  32201. };
  32202. H264Stream$1.prototype = new Stream$2();
  32203. var h264 = {
  32204. H264Stream: H264Stream$1,
  32205. NalByteStream: NalByteStream
  32206. };
  32207. /**
  32208. * mux.js
  32209. *
  32210. * Copyright (c) Brightcove
  32211. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  32212. *
  32213. * Utilities to detect basic properties and metadata about Aac data.
  32214. */
  32215. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  32216. var parseId3TagSize = function (header, byteIndex) {
  32217. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  32218. flags = header[byteIndex + 5],
  32219. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  32220. returnSize = returnSize >= 0 ? returnSize : 0;
  32221. if (footerPresent) {
  32222. return returnSize + 20;
  32223. }
  32224. return returnSize + 10;
  32225. };
  32226. var getId3Offset = function (data, offset) {
  32227. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  32228. return offset;
  32229. }
  32230. offset += parseId3TagSize(data, offset);
  32231. return getId3Offset(data, offset);
  32232. }; // TODO: use vhs-utils
  32233. var isLikelyAacData$1 = function (data) {
  32234. var offset = getId3Offset(data, 0);
  32235. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 &&
  32236. // verify that the 2 layer bits are 0, aka this
  32237. // is not mp3 data but aac data.
  32238. (data[offset + 1] & 0x16) === 0x10;
  32239. };
  32240. var parseSyncSafeInteger = function (data) {
  32241. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  32242. }; // return a percent-encoded representation of the specified byte range
  32243. // @see http://en.wikipedia.org/wiki/Percent-encoding
  32244. var percentEncode = function (bytes, start, end) {
  32245. var i,
  32246. result = '';
  32247. for (i = start; i < end; i++) {
  32248. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  32249. }
  32250. return result;
  32251. }; // return the string representation of the specified byte range,
  32252. // interpreted as ISO-8859-1.
  32253. var parseIso88591 = function (bytes, start, end) {
  32254. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  32255. };
  32256. var parseAdtsSize = function (header, byteIndex) {
  32257. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  32258. middle = header[byteIndex + 4] << 3,
  32259. highTwo = header[byteIndex + 3] & 0x3 << 11;
  32260. return highTwo | middle | lowThree;
  32261. };
  32262. var parseType$4 = function (header, byteIndex) {
  32263. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  32264. return 'timed-metadata';
  32265. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  32266. return 'audio';
  32267. }
  32268. return null;
  32269. };
  32270. var parseSampleRate = function (packet) {
  32271. var i = 0;
  32272. while (i + 5 < packet.length) {
  32273. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  32274. // If a valid header was not found, jump one forward and attempt to
  32275. // find a valid ADTS header starting at the next byte
  32276. i++;
  32277. continue;
  32278. }
  32279. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  32280. }
  32281. return null;
  32282. };
  32283. var parseAacTimestamp = function (packet) {
  32284. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  32285. frameStart = 10;
  32286. if (packet[5] & 0x40) {
  32287. // advance the frame start past the extended header
  32288. frameStart += 4; // header size field
  32289. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  32290. } // parse one or more ID3 frames
  32291. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  32292. do {
  32293. // determine the number of bytes in this frame
  32294. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  32295. if (frameSize < 1) {
  32296. return null;
  32297. }
  32298. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  32299. if (frameHeader === 'PRIV') {
  32300. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  32301. for (var i = 0; i < frame.byteLength; i++) {
  32302. if (frame[i] === 0) {
  32303. var owner = parseIso88591(frame, 0, i);
  32304. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  32305. var d = frame.subarray(i + 1);
  32306. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  32307. size *= 4;
  32308. size += d[7] & 0x03;
  32309. return size;
  32310. }
  32311. break;
  32312. }
  32313. }
  32314. }
  32315. frameStart += 10; // advance past the frame header
  32316. frameStart += frameSize; // advance past the frame body
  32317. } while (frameStart < packet.byteLength);
  32318. return null;
  32319. };
  32320. var utils = {
  32321. isLikelyAacData: isLikelyAacData$1,
  32322. parseId3TagSize: parseId3TagSize,
  32323. parseAdtsSize: parseAdtsSize,
  32324. parseType: parseType$4,
  32325. parseSampleRate: parseSampleRate,
  32326. parseAacTimestamp: parseAacTimestamp
  32327. };
  32328. /**
  32329. * mux.js
  32330. *
  32331. * Copyright (c) Brightcove
  32332. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  32333. *
  32334. * A stream-based aac to mp4 converter. This utility can be used to
  32335. * deliver mp4s to a SourceBuffer on platforms that support native
  32336. * Media Source Extensions.
  32337. */
  32338. var Stream$1 = stream;
  32339. var aacUtils = utils; // Constants
  32340. var AacStream$1;
  32341. /**
  32342. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  32343. */
  32344. AacStream$1 = function () {
  32345. var everything = new Uint8Array(),
  32346. timeStamp = 0;
  32347. AacStream$1.prototype.init.call(this);
  32348. this.setTimestamp = function (timestamp) {
  32349. timeStamp = timestamp;
  32350. };
  32351. this.push = function (bytes) {
  32352. var frameSize = 0,
  32353. byteIndex = 0,
  32354. bytesLeft,
  32355. chunk,
  32356. packet,
  32357. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  32358. // bytes that were pushed in
  32359. if (everything.length) {
  32360. tempLength = everything.length;
  32361. everything = new Uint8Array(bytes.byteLength + tempLength);
  32362. everything.set(everything.subarray(0, tempLength));
  32363. everything.set(bytes, tempLength);
  32364. } else {
  32365. everything = bytes;
  32366. }
  32367. while (everything.length - byteIndex >= 3) {
  32368. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  32369. // Exit early because we don't have enough to parse
  32370. // the ID3 tag header
  32371. if (everything.length - byteIndex < 10) {
  32372. break;
  32373. } // check framesize
  32374. frameSize = aacUtils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  32375. // to emit a full packet
  32376. // Add to byteIndex to support multiple ID3 tags in sequence
  32377. if (byteIndex + frameSize > everything.length) {
  32378. break;
  32379. }
  32380. chunk = {
  32381. type: 'timed-metadata',
  32382. data: everything.subarray(byteIndex, byteIndex + frameSize)
  32383. };
  32384. this.trigger('data', chunk);
  32385. byteIndex += frameSize;
  32386. continue;
  32387. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  32388. // Exit early because we don't have enough to parse
  32389. // the ADTS frame header
  32390. if (everything.length - byteIndex < 7) {
  32391. break;
  32392. }
  32393. frameSize = aacUtils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  32394. // to emit a full packet
  32395. if (byteIndex + frameSize > everything.length) {
  32396. break;
  32397. }
  32398. packet = {
  32399. type: 'audio',
  32400. data: everything.subarray(byteIndex, byteIndex + frameSize),
  32401. pts: timeStamp,
  32402. dts: timeStamp
  32403. };
  32404. this.trigger('data', packet);
  32405. byteIndex += frameSize;
  32406. continue;
  32407. }
  32408. byteIndex++;
  32409. }
  32410. bytesLeft = everything.length - byteIndex;
  32411. if (bytesLeft > 0) {
  32412. everything = everything.subarray(byteIndex);
  32413. } else {
  32414. everything = new Uint8Array();
  32415. }
  32416. };
  32417. this.reset = function () {
  32418. everything = new Uint8Array();
  32419. this.trigger('reset');
  32420. };
  32421. this.endTimeline = function () {
  32422. everything = new Uint8Array();
  32423. this.trigger('endedtimeline');
  32424. };
  32425. };
  32426. AacStream$1.prototype = new Stream$1();
  32427. var aac = AacStream$1;
  32428. var AUDIO_PROPERTIES$1 = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  32429. var audioProperties = AUDIO_PROPERTIES$1;
  32430. var VIDEO_PROPERTIES$1 = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  32431. var videoProperties = VIDEO_PROPERTIES$1;
  32432. /**
  32433. * mux.js
  32434. *
  32435. * Copyright (c) Brightcove
  32436. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  32437. *
  32438. * A stream-based mp2t to mp4 converter. This utility can be used to
  32439. * deliver mp4s to a SourceBuffer on platforms that support native
  32440. * Media Source Extensions.
  32441. */
  32442. var Stream = stream;
  32443. var mp4 = mp4Generator;
  32444. var frameUtils = frameUtils$1;
  32445. var audioFrameUtils = audioFrameUtils$1;
  32446. var trackDecodeInfo = trackDecodeInfo$1;
  32447. var m2ts = m2ts_1;
  32448. var clock = clock$2;
  32449. var AdtsStream = adts;
  32450. var H264Stream = h264.H264Stream;
  32451. var AacStream = aac;
  32452. var isLikelyAacData = utils.isLikelyAacData;
  32453. var ONE_SECOND_IN_TS$1 = clock$2.ONE_SECOND_IN_TS;
  32454. var AUDIO_PROPERTIES = audioProperties;
  32455. var VIDEO_PROPERTIES = videoProperties; // object types
  32456. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  32457. var retriggerForStream = function (key, event) {
  32458. event.stream = key;
  32459. this.trigger('log', event);
  32460. };
  32461. var addPipelineLogRetriggers = function (transmuxer, pipeline) {
  32462. var keys = Object.keys(pipeline);
  32463. for (var i = 0; i < keys.length; i++) {
  32464. var key = keys[i]; // skip non-stream keys and headOfPipeline
  32465. // which is just a duplicate
  32466. if (key === 'headOfPipeline' || !pipeline[key].on) {
  32467. continue;
  32468. }
  32469. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  32470. }
  32471. };
  32472. /**
  32473. * Compare two arrays (even typed) for same-ness
  32474. */
  32475. var arrayEquals = function (a, b) {
  32476. var i;
  32477. if (a.length !== b.length) {
  32478. return false;
  32479. } // compare the value of each element in the array
  32480. for (i = 0; i < a.length; i++) {
  32481. if (a[i] !== b[i]) {
  32482. return false;
  32483. }
  32484. }
  32485. return true;
  32486. };
  32487. var generateSegmentTimingInfo = function (baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  32488. var ptsOffsetFromDts = startPts - startDts,
  32489. decodeDuration = endDts - startDts,
  32490. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  32491. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  32492. // In order to provide relevant values for the player times, base timing info on the
  32493. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  32494. return {
  32495. start: {
  32496. dts: baseMediaDecodeTime,
  32497. pts: baseMediaDecodeTime + ptsOffsetFromDts
  32498. },
  32499. end: {
  32500. dts: baseMediaDecodeTime + decodeDuration,
  32501. pts: baseMediaDecodeTime + presentationDuration
  32502. },
  32503. prependedContentDuration: prependedContentDuration,
  32504. baseMediaDecodeTime: baseMediaDecodeTime
  32505. };
  32506. };
  32507. /**
  32508. * Constructs a single-track, ISO BMFF media segment from AAC data
  32509. * events. The output of this stream can be fed to a SourceBuffer
  32510. * configured with a suitable initialization segment.
  32511. * @param track {object} track metadata configuration
  32512. * @param options {object} transmuxer options object
  32513. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  32514. * in the source; false to adjust the first segment to start at 0.
  32515. */
  32516. AudioSegmentStream = function (track, options) {
  32517. var adtsFrames = [],
  32518. sequenceNumber,
  32519. earliestAllowedDts = 0,
  32520. audioAppendStartTs = 0,
  32521. videoBaseMediaDecodeTime = Infinity;
  32522. options = options || {};
  32523. sequenceNumber = options.firstSequenceNumber || 0;
  32524. AudioSegmentStream.prototype.init.call(this);
  32525. this.push = function (data) {
  32526. trackDecodeInfo.collectDtsInfo(track, data);
  32527. if (track) {
  32528. AUDIO_PROPERTIES.forEach(function (prop) {
  32529. track[prop] = data[prop];
  32530. });
  32531. } // buffer audio data until end() is called
  32532. adtsFrames.push(data);
  32533. };
  32534. this.setEarliestDts = function (earliestDts) {
  32535. earliestAllowedDts = earliestDts;
  32536. };
  32537. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  32538. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  32539. };
  32540. this.setAudioAppendStart = function (timestamp) {
  32541. audioAppendStartTs = timestamp;
  32542. };
  32543. this.flush = function () {
  32544. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  32545. if (adtsFrames.length === 0) {
  32546. this.trigger('done', 'AudioSegmentStream');
  32547. return;
  32548. }
  32549. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  32550. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  32551. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  32552. // samples (that is, adts frames) in the audio data
  32553. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  32554. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  32555. adtsFrames = [];
  32556. moof = mp4.moof(sequenceNumber, [track]);
  32557. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  32558. sequenceNumber++;
  32559. boxes.set(moof);
  32560. boxes.set(mdat, moof.byteLength);
  32561. trackDecodeInfo.clearDtsInfo(track);
  32562. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  32563. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  32564. // valid use-case where an init segment/data should be triggered without associated
  32565. // frames. Leaving for now, but should be looked into.
  32566. if (frames.length) {
  32567. segmentDuration = frames.length * frameDuration;
  32568. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(
  32569. // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  32570. // frame info is in video clock cycles. Convert to match expectation of
  32571. // listeners (that all timestamps will be based on video clock cycles).
  32572. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate),
  32573. // frame times are already in video clock, as is segment duration
  32574. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  32575. this.trigger('timingInfo', {
  32576. start: frames[0].pts,
  32577. end: frames[0].pts + segmentDuration
  32578. });
  32579. }
  32580. this.trigger('data', {
  32581. track: track,
  32582. boxes: boxes
  32583. });
  32584. this.trigger('done', 'AudioSegmentStream');
  32585. };
  32586. this.reset = function () {
  32587. trackDecodeInfo.clearDtsInfo(track);
  32588. adtsFrames = [];
  32589. this.trigger('reset');
  32590. };
  32591. };
  32592. AudioSegmentStream.prototype = new Stream();
  32593. /**
  32594. * Constructs a single-track, ISO BMFF media segment from H264 data
  32595. * events. The output of this stream can be fed to a SourceBuffer
  32596. * configured with a suitable initialization segment.
  32597. * @param track {object} track metadata configuration
  32598. * @param options {object} transmuxer options object
  32599. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  32600. * gopsToAlignWith list when attempting to align gop pts
  32601. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  32602. * in the source; false to adjust the first segment to start at 0.
  32603. */
  32604. VideoSegmentStream = function (track, options) {
  32605. var sequenceNumber,
  32606. nalUnits = [],
  32607. gopsToAlignWith = [],
  32608. config,
  32609. pps;
  32610. options = options || {};
  32611. sequenceNumber = options.firstSequenceNumber || 0;
  32612. VideoSegmentStream.prototype.init.call(this);
  32613. delete track.minPTS;
  32614. this.gopCache_ = [];
  32615. /**
  32616. * Constructs a ISO BMFF segment given H264 nalUnits
  32617. * @param {Object} nalUnit A data event representing a nalUnit
  32618. * @param {String} nalUnit.nalUnitType
  32619. * @param {Object} nalUnit.config Properties for a mp4 track
  32620. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  32621. * @see lib/codecs/h264.js
  32622. **/
  32623. this.push = function (nalUnit) {
  32624. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  32625. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  32626. config = nalUnit.config;
  32627. track.sps = [nalUnit.data];
  32628. VIDEO_PROPERTIES.forEach(function (prop) {
  32629. track[prop] = config[prop];
  32630. }, this);
  32631. }
  32632. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  32633. pps = nalUnit.data;
  32634. track.pps = [nalUnit.data];
  32635. } // buffer video until flush() is called
  32636. nalUnits.push(nalUnit);
  32637. };
  32638. /**
  32639. * Pass constructed ISO BMFF track and boxes on to the
  32640. * next stream in the pipeline
  32641. **/
  32642. this.flush = function () {
  32643. var frames,
  32644. gopForFusion,
  32645. gops,
  32646. moof,
  32647. mdat,
  32648. boxes,
  32649. prependedContentDuration = 0,
  32650. firstGop,
  32651. lastGop; // Throw away nalUnits at the start of the byte stream until
  32652. // we find the first AUD
  32653. while (nalUnits.length) {
  32654. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  32655. break;
  32656. }
  32657. nalUnits.shift();
  32658. } // Return early if no video data has been observed
  32659. if (nalUnits.length === 0) {
  32660. this.resetStream_();
  32661. this.trigger('done', 'VideoSegmentStream');
  32662. return;
  32663. } // Organize the raw nal-units into arrays that represent
  32664. // higher-level constructs such as frames and gops
  32665. // (group-of-pictures)
  32666. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  32667. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  32668. // a problem since MSE (on Chrome) requires a leading keyframe.
  32669. //
  32670. // We have two approaches to repairing this situation:
  32671. // 1) GOP-FUSION:
  32672. // This is where we keep track of the GOPS (group-of-pictures)
  32673. // from previous fragments and attempt to find one that we can
  32674. // prepend to the current fragment in order to create a valid
  32675. // fragment.
  32676. // 2) KEYFRAME-PULLING:
  32677. // Here we search for the first keyframe in the fragment and
  32678. // throw away all the frames between the start of the fragment
  32679. // and that keyframe. We then extend the duration and pull the
  32680. // PTS of the keyframe forward so that it covers the time range
  32681. // of the frames that were disposed of.
  32682. //
  32683. // #1 is far prefereable over #2 which can cause "stuttering" but
  32684. // requires more things to be just right.
  32685. if (!gops[0][0].keyFrame) {
  32686. // Search for a gop for fusion from our gopCache
  32687. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  32688. if (gopForFusion) {
  32689. // in order to provide more accurate timing information about the segment, save
  32690. // the number of seconds prepended to the original segment due to GOP fusion
  32691. prependedContentDuration = gopForFusion.duration;
  32692. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  32693. // new gop at the beginning
  32694. gops.byteLength += gopForFusion.byteLength;
  32695. gops.nalCount += gopForFusion.nalCount;
  32696. gops.pts = gopForFusion.pts;
  32697. gops.dts = gopForFusion.dts;
  32698. gops.duration += gopForFusion.duration;
  32699. } else {
  32700. // If we didn't find a candidate gop fall back to keyframe-pulling
  32701. gops = frameUtils.extendFirstKeyFrame(gops);
  32702. }
  32703. } // Trim gops to align with gopsToAlignWith
  32704. if (gopsToAlignWith.length) {
  32705. var alignedGops;
  32706. if (options.alignGopsAtEnd) {
  32707. alignedGops = this.alignGopsAtEnd_(gops);
  32708. } else {
  32709. alignedGops = this.alignGopsAtStart_(gops);
  32710. }
  32711. if (!alignedGops) {
  32712. // save all the nals in the last GOP into the gop cache
  32713. this.gopCache_.unshift({
  32714. gop: gops.pop(),
  32715. pps: track.pps,
  32716. sps: track.sps
  32717. }); // Keep a maximum of 6 GOPs in the cache
  32718. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  32719. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  32720. this.resetStream_();
  32721. this.trigger('done', 'VideoSegmentStream');
  32722. return;
  32723. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  32724. // when recalculated before sending off to CoalesceStream
  32725. trackDecodeInfo.clearDtsInfo(track);
  32726. gops = alignedGops;
  32727. }
  32728. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  32729. // samples (that is, frames) in the video data
  32730. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  32731. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  32732. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  32733. this.trigger('processedGopsInfo', gops.map(function (gop) {
  32734. return {
  32735. pts: gop.pts,
  32736. dts: gop.dts,
  32737. byteLength: gop.byteLength
  32738. };
  32739. }));
  32740. firstGop = gops[0];
  32741. lastGop = gops[gops.length - 1];
  32742. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  32743. this.trigger('timingInfo', {
  32744. start: gops[0].pts,
  32745. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  32746. }); // save all the nals in the last GOP into the gop cache
  32747. this.gopCache_.unshift({
  32748. gop: gops.pop(),
  32749. pps: track.pps,
  32750. sps: track.sps
  32751. }); // Keep a maximum of 6 GOPs in the cache
  32752. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  32753. nalUnits = [];
  32754. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  32755. this.trigger('timelineStartInfo', track.timelineStartInfo);
  32756. moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  32757. // throwing away hundreds of media segment fragments
  32758. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  32759. sequenceNumber++;
  32760. boxes.set(moof);
  32761. boxes.set(mdat, moof.byteLength);
  32762. this.trigger('data', {
  32763. track: track,
  32764. boxes: boxes
  32765. });
  32766. this.resetStream_(); // Continue with the flush process now
  32767. this.trigger('done', 'VideoSegmentStream');
  32768. };
  32769. this.reset = function () {
  32770. this.resetStream_();
  32771. nalUnits = [];
  32772. this.gopCache_.length = 0;
  32773. gopsToAlignWith.length = 0;
  32774. this.trigger('reset');
  32775. };
  32776. this.resetStream_ = function () {
  32777. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  32778. // for instance, when we are rendition switching
  32779. config = undefined;
  32780. pps = undefined;
  32781. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  32782. // return it or return null if no good candidate was found
  32783. this.getGopForFusion_ = function (nalUnit) {
  32784. var halfSecond = 45000,
  32785. // Half-a-second in a 90khz clock
  32786. allowableOverlap = 10000,
  32787. // About 3 frames @ 30fps
  32788. nearestDistance = Infinity,
  32789. dtsDistance,
  32790. nearestGopObj,
  32791. currentGop,
  32792. currentGopObj,
  32793. i; // Search for the GOP nearest to the beginning of this nal unit
  32794. for (i = 0; i < this.gopCache_.length; i++) {
  32795. currentGopObj = this.gopCache_[i];
  32796. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  32797. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  32798. continue;
  32799. } // Reject Gops that would require a negative baseMediaDecodeTime
  32800. if (currentGop.dts < track.timelineStartInfo.dts) {
  32801. continue;
  32802. } // The distance between the end of the gop and the start of the nalUnit
  32803. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  32804. // a half-second of the nal unit
  32805. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  32806. // Always use the closest GOP we found if there is more than
  32807. // one candidate
  32808. if (!nearestGopObj || nearestDistance > dtsDistance) {
  32809. nearestGopObj = currentGopObj;
  32810. nearestDistance = dtsDistance;
  32811. }
  32812. }
  32813. }
  32814. if (nearestGopObj) {
  32815. return nearestGopObj.gop;
  32816. }
  32817. return null;
  32818. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  32819. // of gopsToAlignWith starting from the START of the list
  32820. this.alignGopsAtStart_ = function (gops) {
  32821. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  32822. byteLength = gops.byteLength;
  32823. nalCount = gops.nalCount;
  32824. duration = gops.duration;
  32825. alignIndex = gopIndex = 0;
  32826. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  32827. align = gopsToAlignWith[alignIndex];
  32828. gop = gops[gopIndex];
  32829. if (align.pts === gop.pts) {
  32830. break;
  32831. }
  32832. if (gop.pts > align.pts) {
  32833. // this current gop starts after the current gop we want to align on, so increment
  32834. // align index
  32835. alignIndex++;
  32836. continue;
  32837. } // current gop starts before the current gop we want to align on. so increment gop
  32838. // index
  32839. gopIndex++;
  32840. byteLength -= gop.byteLength;
  32841. nalCount -= gop.nalCount;
  32842. duration -= gop.duration;
  32843. }
  32844. if (gopIndex === 0) {
  32845. // no gops to trim
  32846. return gops;
  32847. }
  32848. if (gopIndex === gops.length) {
  32849. // all gops trimmed, skip appending all gops
  32850. return null;
  32851. }
  32852. alignedGops = gops.slice(gopIndex);
  32853. alignedGops.byteLength = byteLength;
  32854. alignedGops.duration = duration;
  32855. alignedGops.nalCount = nalCount;
  32856. alignedGops.pts = alignedGops[0].pts;
  32857. alignedGops.dts = alignedGops[0].dts;
  32858. return alignedGops;
  32859. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  32860. // of gopsToAlignWith starting from the END of the list
  32861. this.alignGopsAtEnd_ = function (gops) {
  32862. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  32863. alignIndex = gopsToAlignWith.length - 1;
  32864. gopIndex = gops.length - 1;
  32865. alignEndIndex = null;
  32866. matchFound = false;
  32867. while (alignIndex >= 0 && gopIndex >= 0) {
  32868. align = gopsToAlignWith[alignIndex];
  32869. gop = gops[gopIndex];
  32870. if (align.pts === gop.pts) {
  32871. matchFound = true;
  32872. break;
  32873. }
  32874. if (align.pts > gop.pts) {
  32875. alignIndex--;
  32876. continue;
  32877. }
  32878. if (alignIndex === gopsToAlignWith.length - 1) {
  32879. // gop.pts is greater than the last alignment candidate. If no match is found
  32880. // by the end of this loop, we still want to append gops that come after this
  32881. // point
  32882. alignEndIndex = gopIndex;
  32883. }
  32884. gopIndex--;
  32885. }
  32886. if (!matchFound && alignEndIndex === null) {
  32887. return null;
  32888. }
  32889. var trimIndex;
  32890. if (matchFound) {
  32891. trimIndex = gopIndex;
  32892. } else {
  32893. trimIndex = alignEndIndex;
  32894. }
  32895. if (trimIndex === 0) {
  32896. return gops;
  32897. }
  32898. var alignedGops = gops.slice(trimIndex);
  32899. var metadata = alignedGops.reduce(function (total, gop) {
  32900. total.byteLength += gop.byteLength;
  32901. total.duration += gop.duration;
  32902. total.nalCount += gop.nalCount;
  32903. return total;
  32904. }, {
  32905. byteLength: 0,
  32906. duration: 0,
  32907. nalCount: 0
  32908. });
  32909. alignedGops.byteLength = metadata.byteLength;
  32910. alignedGops.duration = metadata.duration;
  32911. alignedGops.nalCount = metadata.nalCount;
  32912. alignedGops.pts = alignedGops[0].pts;
  32913. alignedGops.dts = alignedGops[0].dts;
  32914. return alignedGops;
  32915. };
  32916. this.alignGopsWith = function (newGopsToAlignWith) {
  32917. gopsToAlignWith = newGopsToAlignWith;
  32918. };
  32919. };
  32920. VideoSegmentStream.prototype = new Stream();
  32921. /**
  32922. * A Stream that can combine multiple streams (ie. audio & video)
  32923. * into a single output segment for MSE. Also supports audio-only
  32924. * and video-only streams.
  32925. * @param options {object} transmuxer options object
  32926. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  32927. * in the source; false to adjust the first segment to start at media timeline start.
  32928. */
  32929. CoalesceStream = function (options, metadataStream) {
  32930. // Number of Tracks per output segment
  32931. // If greater than 1, we combine multiple
  32932. // tracks into a single segment
  32933. this.numberOfTracks = 0;
  32934. this.metadataStream = metadataStream;
  32935. options = options || {};
  32936. if (typeof options.remux !== 'undefined') {
  32937. this.remuxTracks = !!options.remux;
  32938. } else {
  32939. this.remuxTracks = true;
  32940. }
  32941. if (typeof options.keepOriginalTimestamps === 'boolean') {
  32942. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  32943. } else {
  32944. this.keepOriginalTimestamps = false;
  32945. }
  32946. this.pendingTracks = [];
  32947. this.videoTrack = null;
  32948. this.pendingBoxes = [];
  32949. this.pendingCaptions = [];
  32950. this.pendingMetadata = [];
  32951. this.pendingBytes = 0;
  32952. this.emittedTracks = 0;
  32953. CoalesceStream.prototype.init.call(this); // Take output from multiple
  32954. this.push = function (output) {
  32955. // buffer incoming captions until the associated video segment
  32956. // finishes
  32957. if (output.text) {
  32958. return this.pendingCaptions.push(output);
  32959. } // buffer incoming id3 tags until the final flush
  32960. if (output.frames) {
  32961. return this.pendingMetadata.push(output);
  32962. } // Add this track to the list of pending tracks and store
  32963. // important information required for the construction of
  32964. // the final segment
  32965. this.pendingTracks.push(output.track);
  32966. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  32967. // We unshift audio and push video because
  32968. // as of Chrome 75 when switching from
  32969. // one init segment to another if the video
  32970. // mdat does not appear after the audio mdat
  32971. // only audio will play for the duration of our transmux.
  32972. if (output.track.type === 'video') {
  32973. this.videoTrack = output.track;
  32974. this.pendingBoxes.push(output.boxes);
  32975. }
  32976. if (output.track.type === 'audio') {
  32977. this.audioTrack = output.track;
  32978. this.pendingBoxes.unshift(output.boxes);
  32979. }
  32980. };
  32981. };
  32982. CoalesceStream.prototype = new Stream();
  32983. CoalesceStream.prototype.flush = function (flushSource) {
  32984. var offset = 0,
  32985. event = {
  32986. captions: [],
  32987. captionStreams: {},
  32988. metadata: [],
  32989. info: {}
  32990. },
  32991. caption,
  32992. id3,
  32993. initSegment,
  32994. timelineStartPts = 0,
  32995. i;
  32996. if (this.pendingTracks.length < this.numberOfTracks) {
  32997. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  32998. // Return because we haven't received a flush from a data-generating
  32999. // portion of the segment (meaning that we have only recieved meta-data
  33000. // or captions.)
  33001. return;
  33002. } else if (this.remuxTracks) {
  33003. // Return until we have enough tracks from the pipeline to remux (if we
  33004. // are remuxing audio and video into a single MP4)
  33005. return;
  33006. } else if (this.pendingTracks.length === 0) {
  33007. // In the case where we receive a flush without any data having been
  33008. // received we consider it an emitted track for the purposes of coalescing
  33009. // `done` events.
  33010. // We do this for the case where there is an audio and video track in the
  33011. // segment but no audio data. (seen in several playlists with alternate
  33012. // audio tracks and no audio present in the main TS segments.)
  33013. this.emittedTracks++;
  33014. if (this.emittedTracks >= this.numberOfTracks) {
  33015. this.trigger('done');
  33016. this.emittedTracks = 0;
  33017. }
  33018. return;
  33019. }
  33020. }
  33021. if (this.videoTrack) {
  33022. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  33023. VIDEO_PROPERTIES.forEach(function (prop) {
  33024. event.info[prop] = this.videoTrack[prop];
  33025. }, this);
  33026. } else if (this.audioTrack) {
  33027. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  33028. AUDIO_PROPERTIES.forEach(function (prop) {
  33029. event.info[prop] = this.audioTrack[prop];
  33030. }, this);
  33031. }
  33032. if (this.videoTrack || this.audioTrack) {
  33033. if (this.pendingTracks.length === 1) {
  33034. event.type = this.pendingTracks[0].type;
  33035. } else {
  33036. event.type = 'combined';
  33037. }
  33038. this.emittedTracks += this.pendingTracks.length;
  33039. initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  33040. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  33041. // and track definitions
  33042. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  33043. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  33044. for (i = 0; i < this.pendingBoxes.length; i++) {
  33045. event.data.set(this.pendingBoxes[i], offset);
  33046. offset += this.pendingBoxes[i].byteLength;
  33047. } // Translate caption PTS times into second offsets to match the
  33048. // video timeline for the segment, and add track info
  33049. for (i = 0; i < this.pendingCaptions.length; i++) {
  33050. caption = this.pendingCaptions[i];
  33051. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  33052. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  33053. event.captionStreams[caption.stream] = true;
  33054. event.captions.push(caption);
  33055. } // Translate ID3 frame PTS times into second offsets to match the
  33056. // video timeline for the segment
  33057. for (i = 0; i < this.pendingMetadata.length; i++) {
  33058. id3 = this.pendingMetadata[i];
  33059. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  33060. event.metadata.push(id3);
  33061. } // We add this to every single emitted segment even though we only need
  33062. // it for the first
  33063. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  33064. this.pendingTracks.length = 0;
  33065. this.videoTrack = null;
  33066. this.pendingBoxes.length = 0;
  33067. this.pendingCaptions.length = 0;
  33068. this.pendingBytes = 0;
  33069. this.pendingMetadata.length = 0; // Emit the built segment
  33070. // We include captions and ID3 tags for backwards compatibility,
  33071. // ideally we should send only video and audio in the data event
  33072. this.trigger('data', event); // Emit each caption to the outside world
  33073. // Ideally, this would happen immediately on parsing captions,
  33074. // but we need to ensure that video data is sent back first
  33075. // so that caption timing can be adjusted to match video timing
  33076. for (i = 0; i < event.captions.length; i++) {
  33077. caption = event.captions[i];
  33078. this.trigger('caption', caption);
  33079. } // Emit each id3 tag to the outside world
  33080. // Ideally, this would happen immediately on parsing the tag,
  33081. // but we need to ensure that video data is sent back first
  33082. // so that ID3 frame timing can be adjusted to match video timing
  33083. for (i = 0; i < event.metadata.length; i++) {
  33084. id3 = event.metadata[i];
  33085. this.trigger('id3Frame', id3);
  33086. }
  33087. } // Only emit `done` if all tracks have been flushed and emitted
  33088. if (this.emittedTracks >= this.numberOfTracks) {
  33089. this.trigger('done');
  33090. this.emittedTracks = 0;
  33091. }
  33092. };
  33093. CoalesceStream.prototype.setRemux = function (val) {
  33094. this.remuxTracks = val;
  33095. };
  33096. /**
  33097. * A Stream that expects MP2T binary data as input and produces
  33098. * corresponding media segments, suitable for use with Media Source
  33099. * Extension (MSE) implementations that support the ISO BMFF byte
  33100. * stream format, like Chrome.
  33101. */
  33102. Transmuxer = function (options) {
  33103. var self = this,
  33104. hasFlushed = true,
  33105. videoTrack,
  33106. audioTrack;
  33107. Transmuxer.prototype.init.call(this);
  33108. options = options || {};
  33109. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  33110. this.transmuxPipeline_ = {};
  33111. this.setupAacPipeline = function () {
  33112. var pipeline = {};
  33113. this.transmuxPipeline_ = pipeline;
  33114. pipeline.type = 'aac';
  33115. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  33116. pipeline.aacStream = new AacStream();
  33117. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  33118. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  33119. pipeline.adtsStream = new AdtsStream();
  33120. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  33121. pipeline.headOfPipeline = pipeline.aacStream;
  33122. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  33123. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  33124. pipeline.metadataStream.on('timestamp', function (frame) {
  33125. pipeline.aacStream.setTimestamp(frame.timeStamp);
  33126. });
  33127. pipeline.aacStream.on('data', function (data) {
  33128. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  33129. return;
  33130. }
  33131. audioTrack = audioTrack || {
  33132. timelineStartInfo: {
  33133. baseMediaDecodeTime: self.baseMediaDecodeTime
  33134. },
  33135. codec: 'adts',
  33136. type: 'audio'
  33137. }; // hook up the audio segment stream to the first track with aac data
  33138. pipeline.coalesceStream.numberOfTracks++;
  33139. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  33140. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  33141. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  33142. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  33143. self.trigger('trackinfo', {
  33144. hasAudio: !!audioTrack,
  33145. hasVideo: !!videoTrack
  33146. });
  33147. }); // Re-emit any data coming from the coalesce stream to the outside world
  33148. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  33149. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  33150. addPipelineLogRetriggers(this, pipeline);
  33151. };
  33152. this.setupTsPipeline = function () {
  33153. var pipeline = {};
  33154. this.transmuxPipeline_ = pipeline;
  33155. pipeline.type = 'ts';
  33156. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  33157. pipeline.packetStream = new m2ts.TransportPacketStream();
  33158. pipeline.parseStream = new m2ts.TransportParseStream();
  33159. pipeline.elementaryStream = new m2ts.ElementaryStream();
  33160. pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
  33161. pipeline.adtsStream = new AdtsStream();
  33162. pipeline.h264Stream = new H264Stream();
  33163. pipeline.captionStream = new m2ts.CaptionStream(options);
  33164. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  33165. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  33166. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  33167. // demux the streams
  33168. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  33169. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  33170. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  33171. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  33172. pipeline.elementaryStream.on('data', function (data) {
  33173. var i;
  33174. if (data.type === 'metadata') {
  33175. i = data.tracks.length; // scan the tracks listed in the metadata
  33176. while (i--) {
  33177. if (!videoTrack && data.tracks[i].type === 'video') {
  33178. videoTrack = data.tracks[i];
  33179. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  33180. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  33181. audioTrack = data.tracks[i];
  33182. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  33183. }
  33184. } // hook up the video segment stream to the first track with h264 data
  33185. if (videoTrack && !pipeline.videoSegmentStream) {
  33186. pipeline.coalesceStream.numberOfTracks++;
  33187. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  33188. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  33189. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  33190. // When video emits timelineStartInfo data after a flush, we forward that
  33191. // info to the AudioSegmentStream, if it exists, because video timeline
  33192. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  33193. // because this is a particularly subtle form of timestamp alteration.
  33194. if (audioTrack && !options.keepOriginalTimestamps) {
  33195. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  33196. // very earliest DTS we have seen in video because Chrome will
  33197. // interpret any video track with a baseMediaDecodeTime that is
  33198. // non-zero as a gap.
  33199. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  33200. }
  33201. });
  33202. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  33203. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  33204. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  33205. if (audioTrack) {
  33206. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  33207. }
  33208. });
  33209. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  33210. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  33211. }
  33212. if (audioTrack && !pipeline.audioSegmentStream) {
  33213. // hook up the audio segment stream to the first track with aac data
  33214. pipeline.coalesceStream.numberOfTracks++;
  33215. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  33216. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  33217. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  33218. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  33219. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  33220. } // emit pmt info
  33221. self.trigger('trackinfo', {
  33222. hasAudio: !!audioTrack,
  33223. hasVideo: !!videoTrack
  33224. });
  33225. }
  33226. }); // Re-emit any data coming from the coalesce stream to the outside world
  33227. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  33228. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  33229. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  33230. self.trigger('id3Frame', id3Frame);
  33231. });
  33232. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  33233. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  33234. addPipelineLogRetriggers(this, pipeline);
  33235. }; // hook up the segment streams once track metadata is delivered
  33236. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  33237. var pipeline = this.transmuxPipeline_;
  33238. if (!options.keepOriginalTimestamps) {
  33239. this.baseMediaDecodeTime = baseMediaDecodeTime;
  33240. }
  33241. if (audioTrack) {
  33242. audioTrack.timelineStartInfo.dts = undefined;
  33243. audioTrack.timelineStartInfo.pts = undefined;
  33244. trackDecodeInfo.clearDtsInfo(audioTrack);
  33245. if (pipeline.audioTimestampRolloverStream) {
  33246. pipeline.audioTimestampRolloverStream.discontinuity();
  33247. }
  33248. }
  33249. if (videoTrack) {
  33250. if (pipeline.videoSegmentStream) {
  33251. pipeline.videoSegmentStream.gopCache_ = [];
  33252. }
  33253. videoTrack.timelineStartInfo.dts = undefined;
  33254. videoTrack.timelineStartInfo.pts = undefined;
  33255. trackDecodeInfo.clearDtsInfo(videoTrack);
  33256. pipeline.captionStream.reset();
  33257. }
  33258. if (pipeline.timestampRolloverStream) {
  33259. pipeline.timestampRolloverStream.discontinuity();
  33260. }
  33261. };
  33262. this.setAudioAppendStart = function (timestamp) {
  33263. if (audioTrack) {
  33264. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  33265. }
  33266. };
  33267. this.setRemux = function (val) {
  33268. var pipeline = this.transmuxPipeline_;
  33269. options.remux = val;
  33270. if (pipeline && pipeline.coalesceStream) {
  33271. pipeline.coalesceStream.setRemux(val);
  33272. }
  33273. };
  33274. this.alignGopsWith = function (gopsToAlignWith) {
  33275. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  33276. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  33277. }
  33278. };
  33279. this.getLogTrigger_ = function (key) {
  33280. var self = this;
  33281. return function (event) {
  33282. event.stream = key;
  33283. self.trigger('log', event);
  33284. };
  33285. }; // feed incoming data to the front of the parsing pipeline
  33286. this.push = function (data) {
  33287. if (hasFlushed) {
  33288. var isAac = isLikelyAacData(data);
  33289. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  33290. this.setupAacPipeline();
  33291. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  33292. this.setupTsPipeline();
  33293. }
  33294. hasFlushed = false;
  33295. }
  33296. this.transmuxPipeline_.headOfPipeline.push(data);
  33297. }; // flush any buffered data
  33298. this.flush = function () {
  33299. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  33300. this.transmuxPipeline_.headOfPipeline.flush();
  33301. };
  33302. this.endTimeline = function () {
  33303. this.transmuxPipeline_.headOfPipeline.endTimeline();
  33304. };
  33305. this.reset = function () {
  33306. if (this.transmuxPipeline_.headOfPipeline) {
  33307. this.transmuxPipeline_.headOfPipeline.reset();
  33308. }
  33309. }; // Caption data has to be reset when seeking outside buffered range
  33310. this.resetCaptions = function () {
  33311. if (this.transmuxPipeline_.captionStream) {
  33312. this.transmuxPipeline_.captionStream.reset();
  33313. }
  33314. };
  33315. };
  33316. Transmuxer.prototype = new Stream();
  33317. var transmuxer = {
  33318. Transmuxer: Transmuxer,
  33319. VideoSegmentStream: VideoSegmentStream,
  33320. AudioSegmentStream: AudioSegmentStream,
  33321. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  33322. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  33323. // exported for testing
  33324. generateSegmentTimingInfo: generateSegmentTimingInfo
  33325. };
  33326. /**
  33327. * mux.js
  33328. *
  33329. * Copyright (c) Brightcove
  33330. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  33331. */
  33332. var toUnsigned$3 = function (value) {
  33333. return value >>> 0;
  33334. };
  33335. var toHexString$1 = function (value) {
  33336. return ('00' + value.toString(16)).slice(-2);
  33337. };
  33338. var bin = {
  33339. toUnsigned: toUnsigned$3,
  33340. toHexString: toHexString$1
  33341. };
  33342. var parseType$3 = function (buffer) {
  33343. var result = '';
  33344. result += String.fromCharCode(buffer[0]);
  33345. result += String.fromCharCode(buffer[1]);
  33346. result += String.fromCharCode(buffer[2]);
  33347. result += String.fromCharCode(buffer[3]);
  33348. return result;
  33349. };
  33350. var parseType_1 = parseType$3;
  33351. var toUnsigned$2 = bin.toUnsigned;
  33352. var parseType$2 = parseType_1;
  33353. var findBox$2 = function (data, path) {
  33354. var results = [],
  33355. i,
  33356. size,
  33357. type,
  33358. end,
  33359. subresults;
  33360. if (!path.length) {
  33361. // short-circuit the search for empty paths
  33362. return null;
  33363. }
  33364. for (i = 0; i < data.byteLength;) {
  33365. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  33366. type = parseType$2(data.subarray(i + 4, i + 8));
  33367. end = size > 1 ? i + size : data.byteLength;
  33368. if (type === path[0]) {
  33369. if (path.length === 1) {
  33370. // this is the end of the path and we've found the box we were
  33371. // looking for
  33372. results.push(data.subarray(i + 8, end));
  33373. } else {
  33374. // recursively search for the next box along the path
  33375. subresults = findBox$2(data.subarray(i + 8, end), path.slice(1));
  33376. if (subresults.length) {
  33377. results = results.concat(subresults);
  33378. }
  33379. }
  33380. }
  33381. i = end;
  33382. } // we've finished searching all of data
  33383. return results;
  33384. };
  33385. var findBox_1 = findBox$2;
  33386. var toUnsigned$1 = bin.toUnsigned;
  33387. var getUint64$2 = numbers.getUint64;
  33388. var tfdt = function (data) {
  33389. var result = {
  33390. version: data[0],
  33391. flags: new Uint8Array(data.subarray(1, 4))
  33392. };
  33393. if (result.version === 1) {
  33394. result.baseMediaDecodeTime = getUint64$2(data.subarray(4));
  33395. } else {
  33396. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  33397. }
  33398. return result;
  33399. };
  33400. var parseTfdt$2 = tfdt;
  33401. var parseSampleFlags$1 = function (flags) {
  33402. return {
  33403. isLeading: (flags[0] & 0x0c) >>> 2,
  33404. dependsOn: flags[0] & 0x03,
  33405. isDependedOn: (flags[1] & 0xc0) >>> 6,
  33406. hasRedundancy: (flags[1] & 0x30) >>> 4,
  33407. paddingValue: (flags[1] & 0x0e) >>> 1,
  33408. isNonSyncSample: flags[1] & 0x01,
  33409. degradationPriority: flags[2] << 8 | flags[3]
  33410. };
  33411. };
  33412. var parseSampleFlags_1 = parseSampleFlags$1;
  33413. var parseSampleFlags = parseSampleFlags_1;
  33414. var trun = function (data) {
  33415. var result = {
  33416. version: data[0],
  33417. flags: new Uint8Array(data.subarray(1, 4)),
  33418. samples: []
  33419. },
  33420. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  33421. // Flag interpretation
  33422. dataOffsetPresent = result.flags[2] & 0x01,
  33423. // compare with 2nd byte of 0x1
  33424. firstSampleFlagsPresent = result.flags[2] & 0x04,
  33425. // compare with 2nd byte of 0x4
  33426. sampleDurationPresent = result.flags[1] & 0x01,
  33427. // compare with 2nd byte of 0x100
  33428. sampleSizePresent = result.flags[1] & 0x02,
  33429. // compare with 2nd byte of 0x200
  33430. sampleFlagsPresent = result.flags[1] & 0x04,
  33431. // compare with 2nd byte of 0x400
  33432. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  33433. // compare with 2nd byte of 0x800
  33434. sampleCount = view.getUint32(4),
  33435. offset = 8,
  33436. sample;
  33437. if (dataOffsetPresent) {
  33438. // 32 bit signed integer
  33439. result.dataOffset = view.getInt32(offset);
  33440. offset += 4;
  33441. } // Overrides the flags for the first sample only. The order of
  33442. // optional values will be: duration, size, compositionTimeOffset
  33443. if (firstSampleFlagsPresent && sampleCount) {
  33444. sample = {
  33445. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  33446. };
  33447. offset += 4;
  33448. if (sampleDurationPresent) {
  33449. sample.duration = view.getUint32(offset);
  33450. offset += 4;
  33451. }
  33452. if (sampleSizePresent) {
  33453. sample.size = view.getUint32(offset);
  33454. offset += 4;
  33455. }
  33456. if (sampleCompositionTimeOffsetPresent) {
  33457. if (result.version === 1) {
  33458. sample.compositionTimeOffset = view.getInt32(offset);
  33459. } else {
  33460. sample.compositionTimeOffset = view.getUint32(offset);
  33461. }
  33462. offset += 4;
  33463. }
  33464. result.samples.push(sample);
  33465. sampleCount--;
  33466. }
  33467. while (sampleCount--) {
  33468. sample = {};
  33469. if (sampleDurationPresent) {
  33470. sample.duration = view.getUint32(offset);
  33471. offset += 4;
  33472. }
  33473. if (sampleSizePresent) {
  33474. sample.size = view.getUint32(offset);
  33475. offset += 4;
  33476. }
  33477. if (sampleFlagsPresent) {
  33478. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  33479. offset += 4;
  33480. }
  33481. if (sampleCompositionTimeOffsetPresent) {
  33482. if (result.version === 1) {
  33483. sample.compositionTimeOffset = view.getInt32(offset);
  33484. } else {
  33485. sample.compositionTimeOffset = view.getUint32(offset);
  33486. }
  33487. offset += 4;
  33488. }
  33489. result.samples.push(sample);
  33490. }
  33491. return result;
  33492. };
  33493. var parseTrun$2 = trun;
  33494. var tfhd = function (data) {
  33495. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  33496. result = {
  33497. version: data[0],
  33498. flags: new Uint8Array(data.subarray(1, 4)),
  33499. trackId: view.getUint32(4)
  33500. },
  33501. baseDataOffsetPresent = result.flags[2] & 0x01,
  33502. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  33503. defaultSampleDurationPresent = result.flags[2] & 0x08,
  33504. defaultSampleSizePresent = result.flags[2] & 0x10,
  33505. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  33506. durationIsEmpty = result.flags[0] & 0x010000,
  33507. defaultBaseIsMoof = result.flags[0] & 0x020000,
  33508. i;
  33509. i = 8;
  33510. if (baseDataOffsetPresent) {
  33511. i += 4; // truncate top 4 bytes
  33512. // FIXME: should we read the full 64 bits?
  33513. result.baseDataOffset = view.getUint32(12);
  33514. i += 4;
  33515. }
  33516. if (sampleDescriptionIndexPresent) {
  33517. result.sampleDescriptionIndex = view.getUint32(i);
  33518. i += 4;
  33519. }
  33520. if (defaultSampleDurationPresent) {
  33521. result.defaultSampleDuration = view.getUint32(i);
  33522. i += 4;
  33523. }
  33524. if (defaultSampleSizePresent) {
  33525. result.defaultSampleSize = view.getUint32(i);
  33526. i += 4;
  33527. }
  33528. if (defaultSampleFlagsPresent) {
  33529. result.defaultSampleFlags = view.getUint32(i);
  33530. }
  33531. if (durationIsEmpty) {
  33532. result.durationIsEmpty = true;
  33533. }
  33534. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  33535. result.baseDataOffsetIsMoof = true;
  33536. }
  33537. return result;
  33538. };
  33539. var parseTfhd$2 = tfhd;
  33540. var win;
  33541. if (typeof window !== "undefined") {
  33542. win = window;
  33543. } else if (typeof commonjsGlobal !== "undefined") {
  33544. win = commonjsGlobal;
  33545. } else if (typeof self !== "undefined") {
  33546. win = self;
  33547. } else {
  33548. win = {};
  33549. }
  33550. var window_1 = win;
  33551. /**
  33552. * mux.js
  33553. *
  33554. * Copyright (c) Brightcove
  33555. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  33556. *
  33557. * Reads in-band CEA-708 captions out of FMP4 segments.
  33558. * @see https://en.wikipedia.org/wiki/CEA-708
  33559. */
  33560. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  33561. var CaptionStream = captionStream.CaptionStream;
  33562. var findBox$1 = findBox_1;
  33563. var parseTfdt$1 = parseTfdt$2;
  33564. var parseTrun$1 = parseTrun$2;
  33565. var parseTfhd$1 = parseTfhd$2;
  33566. var window$2 = window_1;
  33567. /**
  33568. * Maps an offset in the mdat to a sample based on the the size of the samples.
  33569. * Assumes that `parseSamples` has been called first.
  33570. *
  33571. * @param {Number} offset - The offset into the mdat
  33572. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  33573. * @return {?Object} The matching sample, or null if no match was found.
  33574. *
  33575. * @see ISO-BMFF-12/2015, Section 8.8.8
  33576. **/
  33577. var mapToSample = function (offset, samples) {
  33578. var approximateOffset = offset;
  33579. for (var i = 0; i < samples.length; i++) {
  33580. var sample = samples[i];
  33581. if (approximateOffset < sample.size) {
  33582. return sample;
  33583. }
  33584. approximateOffset -= sample.size;
  33585. }
  33586. return null;
  33587. };
  33588. /**
  33589. * Finds SEI nal units contained in a Media Data Box.
  33590. * Assumes that `parseSamples` has been called first.
  33591. *
  33592. * @param {Uint8Array} avcStream - The bytes of the mdat
  33593. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  33594. * @param {Number} trackId - The trackId of this video track
  33595. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  33596. * The contents of the seiNal should match what is expected by
  33597. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  33598. *
  33599. * @see ISO-BMFF-12/2015, Section 8.1.1
  33600. * @see Rec. ITU-T H.264, 7.3.2.3.1
  33601. **/
  33602. var findSeiNals = function (avcStream, samples, trackId) {
  33603. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  33604. result = {
  33605. logs: [],
  33606. seiNals: []
  33607. },
  33608. seiNal,
  33609. i,
  33610. length,
  33611. lastMatchedSample;
  33612. for (i = 0; i + 4 < avcStream.length; i += length) {
  33613. length = avcView.getUint32(i);
  33614. i += 4; // Bail if this doesn't appear to be an H264 stream
  33615. if (length <= 0) {
  33616. continue;
  33617. }
  33618. switch (avcStream[i] & 0x1F) {
  33619. case 0x06:
  33620. var data = avcStream.subarray(i + 1, i + 1 + length);
  33621. var matchingSample = mapToSample(i, samples);
  33622. seiNal = {
  33623. nalUnitType: 'sei_rbsp',
  33624. size: length,
  33625. data: data,
  33626. escapedRBSP: discardEmulationPreventionBytes(data),
  33627. trackId: trackId
  33628. };
  33629. if (matchingSample) {
  33630. seiNal.pts = matchingSample.pts;
  33631. seiNal.dts = matchingSample.dts;
  33632. lastMatchedSample = matchingSample;
  33633. } else if (lastMatchedSample) {
  33634. // If a matching sample cannot be found, use the last
  33635. // sample's values as they should be as close as possible
  33636. seiNal.pts = lastMatchedSample.pts;
  33637. seiNal.dts = lastMatchedSample.dts;
  33638. } else {
  33639. result.logs.push({
  33640. level: 'warn',
  33641. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  33642. });
  33643. break;
  33644. }
  33645. result.seiNals.push(seiNal);
  33646. break;
  33647. }
  33648. }
  33649. return result;
  33650. };
  33651. /**
  33652. * Parses sample information out of Track Run Boxes and calculates
  33653. * the absolute presentation and decode timestamps of each sample.
  33654. *
  33655. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  33656. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  33657. @see ISO-BMFF-12/2015, Section 8.8.12
  33658. * @param {Object} tfhd - The parsed Track Fragment Header
  33659. * @see inspect.parseTfhd
  33660. * @return {Object[]} the parsed samples
  33661. *
  33662. * @see ISO-BMFF-12/2015, Section 8.8.8
  33663. **/
  33664. var parseSamples = function (truns, baseMediaDecodeTime, tfhd) {
  33665. var currentDts = baseMediaDecodeTime;
  33666. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  33667. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  33668. var trackId = tfhd.trackId;
  33669. var allSamples = [];
  33670. truns.forEach(function (trun) {
  33671. // Note: We currently do not parse the sample table as well
  33672. // as the trun. It's possible some sources will require this.
  33673. // moov > trak > mdia > minf > stbl
  33674. var trackRun = parseTrun$1(trun);
  33675. var samples = trackRun.samples;
  33676. samples.forEach(function (sample) {
  33677. if (sample.duration === undefined) {
  33678. sample.duration = defaultSampleDuration;
  33679. }
  33680. if (sample.size === undefined) {
  33681. sample.size = defaultSampleSize;
  33682. }
  33683. sample.trackId = trackId;
  33684. sample.dts = currentDts;
  33685. if (sample.compositionTimeOffset === undefined) {
  33686. sample.compositionTimeOffset = 0;
  33687. }
  33688. if (typeof currentDts === 'bigint') {
  33689. sample.pts = currentDts + window$2.BigInt(sample.compositionTimeOffset);
  33690. currentDts += window$2.BigInt(sample.duration);
  33691. } else {
  33692. sample.pts = currentDts + sample.compositionTimeOffset;
  33693. currentDts += sample.duration;
  33694. }
  33695. });
  33696. allSamples = allSamples.concat(samples);
  33697. });
  33698. return allSamples;
  33699. };
  33700. /**
  33701. * Parses out caption nals from an FMP4 segment's video tracks.
  33702. *
  33703. * @param {Uint8Array} segment - The bytes of a single segment
  33704. * @param {Number} videoTrackId - The trackId of a video track in the segment
  33705. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  33706. * a list of seiNals found in that track
  33707. **/
  33708. var parseCaptionNals = function (segment, videoTrackId) {
  33709. // To get the samples
  33710. var trafs = findBox$1(segment, ['moof', 'traf']); // To get SEI NAL units
  33711. var mdats = findBox$1(segment, ['mdat']);
  33712. var captionNals = {};
  33713. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  33714. mdats.forEach(function (mdat, index) {
  33715. var matchingTraf = trafs[index];
  33716. mdatTrafPairs.push({
  33717. mdat: mdat,
  33718. traf: matchingTraf
  33719. });
  33720. });
  33721. mdatTrafPairs.forEach(function (pair) {
  33722. var mdat = pair.mdat;
  33723. var traf = pair.traf;
  33724. var tfhd = findBox$1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  33725. var headerInfo = parseTfhd$1(tfhd[0]);
  33726. var trackId = headerInfo.trackId;
  33727. var tfdt = findBox$1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  33728. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt$1(tfdt[0]).baseMediaDecodeTime : 0;
  33729. var truns = findBox$1(traf, ['trun']);
  33730. var samples;
  33731. var result; // Only parse video data for the chosen video track
  33732. if (videoTrackId === trackId && truns.length > 0) {
  33733. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  33734. result = findSeiNals(mdat, samples, trackId);
  33735. if (!captionNals[trackId]) {
  33736. captionNals[trackId] = {
  33737. seiNals: [],
  33738. logs: []
  33739. };
  33740. }
  33741. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  33742. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  33743. }
  33744. });
  33745. return captionNals;
  33746. };
  33747. /**
  33748. * Parses out inband captions from an MP4 container and returns
  33749. * caption objects that can be used by WebVTT and the TextTrack API.
  33750. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  33751. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  33752. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  33753. *
  33754. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  33755. * @param {Number} trackId - The id of the video track to parse
  33756. * @param {Number} timescale - The timescale for the video track from the init segment
  33757. *
  33758. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  33759. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  33760. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  33761. * @return {String} parsedCaptions[].text - The visible content of the caption
  33762. **/
  33763. var parseEmbeddedCaptions = function (segment, trackId, timescale) {
  33764. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  33765. if (trackId === null) {
  33766. return null;
  33767. }
  33768. captionNals = parseCaptionNals(segment, trackId);
  33769. var trackNals = captionNals[trackId] || {};
  33770. return {
  33771. seiNals: trackNals.seiNals,
  33772. logs: trackNals.logs,
  33773. timescale: timescale
  33774. };
  33775. };
  33776. /**
  33777. * Converts SEI NALUs into captions that can be used by video.js
  33778. **/
  33779. var CaptionParser = function () {
  33780. var isInitialized = false;
  33781. var captionStream; // Stores segments seen before trackId and timescale are set
  33782. var segmentCache; // Stores video track ID of the track being parsed
  33783. var trackId; // Stores the timescale of the track being parsed
  33784. var timescale; // Stores captions parsed so far
  33785. var parsedCaptions; // Stores whether we are receiving partial data or not
  33786. var parsingPartial;
  33787. /**
  33788. * A method to indicate whether a CaptionParser has been initalized
  33789. * @returns {Boolean}
  33790. **/
  33791. this.isInitialized = function () {
  33792. return isInitialized;
  33793. };
  33794. /**
  33795. * Initializes the underlying CaptionStream, SEI NAL parsing
  33796. * and management, and caption collection
  33797. **/
  33798. this.init = function (options) {
  33799. captionStream = new CaptionStream();
  33800. isInitialized = true;
  33801. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  33802. captionStream.on('data', function (event) {
  33803. // Convert to seconds in the source's timescale
  33804. event.startTime = event.startPts / timescale;
  33805. event.endTime = event.endPts / timescale;
  33806. parsedCaptions.captions.push(event);
  33807. parsedCaptions.captionStreams[event.stream] = true;
  33808. });
  33809. captionStream.on('log', function (log) {
  33810. parsedCaptions.logs.push(log);
  33811. });
  33812. };
  33813. /**
  33814. * Determines if a new video track will be selected
  33815. * or if the timescale changed
  33816. * @return {Boolean}
  33817. **/
  33818. this.isNewInit = function (videoTrackIds, timescales) {
  33819. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  33820. return false;
  33821. }
  33822. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  33823. };
  33824. /**
  33825. * Parses out SEI captions and interacts with underlying
  33826. * CaptionStream to return dispatched captions
  33827. *
  33828. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  33829. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  33830. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  33831. * @see parseEmbeddedCaptions
  33832. * @see m2ts/caption-stream.js
  33833. **/
  33834. this.parse = function (segment, videoTrackIds, timescales) {
  33835. var parsedData;
  33836. if (!this.isInitialized()) {
  33837. return null; // This is not likely to be a video segment
  33838. } else if (!videoTrackIds || !timescales) {
  33839. return null;
  33840. } else if (this.isNewInit(videoTrackIds, timescales)) {
  33841. // Use the first video track only as there is no
  33842. // mechanism to switch to other video tracks
  33843. trackId = videoTrackIds[0];
  33844. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  33845. // data until we have one.
  33846. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  33847. } else if (trackId === null || !timescale) {
  33848. segmentCache.push(segment);
  33849. return null;
  33850. } // Now that a timescale and trackId is set, parse cached segments
  33851. while (segmentCache.length > 0) {
  33852. var cachedSegment = segmentCache.shift();
  33853. this.parse(cachedSegment, videoTrackIds, timescales);
  33854. }
  33855. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  33856. if (parsedData && parsedData.logs) {
  33857. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  33858. }
  33859. if (parsedData === null || !parsedData.seiNals) {
  33860. if (parsedCaptions.logs.length) {
  33861. return {
  33862. logs: parsedCaptions.logs,
  33863. captions: [],
  33864. captionStreams: []
  33865. };
  33866. }
  33867. return null;
  33868. }
  33869. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  33870. this.flushStream();
  33871. return parsedCaptions;
  33872. };
  33873. /**
  33874. * Pushes SEI NALUs onto CaptionStream
  33875. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  33876. * Assumes that `parseCaptionNals` has been called first
  33877. * @see m2ts/caption-stream.js
  33878. **/
  33879. this.pushNals = function (nals) {
  33880. if (!this.isInitialized() || !nals || nals.length === 0) {
  33881. return null;
  33882. }
  33883. nals.forEach(function (nal) {
  33884. captionStream.push(nal);
  33885. });
  33886. };
  33887. /**
  33888. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  33889. * @see m2ts/caption-stream.js
  33890. **/
  33891. this.flushStream = function () {
  33892. if (!this.isInitialized()) {
  33893. return null;
  33894. }
  33895. if (!parsingPartial) {
  33896. captionStream.flush();
  33897. } else {
  33898. captionStream.partialFlush();
  33899. }
  33900. };
  33901. /**
  33902. * Reset caption buckets for new data
  33903. **/
  33904. this.clearParsedCaptions = function () {
  33905. parsedCaptions.captions = [];
  33906. parsedCaptions.captionStreams = {};
  33907. parsedCaptions.logs = [];
  33908. };
  33909. /**
  33910. * Resets underlying CaptionStream
  33911. * @see m2ts/caption-stream.js
  33912. **/
  33913. this.resetCaptionStream = function () {
  33914. if (!this.isInitialized()) {
  33915. return null;
  33916. }
  33917. captionStream.reset();
  33918. };
  33919. /**
  33920. * Convenience method to clear all captions flushed from the
  33921. * CaptionStream and still being parsed
  33922. * @see m2ts/caption-stream.js
  33923. **/
  33924. this.clearAllCaptions = function () {
  33925. this.clearParsedCaptions();
  33926. this.resetCaptionStream();
  33927. };
  33928. /**
  33929. * Reset caption parser
  33930. **/
  33931. this.reset = function () {
  33932. segmentCache = [];
  33933. trackId = null;
  33934. timescale = null;
  33935. if (!parsedCaptions) {
  33936. parsedCaptions = {
  33937. captions: [],
  33938. // CC1, CC2, CC3, CC4
  33939. captionStreams: {},
  33940. logs: []
  33941. };
  33942. } else {
  33943. this.clearParsedCaptions();
  33944. }
  33945. this.resetCaptionStream();
  33946. };
  33947. this.reset();
  33948. };
  33949. var captionParser = CaptionParser;
  33950. /**
  33951. * Returns the first string in the data array ending with a null char '\0'
  33952. * @param {UInt8} data
  33953. * @returns the string with the null char
  33954. */
  33955. var uint8ToCString$1 = function (data) {
  33956. var index = 0;
  33957. var curChar = String.fromCharCode(data[index]);
  33958. var retString = '';
  33959. while (curChar !== '\0') {
  33960. retString += curChar;
  33961. index++;
  33962. curChar = String.fromCharCode(data[index]);
  33963. } // Add nullChar
  33964. retString += curChar;
  33965. return retString;
  33966. };
  33967. var string = {
  33968. uint8ToCString: uint8ToCString$1
  33969. };
  33970. var uint8ToCString = string.uint8ToCString;
  33971. var getUint64$1 = numbers.getUint64;
  33972. /**
  33973. * Based on: ISO/IEC 23009 Section: 5.10.3.3
  33974. * References:
  33975. * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format
  33976. * https://aomediacodec.github.io/id3-emsg/
  33977. *
  33978. * Takes emsg box data as a uint8 array and returns a emsg box object
  33979. * @param {UInt8Array} boxData data from emsg box
  33980. * @returns A parsed emsg box object
  33981. */
  33982. var parseEmsgBox = function (boxData) {
  33983. // version + flags
  33984. var offset = 4;
  33985. var version = boxData[0];
  33986. var scheme_id_uri, value, timescale, presentation_time, presentation_time_delta, event_duration, id, message_data;
  33987. if (version === 0) {
  33988. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  33989. offset += scheme_id_uri.length;
  33990. value = uint8ToCString(boxData.subarray(offset));
  33991. offset += value.length;
  33992. var dv = new DataView(boxData.buffer);
  33993. timescale = dv.getUint32(offset);
  33994. offset += 4;
  33995. presentation_time_delta = dv.getUint32(offset);
  33996. offset += 4;
  33997. event_duration = dv.getUint32(offset);
  33998. offset += 4;
  33999. id = dv.getUint32(offset);
  34000. offset += 4;
  34001. } else if (version === 1) {
  34002. var dv = new DataView(boxData.buffer);
  34003. timescale = dv.getUint32(offset);
  34004. offset += 4;
  34005. presentation_time = getUint64$1(boxData.subarray(offset));
  34006. offset += 8;
  34007. event_duration = dv.getUint32(offset);
  34008. offset += 4;
  34009. id = dv.getUint32(offset);
  34010. offset += 4;
  34011. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  34012. offset += scheme_id_uri.length;
  34013. value = uint8ToCString(boxData.subarray(offset));
  34014. offset += value.length;
  34015. }
  34016. message_data = new Uint8Array(boxData.subarray(offset, boxData.byteLength));
  34017. var emsgBox = {
  34018. scheme_id_uri,
  34019. value,
  34020. // if timescale is undefined or 0 set to 1
  34021. timescale: timescale ? timescale : 1,
  34022. presentation_time,
  34023. presentation_time_delta,
  34024. event_duration,
  34025. id,
  34026. message_data
  34027. };
  34028. return isValidEmsgBox(version, emsgBox) ? emsgBox : undefined;
  34029. };
  34030. /**
  34031. * Scales a presentation time or time delta with an offset with a provided timescale
  34032. * @param {number} presentationTime
  34033. * @param {number} timescale
  34034. * @param {number} timeDelta
  34035. * @param {number} offset
  34036. * @returns the scaled time as a number
  34037. */
  34038. var scaleTime = function (presentationTime, timescale, timeDelta, offset) {
  34039. return presentationTime || presentationTime === 0 ? presentationTime / timescale : offset + timeDelta / timescale;
  34040. };
  34041. /**
  34042. * Checks the emsg box data for validity based on the version
  34043. * @param {number} version of the emsg box to validate
  34044. * @param {Object} emsg the emsg data to validate
  34045. * @returns if the box is valid as a boolean
  34046. */
  34047. var isValidEmsgBox = function (version, emsg) {
  34048. var hasScheme = emsg.scheme_id_uri !== '\0';
  34049. var isValidV0Box = version === 0 && isDefined(emsg.presentation_time_delta) && hasScheme;
  34050. var isValidV1Box = version === 1 && isDefined(emsg.presentation_time) && hasScheme; // Only valid versions of emsg are 0 and 1
  34051. return !(version > 1) && isValidV0Box || isValidV1Box;
  34052. }; // Utility function to check if an object is defined
  34053. var isDefined = function (data) {
  34054. return data !== undefined || data !== null;
  34055. };
  34056. var emsg$1 = {
  34057. parseEmsgBox: parseEmsgBox,
  34058. scaleTime: scaleTime
  34059. };
  34060. /**
  34061. * mux.js
  34062. *
  34063. * Copyright (c) Brightcove
  34064. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  34065. *
  34066. * Utilities to detect basic properties and metadata about MP4s.
  34067. */
  34068. var toUnsigned = bin.toUnsigned;
  34069. var toHexString = bin.toHexString;
  34070. var findBox = findBox_1;
  34071. var parseType$1 = parseType_1;
  34072. var emsg = emsg$1;
  34073. var parseTfhd = parseTfhd$2;
  34074. var parseTrun = parseTrun$2;
  34075. var parseTfdt = parseTfdt$2;
  34076. var getUint64 = numbers.getUint64;
  34077. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader, getEmsgID3;
  34078. var window$1 = window_1;
  34079. var parseId3Frames = parseId3.parseId3Frames;
  34080. /**
  34081. * Parses an MP4 initialization segment and extracts the timescale
  34082. * values for any declared tracks. Timescale values indicate the
  34083. * number of clock ticks per second to assume for time-based values
  34084. * elsewhere in the MP4.
  34085. *
  34086. * To determine the start time of an MP4, you need two pieces of
  34087. * information: the timescale unit and the earliest base media decode
  34088. * time. Multiple timescales can be specified within an MP4 but the
  34089. * base media decode time is always expressed in the timescale from
  34090. * the media header box for the track:
  34091. * ```
  34092. * moov > trak > mdia > mdhd.timescale
  34093. * ```
  34094. * @param init {Uint8Array} the bytes of the init segment
  34095. * @return {object} a hash of track ids to timescale values or null if
  34096. * the init segment is malformed.
  34097. */
  34098. timescale = function (init) {
  34099. var result = {},
  34100. traks = findBox(init, ['moov', 'trak']); // mdhd timescale
  34101. return traks.reduce(function (result, trak) {
  34102. var tkhd, version, index, id, mdhd;
  34103. tkhd = findBox(trak, ['tkhd'])[0];
  34104. if (!tkhd) {
  34105. return null;
  34106. }
  34107. version = tkhd[0];
  34108. index = version === 0 ? 12 : 20;
  34109. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  34110. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  34111. if (!mdhd) {
  34112. return null;
  34113. }
  34114. version = mdhd[0];
  34115. index = version === 0 ? 12 : 20;
  34116. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  34117. return result;
  34118. }, result);
  34119. };
  34120. /**
  34121. * Determine the base media decode start time, in seconds, for an MP4
  34122. * fragment. If multiple fragments are specified, the earliest time is
  34123. * returned.
  34124. *
  34125. * The base media decode time can be parsed from track fragment
  34126. * metadata:
  34127. * ```
  34128. * moof > traf > tfdt.baseMediaDecodeTime
  34129. * ```
  34130. * It requires the timescale value from the mdhd to interpret.
  34131. *
  34132. * @param timescale {object} a hash of track ids to timescale values.
  34133. * @return {number} the earliest base media decode start time for the
  34134. * fragment, in seconds
  34135. */
  34136. startTime = function (timescale, fragment) {
  34137. var trafs; // we need info from two childrend of each track fragment box
  34138. trafs = findBox(fragment, ['moof', 'traf']); // determine the start times for each track
  34139. var lowestTime = trafs.reduce(function (acc, traf) {
  34140. var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
  34141. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  34142. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  34143. var tfdt = findBox(traf, ['tfdt'])[0];
  34144. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  34145. var baseTime; // version 1 is 64 bit
  34146. if (tfdt[0] === 1) {
  34147. baseTime = getUint64(tfdt.subarray(4, 12));
  34148. } else {
  34149. baseTime = dv.getUint32(4);
  34150. } // convert base time to seconds if it is a valid number.
  34151. let seconds;
  34152. if (typeof baseTime === 'bigint') {
  34153. seconds = baseTime / window$1.BigInt(scale);
  34154. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  34155. seconds = baseTime / scale;
  34156. }
  34157. if (seconds < Number.MAX_SAFE_INTEGER) {
  34158. seconds = Number(seconds);
  34159. }
  34160. if (seconds < acc) {
  34161. acc = seconds;
  34162. }
  34163. return acc;
  34164. }, Infinity);
  34165. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  34166. };
  34167. /**
  34168. * Determine the composition start, in seconds, for an MP4
  34169. * fragment.
  34170. *
  34171. * The composition start time of a fragment can be calculated using the base
  34172. * media decode time, composition time offset, and timescale, as follows:
  34173. *
  34174. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  34175. *
  34176. * All of the aforementioned information is contained within a media fragment's
  34177. * `traf` box, except for timescale info, which comes from the initialization
  34178. * segment, so a track id (also contained within a `traf`) is also necessary to
  34179. * associate it with a timescale
  34180. *
  34181. *
  34182. * @param timescales {object} - a hash of track ids to timescale values.
  34183. * @param fragment {Unit8Array} - the bytes of a media segment
  34184. * @return {number} the composition start time for the fragment, in seconds
  34185. **/
  34186. compositionStartTime = function (timescales, fragment) {
  34187. var trafBoxes = findBox(fragment, ['moof', 'traf']);
  34188. var baseMediaDecodeTime = 0;
  34189. var compositionTimeOffset = 0;
  34190. var trackId;
  34191. if (trafBoxes && trafBoxes.length) {
  34192. // The spec states that track run samples contained within a `traf` box are contiguous, but
  34193. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  34194. // We will assume that they are, so we only need the first to calculate start time.
  34195. var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
  34196. var trun = findBox(trafBoxes[0], ['trun'])[0];
  34197. var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];
  34198. if (tfhd) {
  34199. var parsedTfhd = parseTfhd(tfhd);
  34200. trackId = parsedTfhd.trackId;
  34201. }
  34202. if (tfdt) {
  34203. var parsedTfdt = parseTfdt(tfdt);
  34204. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  34205. }
  34206. if (trun) {
  34207. var parsedTrun = parseTrun(trun);
  34208. if (parsedTrun.samples && parsedTrun.samples.length) {
  34209. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  34210. }
  34211. }
  34212. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  34213. // specified.
  34214. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  34215. if (typeof baseMediaDecodeTime === 'bigint') {
  34216. compositionTimeOffset = window$1.BigInt(compositionTimeOffset);
  34217. timescale = window$1.BigInt(timescale);
  34218. }
  34219. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  34220. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  34221. result = Number(result);
  34222. }
  34223. return result;
  34224. };
  34225. /**
  34226. * Find the trackIds of the video tracks in this source.
  34227. * Found by parsing the Handler Reference and Track Header Boxes:
  34228. * moov > trak > mdia > hdlr
  34229. * moov > trak > tkhd
  34230. *
  34231. * @param {Uint8Array} init - The bytes of the init segment for this source
  34232. * @return {Number[]} A list of trackIds
  34233. *
  34234. * @see ISO-BMFF-12/2015, Section 8.4.3
  34235. **/
  34236. getVideoTrackIds = function (init) {
  34237. var traks = findBox(init, ['moov', 'trak']);
  34238. var videoTrackIds = [];
  34239. traks.forEach(function (trak) {
  34240. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  34241. var tkhds = findBox(trak, ['tkhd']);
  34242. hdlrs.forEach(function (hdlr, index) {
  34243. var handlerType = parseType$1(hdlr.subarray(8, 12));
  34244. var tkhd = tkhds[index];
  34245. var view;
  34246. var version;
  34247. var trackId;
  34248. if (handlerType === 'vide') {
  34249. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  34250. version = view.getUint8(0);
  34251. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  34252. videoTrackIds.push(trackId);
  34253. }
  34254. });
  34255. });
  34256. return videoTrackIds;
  34257. };
  34258. getTimescaleFromMediaHeader = function (mdhd) {
  34259. // mdhd is a FullBox, meaning it will have its own version as the first byte
  34260. var version = mdhd[0];
  34261. var index = version === 0 ? 12 : 20;
  34262. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  34263. };
  34264. /**
  34265. * Get all the video, audio, and hint tracks from a non fragmented
  34266. * mp4 segment
  34267. */
  34268. getTracks = function (init) {
  34269. var traks = findBox(init, ['moov', 'trak']);
  34270. var tracks = [];
  34271. traks.forEach(function (trak) {
  34272. var track = {};
  34273. var tkhd = findBox(trak, ['tkhd'])[0];
  34274. var view, tkhdVersion; // id
  34275. if (tkhd) {
  34276. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  34277. tkhdVersion = view.getUint8(0);
  34278. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  34279. }
  34280. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0]; // type
  34281. if (hdlr) {
  34282. var type = parseType$1(hdlr.subarray(8, 12));
  34283. if (type === 'vide') {
  34284. track.type = 'video';
  34285. } else if (type === 'soun') {
  34286. track.type = 'audio';
  34287. } else {
  34288. track.type = type;
  34289. }
  34290. } // codec
  34291. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  34292. if (stsd) {
  34293. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  34294. track.codec = parseType$1(sampleDescriptions.subarray(4, 8));
  34295. var codecBox = findBox(sampleDescriptions, [track.codec])[0];
  34296. var codecConfig, codecConfigType;
  34297. if (codecBox) {
  34298. // https://tools.ietf.org/html/rfc6381#section-3.3
  34299. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  34300. // we don't need anything but the "config" parameter of the
  34301. // avc1 codecBox
  34302. codecConfig = codecBox.subarray(78);
  34303. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  34304. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  34305. track.codec += '.'; // left padded with zeroes for single digit hex
  34306. // profile idc
  34307. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  34308. track.codec += toHexString(codecConfig[10]); // level idc
  34309. track.codec += toHexString(codecConfig[11]);
  34310. } else {
  34311. // TODO: show a warning that we couldn't parse the codec
  34312. // and are using the default
  34313. track.codec = 'avc1.4d400d';
  34314. }
  34315. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  34316. // we do not need anything but the streamDescriptor of the mp4a codecBox
  34317. codecConfig = codecBox.subarray(28);
  34318. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  34319. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  34320. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  34321. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  34322. } else {
  34323. // TODO: show a warning that we couldn't parse the codec
  34324. // and are using the default
  34325. track.codec = 'mp4a.40.2';
  34326. }
  34327. } else {
  34328. // flac, opus, etc
  34329. track.codec = track.codec.toLowerCase();
  34330. }
  34331. }
  34332. }
  34333. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  34334. if (mdhd) {
  34335. track.timescale = getTimescaleFromMediaHeader(mdhd);
  34336. }
  34337. tracks.push(track);
  34338. });
  34339. return tracks;
  34340. };
  34341. /**
  34342. * Returns an array of emsg ID3 data from the provided segmentData.
  34343. * An offset can also be provided as the Latest Arrival Time to calculate
  34344. * the Event Start Time of v0 EMSG boxes.
  34345. * See: https://dashif-documents.azurewebsites.net/Events/master/event.html#Inband-event-timing
  34346. *
  34347. * @param {Uint8Array} segmentData the segment byte array.
  34348. * @param {number} offset the segment start time or Latest Arrival Time,
  34349. * @return {Object[]} an array of ID3 parsed from EMSG boxes
  34350. */
  34351. getEmsgID3 = function (segmentData, offset = 0) {
  34352. var emsgBoxes = findBox(segmentData, ['emsg']);
  34353. return emsgBoxes.map(data => {
  34354. var parsedBox = emsg.parseEmsgBox(new Uint8Array(data));
  34355. var parsedId3Frames = parseId3Frames(parsedBox.message_data);
  34356. return {
  34357. cueTime: emsg.scaleTime(parsedBox.presentation_time, parsedBox.timescale, parsedBox.presentation_time_delta, offset),
  34358. duration: emsg.scaleTime(parsedBox.event_duration, parsedBox.timescale),
  34359. frames: parsedId3Frames
  34360. };
  34361. });
  34362. };
  34363. var probe$2 = {
  34364. // export mp4 inspector's findBox and parseType for backwards compatibility
  34365. findBox: findBox,
  34366. parseType: parseType$1,
  34367. timescale: timescale,
  34368. startTime: startTime,
  34369. compositionStartTime: compositionStartTime,
  34370. videoTrackIds: getVideoTrackIds,
  34371. tracks: getTracks,
  34372. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader,
  34373. getEmsgID3: getEmsgID3
  34374. };
  34375. /**
  34376. * mux.js
  34377. *
  34378. * Copyright (c) Brightcove
  34379. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  34380. *
  34381. * Utilities to detect basic properties and metadata about TS Segments.
  34382. */
  34383. var StreamTypes$1 = streamTypes;
  34384. var parsePid = function (packet) {
  34385. var pid = packet[1] & 0x1f;
  34386. pid <<= 8;
  34387. pid |= packet[2];
  34388. return pid;
  34389. };
  34390. var parsePayloadUnitStartIndicator = function (packet) {
  34391. return !!(packet[1] & 0x40);
  34392. };
  34393. var parseAdaptionField = function (packet) {
  34394. var offset = 0; // if an adaption field is present, its length is specified by the
  34395. // fifth byte of the TS packet header. The adaptation field is
  34396. // used to add stuffing to PES packets that don't fill a complete
  34397. // TS packet, and to specify some forms of timing and control data
  34398. // that we do not currently use.
  34399. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  34400. offset += packet[4] + 1;
  34401. }
  34402. return offset;
  34403. };
  34404. var parseType = function (packet, pmtPid) {
  34405. var pid = parsePid(packet);
  34406. if (pid === 0) {
  34407. return 'pat';
  34408. } else if (pid === pmtPid) {
  34409. return 'pmt';
  34410. } else if (pmtPid) {
  34411. return 'pes';
  34412. }
  34413. return null;
  34414. };
  34415. var parsePat = function (packet) {
  34416. var pusi = parsePayloadUnitStartIndicator(packet);
  34417. var offset = 4 + parseAdaptionField(packet);
  34418. if (pusi) {
  34419. offset += packet[offset] + 1;
  34420. }
  34421. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  34422. };
  34423. var parsePmt = function (packet) {
  34424. var programMapTable = {};
  34425. var pusi = parsePayloadUnitStartIndicator(packet);
  34426. var payloadOffset = 4 + parseAdaptionField(packet);
  34427. if (pusi) {
  34428. payloadOffset += packet[payloadOffset] + 1;
  34429. } // PMTs can be sent ahead of the time when they should actually
  34430. // take effect. We don't believe this should ever be the case
  34431. // for HLS but we'll ignore "forward" PMT declarations if we see
  34432. // them. Future PMT declarations have the current_next_indicator
  34433. // set to zero.
  34434. if (!(packet[payloadOffset + 5] & 0x01)) {
  34435. return;
  34436. }
  34437. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  34438. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  34439. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  34440. // long the program info descriptors are
  34441. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  34442. var offset = 12 + programInfoLength;
  34443. while (offset < tableEnd) {
  34444. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  34445. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  34446. // skip past the elementary stream descriptors, if present
  34447. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  34448. }
  34449. return programMapTable;
  34450. };
  34451. var parsePesType = function (packet, programMapTable) {
  34452. var pid = parsePid(packet);
  34453. var type = programMapTable[pid];
  34454. switch (type) {
  34455. case StreamTypes$1.H264_STREAM_TYPE:
  34456. return 'video';
  34457. case StreamTypes$1.ADTS_STREAM_TYPE:
  34458. return 'audio';
  34459. case StreamTypes$1.METADATA_STREAM_TYPE:
  34460. return 'timed-metadata';
  34461. default:
  34462. return null;
  34463. }
  34464. };
  34465. var parsePesTime = function (packet) {
  34466. var pusi = parsePayloadUnitStartIndicator(packet);
  34467. if (!pusi) {
  34468. return null;
  34469. }
  34470. var offset = 4 + parseAdaptionField(packet);
  34471. if (offset >= packet.byteLength) {
  34472. // From the H 222.0 MPEG-TS spec
  34473. // "For transport stream packets carrying PES packets, stuffing is needed when there
  34474. // is insufficient PES packet data to completely fill the transport stream packet
  34475. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  34476. // the sum of the lengths of the data elements in it, so that the payload bytes
  34477. // remaining after the adaptation field exactly accommodates the available PES packet
  34478. // data."
  34479. //
  34480. // If the offset is >= the length of the packet, then the packet contains no data
  34481. // and instead is just adaption field stuffing bytes
  34482. return null;
  34483. }
  34484. var pes = null;
  34485. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  34486. // and a DTS value. Determine what combination of values is
  34487. // available to work with.
  34488. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  34489. // performs all bitwise operations on 32-bit integers but javascript
  34490. // supports a much greater range (52-bits) of integer using standard
  34491. // mathematical operations.
  34492. // We construct a 31-bit value using bitwise operators over the 31
  34493. // most significant bits and then multiply by 4 (equal to a left-shift
  34494. // of 2) before we add the final 2 least significant bits of the
  34495. // timestamp (equal to an OR.)
  34496. if (ptsDtsFlags & 0xC0) {
  34497. pes = {}; // the PTS and DTS are not written out directly. For information
  34498. // on how they are encoded, see
  34499. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  34500. 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;
  34501. pes.pts *= 4; // Left shift by 2
  34502. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  34503. pes.dts = pes.pts;
  34504. if (ptsDtsFlags & 0x40) {
  34505. 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;
  34506. pes.dts *= 4; // Left shift by 2
  34507. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  34508. }
  34509. }
  34510. return pes;
  34511. };
  34512. var parseNalUnitType = function (type) {
  34513. switch (type) {
  34514. case 0x05:
  34515. return 'slice_layer_without_partitioning_rbsp_idr';
  34516. case 0x06:
  34517. return 'sei_rbsp';
  34518. case 0x07:
  34519. return 'seq_parameter_set_rbsp';
  34520. case 0x08:
  34521. return 'pic_parameter_set_rbsp';
  34522. case 0x09:
  34523. return 'access_unit_delimiter_rbsp';
  34524. default:
  34525. return null;
  34526. }
  34527. };
  34528. var videoPacketContainsKeyFrame = function (packet) {
  34529. var offset = 4 + parseAdaptionField(packet);
  34530. var frameBuffer = packet.subarray(offset);
  34531. var frameI = 0;
  34532. var frameSyncPoint = 0;
  34533. var foundKeyFrame = false;
  34534. var nalType; // advance the sync point to a NAL start, if necessary
  34535. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  34536. if (frameBuffer[frameSyncPoint + 2] === 1) {
  34537. // the sync point is properly aligned
  34538. frameI = frameSyncPoint + 5;
  34539. break;
  34540. }
  34541. }
  34542. while (frameI < frameBuffer.byteLength) {
  34543. // look at the current byte to determine if we've hit the end of
  34544. // a NAL unit boundary
  34545. switch (frameBuffer[frameI]) {
  34546. case 0:
  34547. // skip past non-sync sequences
  34548. if (frameBuffer[frameI - 1] !== 0) {
  34549. frameI += 2;
  34550. break;
  34551. } else if (frameBuffer[frameI - 2] !== 0) {
  34552. frameI++;
  34553. break;
  34554. }
  34555. if (frameSyncPoint + 3 !== frameI - 2) {
  34556. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  34557. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  34558. foundKeyFrame = true;
  34559. }
  34560. } // drop trailing zeroes
  34561. do {
  34562. frameI++;
  34563. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  34564. frameSyncPoint = frameI - 2;
  34565. frameI += 3;
  34566. break;
  34567. case 1:
  34568. // skip past non-sync sequences
  34569. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  34570. frameI += 3;
  34571. break;
  34572. }
  34573. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  34574. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  34575. foundKeyFrame = true;
  34576. }
  34577. frameSyncPoint = frameI - 2;
  34578. frameI += 3;
  34579. break;
  34580. default:
  34581. // the current byte isn't a one or zero, so it cannot be part
  34582. // of a sync sequence
  34583. frameI += 3;
  34584. break;
  34585. }
  34586. }
  34587. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  34588. frameI -= frameSyncPoint;
  34589. frameSyncPoint = 0; // parse the final nal
  34590. if (frameBuffer && frameBuffer.byteLength > 3) {
  34591. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  34592. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  34593. foundKeyFrame = true;
  34594. }
  34595. }
  34596. return foundKeyFrame;
  34597. };
  34598. var probe$1 = {
  34599. parseType: parseType,
  34600. parsePat: parsePat,
  34601. parsePmt: parsePmt,
  34602. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  34603. parsePesType: parsePesType,
  34604. parsePesTime: parsePesTime,
  34605. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  34606. };
  34607. /**
  34608. * mux.js
  34609. *
  34610. * Copyright (c) Brightcove
  34611. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  34612. *
  34613. * Parse mpeg2 transport stream packets to extract basic timing information
  34614. */
  34615. var StreamTypes = streamTypes;
  34616. var handleRollover = timestampRolloverStream.handleRollover;
  34617. var probe = {};
  34618. probe.ts = probe$1;
  34619. probe.aac = utils;
  34620. var ONE_SECOND_IN_TS = clock$2.ONE_SECOND_IN_TS;
  34621. var MP2T_PACKET_LENGTH = 188,
  34622. // bytes
  34623. SYNC_BYTE = 0x47;
  34624. /**
  34625. * walks through segment data looking for pat and pmt packets to parse out
  34626. * program map table information
  34627. */
  34628. var parsePsi_ = function (bytes, pmt) {
  34629. var startIndex = 0,
  34630. endIndex = MP2T_PACKET_LENGTH,
  34631. packet,
  34632. type;
  34633. while (endIndex < bytes.byteLength) {
  34634. // Look for a pair of start and end sync bytes in the data..
  34635. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  34636. // We found a packet
  34637. packet = bytes.subarray(startIndex, endIndex);
  34638. type = probe.ts.parseType(packet, pmt.pid);
  34639. switch (type) {
  34640. case 'pat':
  34641. pmt.pid = probe.ts.parsePat(packet);
  34642. break;
  34643. case 'pmt':
  34644. var table = probe.ts.parsePmt(packet);
  34645. pmt.table = pmt.table || {};
  34646. Object.keys(table).forEach(function (key) {
  34647. pmt.table[key] = table[key];
  34648. });
  34649. break;
  34650. }
  34651. startIndex += MP2T_PACKET_LENGTH;
  34652. endIndex += MP2T_PACKET_LENGTH;
  34653. continue;
  34654. } // If we get here, we have somehow become de-synchronized and we need to step
  34655. // forward one byte at a time until we find a pair of sync bytes that denote
  34656. // a packet
  34657. startIndex++;
  34658. endIndex++;
  34659. }
  34660. };
  34661. /**
  34662. * walks through the segment data from the start and end to get timing information
  34663. * for the first and last audio pes packets
  34664. */
  34665. var parseAudioPes_ = function (bytes, pmt, result) {
  34666. var startIndex = 0,
  34667. endIndex = MP2T_PACKET_LENGTH,
  34668. packet,
  34669. type,
  34670. pesType,
  34671. pusi,
  34672. parsed;
  34673. var endLoop = false; // Start walking from start of segment to get first audio packet
  34674. while (endIndex <= bytes.byteLength) {
  34675. // Look for a pair of start and end sync bytes in the data..
  34676. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  34677. // We found a packet
  34678. packet = bytes.subarray(startIndex, endIndex);
  34679. type = probe.ts.parseType(packet, pmt.pid);
  34680. switch (type) {
  34681. case 'pes':
  34682. pesType = probe.ts.parsePesType(packet, pmt.table);
  34683. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  34684. if (pesType === 'audio' && pusi) {
  34685. parsed = probe.ts.parsePesTime(packet);
  34686. if (parsed) {
  34687. parsed.type = 'audio';
  34688. result.audio.push(parsed);
  34689. endLoop = true;
  34690. }
  34691. }
  34692. break;
  34693. }
  34694. if (endLoop) {
  34695. break;
  34696. }
  34697. startIndex += MP2T_PACKET_LENGTH;
  34698. endIndex += MP2T_PACKET_LENGTH;
  34699. continue;
  34700. } // If we get here, we have somehow become de-synchronized and we need to step
  34701. // forward one byte at a time until we find a pair of sync bytes that denote
  34702. // a packet
  34703. startIndex++;
  34704. endIndex++;
  34705. } // Start walking from end of segment to get last audio packet
  34706. endIndex = bytes.byteLength;
  34707. startIndex = endIndex - MP2T_PACKET_LENGTH;
  34708. endLoop = false;
  34709. while (startIndex >= 0) {
  34710. // Look for a pair of start and end sync bytes in the data..
  34711. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  34712. // We found a packet
  34713. packet = bytes.subarray(startIndex, endIndex);
  34714. type = probe.ts.parseType(packet, pmt.pid);
  34715. switch (type) {
  34716. case 'pes':
  34717. pesType = probe.ts.parsePesType(packet, pmt.table);
  34718. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  34719. if (pesType === 'audio' && pusi) {
  34720. parsed = probe.ts.parsePesTime(packet);
  34721. if (parsed) {
  34722. parsed.type = 'audio';
  34723. result.audio.push(parsed);
  34724. endLoop = true;
  34725. }
  34726. }
  34727. break;
  34728. }
  34729. if (endLoop) {
  34730. break;
  34731. }
  34732. startIndex -= MP2T_PACKET_LENGTH;
  34733. endIndex -= MP2T_PACKET_LENGTH;
  34734. continue;
  34735. } // If we get here, we have somehow become de-synchronized and we need to step
  34736. // forward one byte at a time until we find a pair of sync bytes that denote
  34737. // a packet
  34738. startIndex--;
  34739. endIndex--;
  34740. }
  34741. };
  34742. /**
  34743. * walks through the segment data from the start and end to get timing information
  34744. * for the first and last video pes packets as well as timing information for the first
  34745. * key frame.
  34746. */
  34747. var parseVideoPes_ = function (bytes, pmt, result) {
  34748. var startIndex = 0,
  34749. endIndex = MP2T_PACKET_LENGTH,
  34750. packet,
  34751. type,
  34752. pesType,
  34753. pusi,
  34754. parsed,
  34755. frame,
  34756. i,
  34757. pes;
  34758. var endLoop = false;
  34759. var currentFrame = {
  34760. data: [],
  34761. size: 0
  34762. }; // Start walking from start of segment to get first video packet
  34763. while (endIndex < bytes.byteLength) {
  34764. // Look for a pair of start and end sync bytes in the data..
  34765. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  34766. // We found a packet
  34767. packet = bytes.subarray(startIndex, endIndex);
  34768. type = probe.ts.parseType(packet, pmt.pid);
  34769. switch (type) {
  34770. case 'pes':
  34771. pesType = probe.ts.parsePesType(packet, pmt.table);
  34772. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  34773. if (pesType === 'video') {
  34774. if (pusi && !endLoop) {
  34775. parsed = probe.ts.parsePesTime(packet);
  34776. if (parsed) {
  34777. parsed.type = 'video';
  34778. result.video.push(parsed);
  34779. endLoop = true;
  34780. }
  34781. }
  34782. if (!result.firstKeyFrame) {
  34783. if (pusi) {
  34784. if (currentFrame.size !== 0) {
  34785. frame = new Uint8Array(currentFrame.size);
  34786. i = 0;
  34787. while (currentFrame.data.length) {
  34788. pes = currentFrame.data.shift();
  34789. frame.set(pes, i);
  34790. i += pes.byteLength;
  34791. }
  34792. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  34793. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  34794. // the keyframe seems to work fine with HLS playback
  34795. // and definitely preferable to a crash with TypeError...
  34796. if (firstKeyFrame) {
  34797. result.firstKeyFrame = firstKeyFrame;
  34798. result.firstKeyFrame.type = 'video';
  34799. } else {
  34800. // eslint-disable-next-line
  34801. 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.');
  34802. }
  34803. }
  34804. currentFrame.size = 0;
  34805. }
  34806. }
  34807. currentFrame.data.push(packet);
  34808. currentFrame.size += packet.byteLength;
  34809. }
  34810. }
  34811. break;
  34812. }
  34813. if (endLoop && result.firstKeyFrame) {
  34814. break;
  34815. }
  34816. startIndex += MP2T_PACKET_LENGTH;
  34817. endIndex += MP2T_PACKET_LENGTH;
  34818. continue;
  34819. } // If we get here, we have somehow become de-synchronized and we need to step
  34820. // forward one byte at a time until we find a pair of sync bytes that denote
  34821. // a packet
  34822. startIndex++;
  34823. endIndex++;
  34824. } // Start walking from end of segment to get last video packet
  34825. endIndex = bytes.byteLength;
  34826. startIndex = endIndex - MP2T_PACKET_LENGTH;
  34827. endLoop = false;
  34828. while (startIndex >= 0) {
  34829. // Look for a pair of start and end sync bytes in the data..
  34830. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  34831. // We found a packet
  34832. packet = bytes.subarray(startIndex, endIndex);
  34833. type = probe.ts.parseType(packet, pmt.pid);
  34834. switch (type) {
  34835. case 'pes':
  34836. pesType = probe.ts.parsePesType(packet, pmt.table);
  34837. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  34838. if (pesType === 'video' && pusi) {
  34839. parsed = probe.ts.parsePesTime(packet);
  34840. if (parsed) {
  34841. parsed.type = 'video';
  34842. result.video.push(parsed);
  34843. endLoop = true;
  34844. }
  34845. }
  34846. break;
  34847. }
  34848. if (endLoop) {
  34849. break;
  34850. }
  34851. startIndex -= MP2T_PACKET_LENGTH;
  34852. endIndex -= MP2T_PACKET_LENGTH;
  34853. continue;
  34854. } // If we get here, we have somehow become de-synchronized and we need to step
  34855. // forward one byte at a time until we find a pair of sync bytes that denote
  34856. // a packet
  34857. startIndex--;
  34858. endIndex--;
  34859. }
  34860. };
  34861. /**
  34862. * Adjusts the timestamp information for the segment to account for
  34863. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  34864. */
  34865. var adjustTimestamp_ = function (segmentInfo, baseTimestamp) {
  34866. if (segmentInfo.audio && segmentInfo.audio.length) {
  34867. var audioBaseTimestamp = baseTimestamp;
  34868. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  34869. audioBaseTimestamp = segmentInfo.audio[0].dts;
  34870. }
  34871. segmentInfo.audio.forEach(function (info) {
  34872. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  34873. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  34874. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  34875. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  34876. });
  34877. }
  34878. if (segmentInfo.video && segmentInfo.video.length) {
  34879. var videoBaseTimestamp = baseTimestamp;
  34880. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  34881. videoBaseTimestamp = segmentInfo.video[0].dts;
  34882. }
  34883. segmentInfo.video.forEach(function (info) {
  34884. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  34885. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  34886. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  34887. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  34888. });
  34889. if (segmentInfo.firstKeyFrame) {
  34890. var frame = segmentInfo.firstKeyFrame;
  34891. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  34892. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  34893. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  34894. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  34895. }
  34896. }
  34897. };
  34898. /**
  34899. * inspects the aac data stream for start and end time information
  34900. */
  34901. var inspectAac_ = function (bytes) {
  34902. var endLoop = false,
  34903. audioCount = 0,
  34904. sampleRate = null,
  34905. timestamp = null,
  34906. frameSize = 0,
  34907. byteIndex = 0,
  34908. packet;
  34909. while (bytes.length - byteIndex >= 3) {
  34910. var type = probe.aac.parseType(bytes, byteIndex);
  34911. switch (type) {
  34912. case 'timed-metadata':
  34913. // Exit early because we don't have enough to parse
  34914. // the ID3 tag header
  34915. if (bytes.length - byteIndex < 10) {
  34916. endLoop = true;
  34917. break;
  34918. }
  34919. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  34920. // to emit a full packet
  34921. if (frameSize > bytes.length) {
  34922. endLoop = true;
  34923. break;
  34924. }
  34925. if (timestamp === null) {
  34926. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  34927. timestamp = probe.aac.parseAacTimestamp(packet);
  34928. }
  34929. byteIndex += frameSize;
  34930. break;
  34931. case 'audio':
  34932. // Exit early because we don't have enough to parse
  34933. // the ADTS frame header
  34934. if (bytes.length - byteIndex < 7) {
  34935. endLoop = true;
  34936. break;
  34937. }
  34938. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  34939. // to emit a full packet
  34940. if (frameSize > bytes.length) {
  34941. endLoop = true;
  34942. break;
  34943. }
  34944. if (sampleRate === null) {
  34945. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  34946. sampleRate = probe.aac.parseSampleRate(packet);
  34947. }
  34948. audioCount++;
  34949. byteIndex += frameSize;
  34950. break;
  34951. default:
  34952. byteIndex++;
  34953. break;
  34954. }
  34955. if (endLoop) {
  34956. return null;
  34957. }
  34958. }
  34959. if (sampleRate === null || timestamp === null) {
  34960. return null;
  34961. }
  34962. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  34963. var result = {
  34964. audio: [{
  34965. type: 'audio',
  34966. dts: timestamp,
  34967. pts: timestamp
  34968. }, {
  34969. type: 'audio',
  34970. dts: timestamp + audioCount * 1024 * audioTimescale,
  34971. pts: timestamp + audioCount * 1024 * audioTimescale
  34972. }]
  34973. };
  34974. return result;
  34975. };
  34976. /**
  34977. * inspects the transport stream segment data for start and end time information
  34978. * of the audio and video tracks (when present) as well as the first key frame's
  34979. * start time.
  34980. */
  34981. var inspectTs_ = function (bytes) {
  34982. var pmt = {
  34983. pid: null,
  34984. table: null
  34985. };
  34986. var result = {};
  34987. parsePsi_(bytes, pmt);
  34988. for (var pid in pmt.table) {
  34989. if (pmt.table.hasOwnProperty(pid)) {
  34990. var type = pmt.table[pid];
  34991. switch (type) {
  34992. case StreamTypes.H264_STREAM_TYPE:
  34993. result.video = [];
  34994. parseVideoPes_(bytes, pmt, result);
  34995. if (result.video.length === 0) {
  34996. delete result.video;
  34997. }
  34998. break;
  34999. case StreamTypes.ADTS_STREAM_TYPE:
  35000. result.audio = [];
  35001. parseAudioPes_(bytes, pmt, result);
  35002. if (result.audio.length === 0) {
  35003. delete result.audio;
  35004. }
  35005. break;
  35006. }
  35007. }
  35008. }
  35009. return result;
  35010. };
  35011. /**
  35012. * Inspects segment byte data and returns an object with start and end timing information
  35013. *
  35014. * @param {Uint8Array} bytes The segment byte data
  35015. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  35016. * timestamps for rollover. This value must be in 90khz clock.
  35017. * @return {Object} Object containing start and end frame timing info of segment.
  35018. */
  35019. var inspect = function (bytes, baseTimestamp) {
  35020. var isAacData = probe.aac.isLikelyAacData(bytes);
  35021. var result;
  35022. if (isAacData) {
  35023. result = inspectAac_(bytes);
  35024. } else {
  35025. result = inspectTs_(bytes);
  35026. }
  35027. if (!result || !result.audio && !result.video) {
  35028. return null;
  35029. }
  35030. adjustTimestamp_(result, baseTimestamp);
  35031. return result;
  35032. };
  35033. var tsInspector = {
  35034. inspect: inspect,
  35035. parseAudioPes_: parseAudioPes_
  35036. };
  35037. /* global self */
  35038. /**
  35039. * Re-emits transmuxer events by converting them into messages to the
  35040. * world outside the worker.
  35041. *
  35042. * @param {Object} transmuxer the transmuxer to wire events on
  35043. * @private
  35044. */
  35045. const wireTransmuxerEvents = function (self, transmuxer) {
  35046. transmuxer.on('data', function (segment) {
  35047. // transfer ownership of the underlying ArrayBuffer
  35048. // instead of doing a copy to save memory
  35049. // ArrayBuffers are transferable but generic TypedArrays are not
  35050. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  35051. const initArray = segment.initSegment;
  35052. segment.initSegment = {
  35053. data: initArray.buffer,
  35054. byteOffset: initArray.byteOffset,
  35055. byteLength: initArray.byteLength
  35056. };
  35057. const typedArray = segment.data;
  35058. segment.data = typedArray.buffer;
  35059. self.postMessage({
  35060. action: 'data',
  35061. segment,
  35062. byteOffset: typedArray.byteOffset,
  35063. byteLength: typedArray.byteLength
  35064. }, [segment.data]);
  35065. });
  35066. transmuxer.on('done', function (data) {
  35067. self.postMessage({
  35068. action: 'done'
  35069. });
  35070. });
  35071. transmuxer.on('gopInfo', function (gopInfo) {
  35072. self.postMessage({
  35073. action: 'gopInfo',
  35074. gopInfo
  35075. });
  35076. });
  35077. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  35078. const videoSegmentTimingInfo = {
  35079. start: {
  35080. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  35081. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  35082. },
  35083. end: {
  35084. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  35085. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  35086. },
  35087. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  35088. };
  35089. if (timingInfo.prependedContentDuration) {
  35090. videoSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  35091. }
  35092. self.postMessage({
  35093. action: 'videoSegmentTimingInfo',
  35094. videoSegmentTimingInfo
  35095. });
  35096. });
  35097. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  35098. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  35099. const audioSegmentTimingInfo = {
  35100. start: {
  35101. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  35102. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  35103. },
  35104. end: {
  35105. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  35106. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  35107. },
  35108. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  35109. };
  35110. if (timingInfo.prependedContentDuration) {
  35111. audioSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  35112. }
  35113. self.postMessage({
  35114. action: 'audioSegmentTimingInfo',
  35115. audioSegmentTimingInfo
  35116. });
  35117. });
  35118. transmuxer.on('id3Frame', function (id3Frame) {
  35119. self.postMessage({
  35120. action: 'id3Frame',
  35121. id3Frame
  35122. });
  35123. });
  35124. transmuxer.on('caption', function (caption) {
  35125. self.postMessage({
  35126. action: 'caption',
  35127. caption
  35128. });
  35129. });
  35130. transmuxer.on('trackinfo', function (trackInfo) {
  35131. self.postMessage({
  35132. action: 'trackinfo',
  35133. trackInfo
  35134. });
  35135. });
  35136. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  35137. // convert to video TS since we prioritize video time over audio
  35138. self.postMessage({
  35139. action: 'audioTimingInfo',
  35140. audioTimingInfo: {
  35141. start: clock$2.videoTsToSeconds(audioTimingInfo.start),
  35142. end: clock$2.videoTsToSeconds(audioTimingInfo.end)
  35143. }
  35144. });
  35145. });
  35146. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  35147. self.postMessage({
  35148. action: 'videoTimingInfo',
  35149. videoTimingInfo: {
  35150. start: clock$2.videoTsToSeconds(videoTimingInfo.start),
  35151. end: clock$2.videoTsToSeconds(videoTimingInfo.end)
  35152. }
  35153. });
  35154. });
  35155. transmuxer.on('log', function (log) {
  35156. self.postMessage({
  35157. action: 'log',
  35158. log
  35159. });
  35160. });
  35161. };
  35162. /**
  35163. * All incoming messages route through this hash. If no function exists
  35164. * to handle an incoming message, then we ignore the message.
  35165. *
  35166. * @class MessageHandlers
  35167. * @param {Object} options the options to initialize with
  35168. */
  35169. class MessageHandlers {
  35170. constructor(self, options) {
  35171. this.options = options || {};
  35172. this.self = self;
  35173. this.init();
  35174. }
  35175. /**
  35176. * initialize our web worker and wire all the events.
  35177. */
  35178. init() {
  35179. if (this.transmuxer) {
  35180. this.transmuxer.dispose();
  35181. }
  35182. this.transmuxer = new transmuxer.Transmuxer(this.options);
  35183. wireTransmuxerEvents(this.self, this.transmuxer);
  35184. }
  35185. pushMp4Captions(data) {
  35186. if (!this.captionParser) {
  35187. this.captionParser = new captionParser();
  35188. this.captionParser.init();
  35189. }
  35190. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  35191. const parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  35192. this.self.postMessage({
  35193. action: 'mp4Captions',
  35194. captions: parsed && parsed.captions || [],
  35195. logs: parsed && parsed.logs || [],
  35196. data: segment.buffer
  35197. }, [segment.buffer]);
  35198. }
  35199. probeMp4StartTime({
  35200. timescales,
  35201. data
  35202. }) {
  35203. const startTime = probe$2.startTime(timescales, data);
  35204. this.self.postMessage({
  35205. action: 'probeMp4StartTime',
  35206. startTime,
  35207. data
  35208. }, [data.buffer]);
  35209. }
  35210. probeMp4Tracks({
  35211. data
  35212. }) {
  35213. const tracks = probe$2.tracks(data);
  35214. this.self.postMessage({
  35215. action: 'probeMp4Tracks',
  35216. tracks,
  35217. data
  35218. }, [data.buffer]);
  35219. }
  35220. /**
  35221. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  35222. * internal "media time," as well as whether it contains video and/or audio.
  35223. *
  35224. * @private
  35225. * @param {Uint8Array} bytes - segment bytes
  35226. * @param {number} baseStartTime
  35227. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  35228. * This value should be in seconds, as it's converted to a 90khz clock within the
  35229. * function body.
  35230. * @return {Object} The start time of the current segment in "media time" as well as
  35231. * whether it contains video and/or audio
  35232. */
  35233. probeTs({
  35234. data,
  35235. baseStartTime
  35236. }) {
  35237. const tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock$2.ONE_SECOND_IN_TS : void 0;
  35238. const timeInfo = tsInspector.inspect(data, tsStartTime);
  35239. let result = null;
  35240. if (timeInfo) {
  35241. result = {
  35242. // each type's time info comes back as an array of 2 times, start and end
  35243. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  35244. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  35245. };
  35246. if (result.hasVideo) {
  35247. result.videoStart = timeInfo.video[0].ptsTime;
  35248. }
  35249. if (result.hasAudio) {
  35250. result.audioStart = timeInfo.audio[0].ptsTime;
  35251. }
  35252. }
  35253. this.self.postMessage({
  35254. action: 'probeTs',
  35255. result,
  35256. data
  35257. }, [data.buffer]);
  35258. }
  35259. clearAllMp4Captions() {
  35260. if (this.captionParser) {
  35261. this.captionParser.clearAllCaptions();
  35262. }
  35263. }
  35264. clearParsedMp4Captions() {
  35265. if (this.captionParser) {
  35266. this.captionParser.clearParsedCaptions();
  35267. }
  35268. }
  35269. /**
  35270. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  35271. * processing.
  35272. *
  35273. * @param {ArrayBuffer} data data to push into the muxer
  35274. */
  35275. push(data) {
  35276. // Cast array buffer to correct type for transmuxer
  35277. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  35278. this.transmuxer.push(segment);
  35279. }
  35280. /**
  35281. * Recreate the transmuxer so that the next segment added via `push`
  35282. * start with a fresh transmuxer.
  35283. */
  35284. reset() {
  35285. this.transmuxer.reset();
  35286. }
  35287. /**
  35288. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  35289. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  35290. * set relative to the first based on the PTS values.
  35291. *
  35292. * @param {Object} data used to set the timestamp offset in the muxer
  35293. */
  35294. setTimestampOffset(data) {
  35295. const timestampOffset = data.timestampOffset || 0;
  35296. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock$2.secondsToVideoTs(timestampOffset)));
  35297. }
  35298. setAudioAppendStart(data) {
  35299. this.transmuxer.setAudioAppendStart(Math.ceil(clock$2.secondsToVideoTs(data.appendStart)));
  35300. }
  35301. setRemux(data) {
  35302. this.transmuxer.setRemux(data.remux);
  35303. }
  35304. /**
  35305. * Forces the pipeline to finish processing the last segment and emit it's
  35306. * results.
  35307. *
  35308. * @param {Object} data event data, not really used
  35309. */
  35310. flush(data) {
  35311. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  35312. self.postMessage({
  35313. action: 'done',
  35314. type: 'transmuxed'
  35315. });
  35316. }
  35317. endTimeline() {
  35318. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  35319. // timelines
  35320. self.postMessage({
  35321. action: 'endedtimeline',
  35322. type: 'transmuxed'
  35323. });
  35324. }
  35325. alignGopsWith(data) {
  35326. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  35327. }
  35328. }
  35329. /**
  35330. * Our web worker interface so that things can talk to mux.js
  35331. * that will be running in a web worker. the scope is passed to this by
  35332. * webworkify.
  35333. *
  35334. * @param {Object} self the scope for the web worker
  35335. */
  35336. self.onmessage = function (event) {
  35337. if (event.data.action === 'init' && event.data.options) {
  35338. this.messageHandlers = new MessageHandlers(self, event.data.options);
  35339. return;
  35340. }
  35341. if (!this.messageHandlers) {
  35342. this.messageHandlers = new MessageHandlers(self);
  35343. }
  35344. if (event.data && event.data.action && event.data.action !== 'init') {
  35345. if (this.messageHandlers[event.data.action]) {
  35346. this.messageHandlers[event.data.action](event.data);
  35347. }
  35348. }
  35349. };
  35350. }));
  35351. var TransmuxWorker = factory(workerCode$1);
  35352. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  35353. const handleData_ = (event, transmuxedData, callback) => {
  35354. const {
  35355. type,
  35356. initSegment,
  35357. captions,
  35358. captionStreams,
  35359. metadata,
  35360. videoFrameDtsTime,
  35361. videoFramePtsTime
  35362. } = event.data.segment;
  35363. transmuxedData.buffer.push({
  35364. captions,
  35365. captionStreams,
  35366. metadata
  35367. });
  35368. const boxes = event.data.segment.boxes || {
  35369. data: event.data.segment.data
  35370. };
  35371. const result = {
  35372. type,
  35373. // cast ArrayBuffer to TypedArray
  35374. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  35375. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  35376. };
  35377. if (typeof videoFrameDtsTime !== 'undefined') {
  35378. result.videoFrameDtsTime = videoFrameDtsTime;
  35379. }
  35380. if (typeof videoFramePtsTime !== 'undefined') {
  35381. result.videoFramePtsTime = videoFramePtsTime;
  35382. }
  35383. callback(result);
  35384. };
  35385. const handleDone_ = ({
  35386. transmuxedData,
  35387. callback
  35388. }) => {
  35389. // Previously we only returned data on data events,
  35390. // not on done events. Clear out the buffer to keep that consistent.
  35391. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  35392. // have received
  35393. callback(transmuxedData);
  35394. };
  35395. const handleGopInfo_ = (event, transmuxedData) => {
  35396. transmuxedData.gopInfo = event.data.gopInfo;
  35397. };
  35398. const processTransmux = options => {
  35399. const {
  35400. transmuxer,
  35401. bytes,
  35402. audioAppendStart,
  35403. gopsToAlignWith,
  35404. remux,
  35405. onData,
  35406. onTrackInfo,
  35407. onAudioTimingInfo,
  35408. onVideoTimingInfo,
  35409. onVideoSegmentTimingInfo,
  35410. onAudioSegmentTimingInfo,
  35411. onId3,
  35412. onCaptions,
  35413. onDone,
  35414. onEndedTimeline,
  35415. onTransmuxerLog,
  35416. isEndOfTimeline
  35417. } = options;
  35418. const transmuxedData = {
  35419. buffer: []
  35420. };
  35421. let waitForEndedTimelineEvent = isEndOfTimeline;
  35422. const handleMessage = event => {
  35423. if (transmuxer.currentTransmux !== options) {
  35424. // disposed
  35425. return;
  35426. }
  35427. if (event.data.action === 'data') {
  35428. handleData_(event, transmuxedData, onData);
  35429. }
  35430. if (event.data.action === 'trackinfo') {
  35431. onTrackInfo(event.data.trackInfo);
  35432. }
  35433. if (event.data.action === 'gopInfo') {
  35434. handleGopInfo_(event, transmuxedData);
  35435. }
  35436. if (event.data.action === 'audioTimingInfo') {
  35437. onAudioTimingInfo(event.data.audioTimingInfo);
  35438. }
  35439. if (event.data.action === 'videoTimingInfo') {
  35440. onVideoTimingInfo(event.data.videoTimingInfo);
  35441. }
  35442. if (event.data.action === 'videoSegmentTimingInfo') {
  35443. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  35444. }
  35445. if (event.data.action === 'audioSegmentTimingInfo') {
  35446. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  35447. }
  35448. if (event.data.action === 'id3Frame') {
  35449. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  35450. }
  35451. if (event.data.action === 'caption') {
  35452. onCaptions(event.data.caption);
  35453. }
  35454. if (event.data.action === 'endedtimeline') {
  35455. waitForEndedTimelineEvent = false;
  35456. onEndedTimeline();
  35457. }
  35458. if (event.data.action === 'log') {
  35459. onTransmuxerLog(event.data.log);
  35460. } // wait for the transmuxed event since we may have audio and video
  35461. if (event.data.type !== 'transmuxed') {
  35462. return;
  35463. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  35464. // of a timeline, that means there may still be data events before the segment
  35465. // processing can be considerred complete. In that case, the final event should be
  35466. // an "endedtimeline" event with the type "transmuxed."
  35467. if (waitForEndedTimelineEvent) {
  35468. return;
  35469. }
  35470. transmuxer.onmessage = null;
  35471. handleDone_({
  35472. transmuxedData,
  35473. callback: onDone
  35474. });
  35475. /* eslint-disable no-use-before-define */
  35476. dequeue(transmuxer);
  35477. /* eslint-enable */
  35478. };
  35479. transmuxer.onmessage = handleMessage;
  35480. if (audioAppendStart) {
  35481. transmuxer.postMessage({
  35482. action: 'setAudioAppendStart',
  35483. appendStart: audioAppendStart
  35484. });
  35485. } // allow empty arrays to be passed to clear out GOPs
  35486. if (Array.isArray(gopsToAlignWith)) {
  35487. transmuxer.postMessage({
  35488. action: 'alignGopsWith',
  35489. gopsToAlignWith
  35490. });
  35491. }
  35492. if (typeof remux !== 'undefined') {
  35493. transmuxer.postMessage({
  35494. action: 'setRemux',
  35495. remux
  35496. });
  35497. }
  35498. if (bytes.byteLength) {
  35499. const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  35500. const byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  35501. transmuxer.postMessage({
  35502. action: 'push',
  35503. // Send the typed-array of data as an ArrayBuffer so that
  35504. // it can be sent as a "Transferable" and avoid the costly
  35505. // memory copy
  35506. data: buffer,
  35507. // To recreate the original typed-array, we need information
  35508. // about what portion of the ArrayBuffer it was a view into
  35509. byteOffset,
  35510. byteLength: bytes.byteLength
  35511. }, [buffer]);
  35512. }
  35513. if (isEndOfTimeline) {
  35514. transmuxer.postMessage({
  35515. action: 'endTimeline'
  35516. });
  35517. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  35518. // the end of the segment
  35519. transmuxer.postMessage({
  35520. action: 'flush'
  35521. });
  35522. };
  35523. const dequeue = transmuxer => {
  35524. transmuxer.currentTransmux = null;
  35525. if (transmuxer.transmuxQueue.length) {
  35526. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  35527. if (typeof transmuxer.currentTransmux === 'function') {
  35528. transmuxer.currentTransmux();
  35529. } else {
  35530. processTransmux(transmuxer.currentTransmux);
  35531. }
  35532. }
  35533. };
  35534. const processAction = (transmuxer, action) => {
  35535. transmuxer.postMessage({
  35536. action
  35537. });
  35538. dequeue(transmuxer);
  35539. };
  35540. const enqueueAction = (action, transmuxer) => {
  35541. if (!transmuxer.currentTransmux) {
  35542. transmuxer.currentTransmux = action;
  35543. processAction(transmuxer, action);
  35544. return;
  35545. }
  35546. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  35547. };
  35548. const reset = transmuxer => {
  35549. enqueueAction('reset', transmuxer);
  35550. };
  35551. const endTimeline = transmuxer => {
  35552. enqueueAction('endTimeline', transmuxer);
  35553. };
  35554. const transmux = options => {
  35555. if (!options.transmuxer.currentTransmux) {
  35556. options.transmuxer.currentTransmux = options;
  35557. processTransmux(options);
  35558. return;
  35559. }
  35560. options.transmuxer.transmuxQueue.push(options);
  35561. };
  35562. const createTransmuxer = options => {
  35563. const transmuxer = new TransmuxWorker();
  35564. transmuxer.currentTransmux = null;
  35565. transmuxer.transmuxQueue = [];
  35566. const term = transmuxer.terminate;
  35567. transmuxer.terminate = () => {
  35568. transmuxer.currentTransmux = null;
  35569. transmuxer.transmuxQueue.length = 0;
  35570. return term.call(transmuxer);
  35571. };
  35572. transmuxer.postMessage({
  35573. action: 'init',
  35574. options
  35575. });
  35576. return transmuxer;
  35577. };
  35578. var segmentTransmuxer = {
  35579. reset,
  35580. endTimeline,
  35581. transmux,
  35582. createTransmuxer
  35583. };
  35584. const workerCallback = function (options) {
  35585. const transmuxer = options.transmuxer;
  35586. const endAction = options.endAction || options.action;
  35587. const callback = options.callback;
  35588. const message = _extends({}, options, {
  35589. endAction: null,
  35590. transmuxer: null,
  35591. callback: null
  35592. });
  35593. const listenForEndEvent = event => {
  35594. if (event.data.action !== endAction) {
  35595. return;
  35596. }
  35597. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  35598. if (event.data.data) {
  35599. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  35600. if (options.data) {
  35601. options.data = event.data.data;
  35602. }
  35603. }
  35604. callback(event.data);
  35605. };
  35606. transmuxer.addEventListener('message', listenForEndEvent);
  35607. if (options.data) {
  35608. const isArrayBuffer = options.data instanceof ArrayBuffer;
  35609. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  35610. message.byteLength = options.data.byteLength;
  35611. const transfers = [isArrayBuffer ? options.data : options.data.buffer];
  35612. transmuxer.postMessage(message, transfers);
  35613. } else {
  35614. transmuxer.postMessage(message);
  35615. }
  35616. };
  35617. const REQUEST_ERRORS = {
  35618. FAILURE: 2,
  35619. TIMEOUT: -101,
  35620. ABORTED: -102
  35621. };
  35622. /**
  35623. * Abort all requests
  35624. *
  35625. * @param {Object} activeXhrs - an object that tracks all XHR requests
  35626. */
  35627. const abortAll = activeXhrs => {
  35628. activeXhrs.forEach(xhr => {
  35629. xhr.abort();
  35630. });
  35631. };
  35632. /**
  35633. * Gather important bandwidth stats once a request has completed
  35634. *
  35635. * @param {Object} request - the XHR request from which to gather stats
  35636. */
  35637. const getRequestStats = request => {
  35638. return {
  35639. bandwidth: request.bandwidth,
  35640. bytesReceived: request.bytesReceived || 0,
  35641. roundTripTime: request.roundTripTime || 0
  35642. };
  35643. };
  35644. /**
  35645. * If possible gather bandwidth stats as a request is in
  35646. * progress
  35647. *
  35648. * @param {Event} progressEvent - an event object from an XHR's progress event
  35649. */
  35650. const getProgressStats = progressEvent => {
  35651. const request = progressEvent.target;
  35652. const roundTripTime = Date.now() - request.requestTime;
  35653. const stats = {
  35654. bandwidth: Infinity,
  35655. bytesReceived: 0,
  35656. roundTripTime: roundTripTime || 0
  35657. };
  35658. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  35659. // because we should only use bandwidth stats on progress to determine when
  35660. // abort a request early due to insufficient bandwidth
  35661. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  35662. return stats;
  35663. };
  35664. /**
  35665. * Handle all error conditions in one place and return an object
  35666. * with all the information
  35667. *
  35668. * @param {Error|null} error - if non-null signals an error occured with the XHR
  35669. * @param {Object} request - the XHR request that possibly generated the error
  35670. */
  35671. const handleErrors = (error, request) => {
  35672. if (request.timedout) {
  35673. return {
  35674. status: request.status,
  35675. message: 'HLS request timed-out at URL: ' + request.uri,
  35676. code: REQUEST_ERRORS.TIMEOUT,
  35677. xhr: request
  35678. };
  35679. }
  35680. if (request.aborted) {
  35681. return {
  35682. status: request.status,
  35683. message: 'HLS request aborted at URL: ' + request.uri,
  35684. code: REQUEST_ERRORS.ABORTED,
  35685. xhr: request
  35686. };
  35687. }
  35688. if (error) {
  35689. return {
  35690. status: request.status,
  35691. message: 'HLS request errored at URL: ' + request.uri,
  35692. code: REQUEST_ERRORS.FAILURE,
  35693. xhr: request
  35694. };
  35695. }
  35696. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  35697. return {
  35698. status: request.status,
  35699. message: 'Empty HLS response at URL: ' + request.uri,
  35700. code: REQUEST_ERRORS.FAILURE,
  35701. xhr: request
  35702. };
  35703. }
  35704. return null;
  35705. };
  35706. /**
  35707. * Handle responses for key data and convert the key data to the correct format
  35708. * for the decryption step later
  35709. *
  35710. * @param {Object} segment - a simplified copy of the segmentInfo object
  35711. * from SegmentLoader
  35712. * @param {Array} objects - objects to add the key bytes to.
  35713. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  35714. * this request
  35715. */
  35716. const handleKeyResponse = (segment, objects, finishProcessingFn) => (error, request) => {
  35717. const response = request.response;
  35718. const errorObj = handleErrors(error, request);
  35719. if (errorObj) {
  35720. return finishProcessingFn(errorObj, segment);
  35721. }
  35722. if (response.byteLength !== 16) {
  35723. return finishProcessingFn({
  35724. status: request.status,
  35725. message: 'Invalid HLS key at URL: ' + request.uri,
  35726. code: REQUEST_ERRORS.FAILURE,
  35727. xhr: request
  35728. }, segment);
  35729. }
  35730. const view = new DataView(response);
  35731. const bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  35732. for (let i = 0; i < objects.length; i++) {
  35733. objects[i].bytes = bytes;
  35734. }
  35735. return finishProcessingFn(null, segment);
  35736. };
  35737. const parseInitSegment = (segment, callback) => {
  35738. const type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  35739. // only know how to parse mp4 init segments at the moment
  35740. if (type !== 'mp4') {
  35741. const uri = segment.map.resolvedUri || segment.map.uri;
  35742. return callback({
  35743. internal: true,
  35744. message: `Found unsupported ${type || 'unknown'} container for initialization segment at URL: ${uri}`,
  35745. code: REQUEST_ERRORS.FAILURE
  35746. });
  35747. }
  35748. workerCallback({
  35749. action: 'probeMp4Tracks',
  35750. data: segment.map.bytes,
  35751. transmuxer: segment.transmuxer,
  35752. callback: ({
  35753. tracks,
  35754. data
  35755. }) => {
  35756. // transfer bytes back to us
  35757. segment.map.bytes = data;
  35758. tracks.forEach(function (track) {
  35759. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  35760. if (segment.map.tracks[track.type]) {
  35761. return;
  35762. }
  35763. segment.map.tracks[track.type] = track;
  35764. if (typeof track.id === 'number' && track.timescale) {
  35765. segment.map.timescales = segment.map.timescales || {};
  35766. segment.map.timescales[track.id] = track.timescale;
  35767. }
  35768. });
  35769. return callback(null);
  35770. }
  35771. });
  35772. };
  35773. /**
  35774. * Handle init-segment responses
  35775. *
  35776. * @param {Object} segment - a simplified copy of the segmentInfo object
  35777. * from SegmentLoader
  35778. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  35779. * this request
  35780. */
  35781. const handleInitSegmentResponse = ({
  35782. segment,
  35783. finishProcessingFn
  35784. }) => (error, request) => {
  35785. const errorObj = handleErrors(error, request);
  35786. if (errorObj) {
  35787. return finishProcessingFn(errorObj, segment);
  35788. }
  35789. const bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  35790. // until the key request is done to decrypt.
  35791. if (segment.map.key) {
  35792. segment.map.encryptedBytes = bytes;
  35793. return finishProcessingFn(null, segment);
  35794. }
  35795. segment.map.bytes = bytes;
  35796. parseInitSegment(segment, function (parseError) {
  35797. if (parseError) {
  35798. parseError.xhr = request;
  35799. parseError.status = request.status;
  35800. return finishProcessingFn(parseError, segment);
  35801. }
  35802. finishProcessingFn(null, segment);
  35803. });
  35804. };
  35805. /**
  35806. * Response handler for segment-requests being sure to set the correct
  35807. * property depending on whether the segment is encryped or not
  35808. * Also records and keeps track of stats that are used for ABR purposes
  35809. *
  35810. * @param {Object} segment - a simplified copy of the segmentInfo object
  35811. * from SegmentLoader
  35812. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  35813. * this request
  35814. */
  35815. const handleSegmentResponse = ({
  35816. segment,
  35817. finishProcessingFn,
  35818. responseType
  35819. }) => (error, request) => {
  35820. const errorObj = handleErrors(error, request);
  35821. if (errorObj) {
  35822. return finishProcessingFn(errorObj, segment);
  35823. }
  35824. const newBytes =
  35825. // although responseText "should" exist, this guard serves to prevent an error being
  35826. // thrown for two primary cases:
  35827. // 1. the mime type override stops working, or is not implemented for a specific
  35828. // browser
  35829. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  35830. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  35831. segment.stats = getRequestStats(request);
  35832. if (segment.key) {
  35833. segment.encryptedBytes = new Uint8Array(newBytes);
  35834. } else {
  35835. segment.bytes = new Uint8Array(newBytes);
  35836. }
  35837. return finishProcessingFn(null, segment);
  35838. };
  35839. const transmuxAndNotify = ({
  35840. segment,
  35841. bytes,
  35842. trackInfoFn,
  35843. timingInfoFn,
  35844. videoSegmentTimingInfoFn,
  35845. audioSegmentTimingInfoFn,
  35846. id3Fn,
  35847. captionsFn,
  35848. isEndOfTimeline,
  35849. endedTimelineFn,
  35850. dataFn,
  35851. doneFn,
  35852. onTransmuxerLog
  35853. }) => {
  35854. const fmp4Tracks = segment.map && segment.map.tracks || {};
  35855. const isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  35856. // One reason for this is that in the case of full segments, we want to trust start
  35857. // times from the probe, rather than the transmuxer.
  35858. let audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  35859. const audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  35860. let videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  35861. const videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  35862. const finish = () => transmux({
  35863. bytes,
  35864. transmuxer: segment.transmuxer,
  35865. audioAppendStart: segment.audioAppendStart,
  35866. gopsToAlignWith: segment.gopsToAlignWith,
  35867. remux: isMuxed,
  35868. onData: result => {
  35869. result.type = result.type === 'combined' ? 'video' : result.type;
  35870. dataFn(segment, result);
  35871. },
  35872. onTrackInfo: trackInfo => {
  35873. if (trackInfoFn) {
  35874. if (isMuxed) {
  35875. trackInfo.isMuxed = true;
  35876. }
  35877. trackInfoFn(segment, trackInfo);
  35878. }
  35879. },
  35880. onAudioTimingInfo: audioTimingInfo => {
  35881. // we only want the first start value we encounter
  35882. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  35883. audioStartFn(audioTimingInfo.start);
  35884. audioStartFn = null;
  35885. } // we want to continually update the end time
  35886. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  35887. audioEndFn(audioTimingInfo.end);
  35888. }
  35889. },
  35890. onVideoTimingInfo: videoTimingInfo => {
  35891. // we only want the first start value we encounter
  35892. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  35893. videoStartFn(videoTimingInfo.start);
  35894. videoStartFn = null;
  35895. } // we want to continually update the end time
  35896. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  35897. videoEndFn(videoTimingInfo.end);
  35898. }
  35899. },
  35900. onVideoSegmentTimingInfo: videoSegmentTimingInfo => {
  35901. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  35902. },
  35903. onAudioSegmentTimingInfo: audioSegmentTimingInfo => {
  35904. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  35905. },
  35906. onId3: (id3Frames, dispatchType) => {
  35907. id3Fn(segment, id3Frames, dispatchType);
  35908. },
  35909. onCaptions: captions => {
  35910. captionsFn(segment, [captions]);
  35911. },
  35912. isEndOfTimeline,
  35913. onEndedTimeline: () => {
  35914. endedTimelineFn();
  35915. },
  35916. onTransmuxerLog,
  35917. onDone: result => {
  35918. if (!doneFn) {
  35919. return;
  35920. }
  35921. result.type = result.type === 'combined' ? 'video' : result.type;
  35922. doneFn(null, segment, result);
  35923. }
  35924. }); // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  35925. // Meaning cached frame data may corrupt our notion of where this segment
  35926. // really starts. To get around this, probe for the info needed.
  35927. workerCallback({
  35928. action: 'probeTs',
  35929. transmuxer: segment.transmuxer,
  35930. data: bytes,
  35931. baseStartTime: segment.baseStartTime,
  35932. callback: data => {
  35933. segment.bytes = bytes = data.data;
  35934. const probeResult = data.result;
  35935. if (probeResult) {
  35936. trackInfoFn(segment, {
  35937. hasAudio: probeResult.hasAudio,
  35938. hasVideo: probeResult.hasVideo,
  35939. isMuxed
  35940. });
  35941. trackInfoFn = null;
  35942. if (probeResult.hasAudio && !isMuxed) {
  35943. audioStartFn(probeResult.audioStart);
  35944. }
  35945. if (probeResult.hasVideo) {
  35946. videoStartFn(probeResult.videoStart);
  35947. }
  35948. audioStartFn = null;
  35949. videoStartFn = null;
  35950. }
  35951. finish();
  35952. }
  35953. });
  35954. };
  35955. const handleSegmentBytes = ({
  35956. segment,
  35957. bytes,
  35958. trackInfoFn,
  35959. timingInfoFn,
  35960. videoSegmentTimingInfoFn,
  35961. audioSegmentTimingInfoFn,
  35962. id3Fn,
  35963. captionsFn,
  35964. isEndOfTimeline,
  35965. endedTimelineFn,
  35966. dataFn,
  35967. doneFn,
  35968. onTransmuxerLog
  35969. }) => {
  35970. let bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  35971. // We should have a handler that fetches the number of bytes required
  35972. // to check if something is fmp4. This will allow us to save bandwidth
  35973. // because we can only exclude a playlist and abort requests
  35974. // by codec after trackinfo triggers.
  35975. if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  35976. segment.isFmp4 = true;
  35977. const {
  35978. tracks
  35979. } = segment.map;
  35980. const trackInfo = {
  35981. isFmp4: true,
  35982. hasVideo: !!tracks.video,
  35983. hasAudio: !!tracks.audio
  35984. }; // if we have a audio track, with a codec that is not set to
  35985. // encrypted audio
  35986. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  35987. trackInfo.audioCodec = tracks.audio.codec;
  35988. } // if we have a video track, with a codec that is not set to
  35989. // encrypted video
  35990. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  35991. trackInfo.videoCodec = tracks.video.codec;
  35992. }
  35993. if (tracks.video && tracks.audio) {
  35994. trackInfo.isMuxed = true;
  35995. } // since we don't support appending fmp4 data on progress, we know we have the full
  35996. // segment here
  35997. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  35998. // time. The end time can be roughly calculated by the receiver using the duration.
  35999. //
  36000. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  36001. // that is the true start of the segment (where the playback engine should begin
  36002. // decoding).
  36003. const finishLoading = captions => {
  36004. // if the track still has audio at this point it is only possible
  36005. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  36006. // above.
  36007. // we make sure to use segment.bytes here as that
  36008. dataFn(segment, {
  36009. data: bytesAsUint8Array,
  36010. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  36011. });
  36012. if (captions && captions.length) {
  36013. captionsFn(segment, captions);
  36014. }
  36015. doneFn(null, segment, {});
  36016. };
  36017. workerCallback({
  36018. action: 'probeMp4StartTime',
  36019. timescales: segment.map.timescales,
  36020. data: bytesAsUint8Array,
  36021. transmuxer: segment.transmuxer,
  36022. callback: ({
  36023. data,
  36024. startTime
  36025. }) => {
  36026. // transfer bytes back to us
  36027. bytes = data.buffer;
  36028. segment.bytes = bytesAsUint8Array = data;
  36029. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  36030. timingInfoFn(segment, 'audio', 'start', startTime);
  36031. }
  36032. if (trackInfo.hasVideo) {
  36033. timingInfoFn(segment, 'video', 'start', startTime);
  36034. } // Run through the CaptionParser in case there are captions.
  36035. // Initialize CaptionParser if it hasn't been yet
  36036. if (!tracks.video || !data.byteLength || !segment.transmuxer) {
  36037. finishLoading();
  36038. return;
  36039. }
  36040. workerCallback({
  36041. action: 'pushMp4Captions',
  36042. endAction: 'mp4Captions',
  36043. transmuxer: segment.transmuxer,
  36044. data: bytesAsUint8Array,
  36045. timescales: segment.map.timescales,
  36046. trackIds: [tracks.video.id],
  36047. callback: message => {
  36048. // transfer bytes back to us
  36049. bytes = message.data.buffer;
  36050. segment.bytes = bytesAsUint8Array = message.data;
  36051. message.logs.forEach(function (log) {
  36052. onTransmuxerLog(merge(log, {
  36053. stream: 'mp4CaptionParser'
  36054. }));
  36055. });
  36056. finishLoading(message.captions);
  36057. }
  36058. });
  36059. }
  36060. });
  36061. return;
  36062. } // VTT or other segments that don't need processing
  36063. if (!segment.transmuxer) {
  36064. doneFn(null, segment, {});
  36065. return;
  36066. }
  36067. if (typeof segment.container === 'undefined') {
  36068. segment.container = detectContainerForBytes(bytesAsUint8Array);
  36069. }
  36070. if (segment.container !== 'ts' && segment.container !== 'aac') {
  36071. trackInfoFn(segment, {
  36072. hasAudio: false,
  36073. hasVideo: false
  36074. });
  36075. doneFn(null, segment, {});
  36076. return;
  36077. } // ts or aac
  36078. transmuxAndNotify({
  36079. segment,
  36080. bytes,
  36081. trackInfoFn,
  36082. timingInfoFn,
  36083. videoSegmentTimingInfoFn,
  36084. audioSegmentTimingInfoFn,
  36085. id3Fn,
  36086. captionsFn,
  36087. isEndOfTimeline,
  36088. endedTimelineFn,
  36089. dataFn,
  36090. doneFn,
  36091. onTransmuxerLog
  36092. });
  36093. };
  36094. const decrypt = function ({
  36095. id,
  36096. key,
  36097. encryptedBytes,
  36098. decryptionWorker
  36099. }, callback) {
  36100. const decryptionHandler = event => {
  36101. if (event.data.source === id) {
  36102. decryptionWorker.removeEventListener('message', decryptionHandler);
  36103. const decrypted = event.data.decrypted;
  36104. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  36105. }
  36106. };
  36107. decryptionWorker.addEventListener('message', decryptionHandler);
  36108. let keyBytes;
  36109. if (key.bytes.slice) {
  36110. keyBytes = key.bytes.slice();
  36111. } else {
  36112. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  36113. } // incrementally decrypt the bytes
  36114. decryptionWorker.postMessage(createTransferableMessage({
  36115. source: id,
  36116. encrypted: encryptedBytes,
  36117. key: keyBytes,
  36118. iv: key.iv
  36119. }), [encryptedBytes.buffer, keyBytes.buffer]);
  36120. };
  36121. /**
  36122. * Decrypt the segment via the decryption web worker
  36123. *
  36124. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  36125. * routines
  36126. * @param {Object} segment - a simplified copy of the segmentInfo object
  36127. * from SegmentLoader
  36128. * @param {Function} trackInfoFn - a callback that receives track info
  36129. * @param {Function} timingInfoFn - a callback that receives timing info
  36130. * @param {Function} videoSegmentTimingInfoFn
  36131. * a callback that receives video timing info based on media times and
  36132. * any adjustments made by the transmuxer
  36133. * @param {Function} audioSegmentTimingInfoFn
  36134. * a callback that receives audio timing info based on media times and
  36135. * any adjustments made by the transmuxer
  36136. * @param {boolean} isEndOfTimeline
  36137. * true if this segment represents the last segment in a timeline
  36138. * @param {Function} endedTimelineFn
  36139. * a callback made when a timeline is ended, will only be called if
  36140. * isEndOfTimeline is true
  36141. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  36142. * and ready to use
  36143. * @param {Function} doneFn - a callback that is executed after decryption has completed
  36144. */
  36145. const decryptSegment = ({
  36146. decryptionWorker,
  36147. segment,
  36148. trackInfoFn,
  36149. timingInfoFn,
  36150. videoSegmentTimingInfoFn,
  36151. audioSegmentTimingInfoFn,
  36152. id3Fn,
  36153. captionsFn,
  36154. isEndOfTimeline,
  36155. endedTimelineFn,
  36156. dataFn,
  36157. doneFn,
  36158. onTransmuxerLog
  36159. }) => {
  36160. decrypt({
  36161. id: segment.requestId,
  36162. key: segment.key,
  36163. encryptedBytes: segment.encryptedBytes,
  36164. decryptionWorker
  36165. }, decryptedBytes => {
  36166. segment.bytes = decryptedBytes;
  36167. handleSegmentBytes({
  36168. segment,
  36169. bytes: segment.bytes,
  36170. trackInfoFn,
  36171. timingInfoFn,
  36172. videoSegmentTimingInfoFn,
  36173. audioSegmentTimingInfoFn,
  36174. id3Fn,
  36175. captionsFn,
  36176. isEndOfTimeline,
  36177. endedTimelineFn,
  36178. dataFn,
  36179. doneFn,
  36180. onTransmuxerLog
  36181. });
  36182. });
  36183. };
  36184. /**
  36185. * This function waits for all XHRs to finish (with either success or failure)
  36186. * before continueing processing via it's callback. The function gathers errors
  36187. * from each request into a single errors array so that the error status for
  36188. * each request can be examined later.
  36189. *
  36190. * @param {Object} activeXhrs - an object that tracks all XHR requests
  36191. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  36192. * routines
  36193. * @param {Function} trackInfoFn - a callback that receives track info
  36194. * @param {Function} timingInfoFn - a callback that receives timing info
  36195. * @param {Function} videoSegmentTimingInfoFn
  36196. * a callback that receives video timing info based on media times and
  36197. * any adjustments made by the transmuxer
  36198. * @param {Function} audioSegmentTimingInfoFn
  36199. * a callback that receives audio timing info based on media times and
  36200. * any adjustments made by the transmuxer
  36201. * @param {Function} id3Fn - a callback that receives ID3 metadata
  36202. * @param {Function} captionsFn - a callback that receives captions
  36203. * @param {boolean} isEndOfTimeline
  36204. * true if this segment represents the last segment in a timeline
  36205. * @param {Function} endedTimelineFn
  36206. * a callback made when a timeline is ended, will only be called if
  36207. * isEndOfTimeline is true
  36208. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  36209. * and ready to use
  36210. * @param {Function} doneFn - a callback that is executed after all resources have been
  36211. * downloaded and any decryption completed
  36212. */
  36213. const waitForCompletion = ({
  36214. activeXhrs,
  36215. decryptionWorker,
  36216. trackInfoFn,
  36217. timingInfoFn,
  36218. videoSegmentTimingInfoFn,
  36219. audioSegmentTimingInfoFn,
  36220. id3Fn,
  36221. captionsFn,
  36222. isEndOfTimeline,
  36223. endedTimelineFn,
  36224. dataFn,
  36225. doneFn,
  36226. onTransmuxerLog
  36227. }) => {
  36228. let count = 0;
  36229. let didError = false;
  36230. return (error, segment) => {
  36231. if (didError) {
  36232. return;
  36233. }
  36234. if (error) {
  36235. didError = true; // If there are errors, we have to abort any outstanding requests
  36236. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  36237. // handle the aborted events from those requests, there are some cases where we may
  36238. // never get an aborted event. For instance, if the network connection is lost and
  36239. // there were two requests, the first may have triggered an error immediately, while
  36240. // the second request remains unsent. In that case, the aborted algorithm will not
  36241. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  36242. //
  36243. // We also can't rely on the ready state of the XHR, since the request that
  36244. // triggered the connection error may also show as a ready state of 0 (unsent).
  36245. // Therefore, we have to finish this group of requests immediately after the first
  36246. // seen error.
  36247. return doneFn(error, segment);
  36248. }
  36249. count += 1;
  36250. if (count === activeXhrs.length) {
  36251. const segmentFinish = function () {
  36252. if (segment.encryptedBytes) {
  36253. return decryptSegment({
  36254. decryptionWorker,
  36255. segment,
  36256. trackInfoFn,
  36257. timingInfoFn,
  36258. videoSegmentTimingInfoFn,
  36259. audioSegmentTimingInfoFn,
  36260. id3Fn,
  36261. captionsFn,
  36262. isEndOfTimeline,
  36263. endedTimelineFn,
  36264. dataFn,
  36265. doneFn,
  36266. onTransmuxerLog
  36267. });
  36268. } // Otherwise, everything is ready just continue
  36269. handleSegmentBytes({
  36270. segment,
  36271. bytes: segment.bytes,
  36272. trackInfoFn,
  36273. timingInfoFn,
  36274. videoSegmentTimingInfoFn,
  36275. audioSegmentTimingInfoFn,
  36276. id3Fn,
  36277. captionsFn,
  36278. isEndOfTimeline,
  36279. endedTimelineFn,
  36280. dataFn,
  36281. doneFn,
  36282. onTransmuxerLog
  36283. });
  36284. }; // Keep track of when *all* of the requests have completed
  36285. segment.endOfAllRequests = Date.now();
  36286. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  36287. return decrypt({
  36288. decryptionWorker,
  36289. // add -init to the "id" to differentiate between segment
  36290. // and init segment decryption, just in case they happen
  36291. // at the same time at some point in the future.
  36292. id: segment.requestId + '-init',
  36293. encryptedBytes: segment.map.encryptedBytes,
  36294. key: segment.map.key
  36295. }, decryptedBytes => {
  36296. segment.map.bytes = decryptedBytes;
  36297. parseInitSegment(segment, parseError => {
  36298. if (parseError) {
  36299. abortAll(activeXhrs);
  36300. return doneFn(parseError, segment);
  36301. }
  36302. segmentFinish();
  36303. });
  36304. });
  36305. }
  36306. segmentFinish();
  36307. }
  36308. };
  36309. };
  36310. /**
  36311. * Calls the abort callback if any request within the batch was aborted. Will only call
  36312. * the callback once per batch of requests, even if multiple were aborted.
  36313. *
  36314. * @param {Object} loadendState - state to check to see if the abort function was called
  36315. * @param {Function} abortFn - callback to call for abort
  36316. */
  36317. const handleLoadEnd = ({
  36318. loadendState,
  36319. abortFn
  36320. }) => event => {
  36321. const request = event.target;
  36322. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  36323. abortFn();
  36324. loadendState.calledAbortFn = true;
  36325. }
  36326. };
  36327. /**
  36328. * Simple progress event callback handler that gathers some stats before
  36329. * executing a provided callback with the `segment` object
  36330. *
  36331. * @param {Object} segment - a simplified copy of the segmentInfo object
  36332. * from SegmentLoader
  36333. * @param {Function} progressFn - a callback that is executed each time a progress event
  36334. * is received
  36335. * @param {Function} trackInfoFn - a callback that receives track info
  36336. * @param {Function} timingInfoFn - a callback that receives timing info
  36337. * @param {Function} videoSegmentTimingInfoFn
  36338. * a callback that receives video timing info based on media times and
  36339. * any adjustments made by the transmuxer
  36340. * @param {Function} audioSegmentTimingInfoFn
  36341. * a callback that receives audio timing info based on media times and
  36342. * any adjustments made by the transmuxer
  36343. * @param {boolean} isEndOfTimeline
  36344. * true if this segment represents the last segment in a timeline
  36345. * @param {Function} endedTimelineFn
  36346. * a callback made when a timeline is ended, will only be called if
  36347. * isEndOfTimeline is true
  36348. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  36349. * and ready to use
  36350. * @param {Event} event - the progress event object from XMLHttpRequest
  36351. */
  36352. const handleProgress = ({
  36353. segment,
  36354. progressFn,
  36355. trackInfoFn,
  36356. timingInfoFn,
  36357. videoSegmentTimingInfoFn,
  36358. audioSegmentTimingInfoFn,
  36359. id3Fn,
  36360. captionsFn,
  36361. isEndOfTimeline,
  36362. endedTimelineFn,
  36363. dataFn
  36364. }) => event => {
  36365. const request = event.target;
  36366. if (request.aborted) {
  36367. return;
  36368. }
  36369. segment.stats = merge(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  36370. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  36371. segment.stats.firstBytesReceivedAt = Date.now();
  36372. }
  36373. return progressFn(event, segment);
  36374. };
  36375. /**
  36376. * Load all resources and does any processing necessary for a media-segment
  36377. *
  36378. * Features:
  36379. * decrypts the media-segment if it has a key uri and an iv
  36380. * aborts *all* requests if *any* one request fails
  36381. *
  36382. * The segment object, at minimum, has the following format:
  36383. * {
  36384. * resolvedUri: String,
  36385. * [transmuxer]: Object,
  36386. * [byterange]: {
  36387. * offset: Number,
  36388. * length: Number
  36389. * },
  36390. * [key]: {
  36391. * resolvedUri: String
  36392. * [byterange]: {
  36393. * offset: Number,
  36394. * length: Number
  36395. * },
  36396. * iv: {
  36397. * bytes: Uint32Array
  36398. * }
  36399. * },
  36400. * [map]: {
  36401. * resolvedUri: String,
  36402. * [byterange]: {
  36403. * offset: Number,
  36404. * length: Number
  36405. * },
  36406. * [bytes]: Uint8Array
  36407. * }
  36408. * }
  36409. * ...where [name] denotes optional properties
  36410. *
  36411. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  36412. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  36413. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  36414. * decryption routines
  36415. * @param {Object} segment - a simplified copy of the segmentInfo object
  36416. * from SegmentLoader
  36417. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  36418. * aborted
  36419. * @param {Function} progressFn - a callback that receives progress events from the main
  36420. * segment's xhr request
  36421. * @param {Function} trackInfoFn - a callback that receives track info
  36422. * @param {Function} timingInfoFn - a callback that receives timing info
  36423. * @param {Function} videoSegmentTimingInfoFn
  36424. * a callback that receives video timing info based on media times and
  36425. * any adjustments made by the transmuxer
  36426. * @param {Function} audioSegmentTimingInfoFn
  36427. * a callback that receives audio timing info based on media times and
  36428. * any adjustments made by the transmuxer
  36429. * @param {Function} id3Fn - a callback that receives ID3 metadata
  36430. * @param {Function} captionsFn - a callback that receives captions
  36431. * @param {boolean} isEndOfTimeline
  36432. * true if this segment represents the last segment in a timeline
  36433. * @param {Function} endedTimelineFn
  36434. * a callback made when a timeline is ended, will only be called if
  36435. * isEndOfTimeline is true
  36436. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  36437. * request, transmuxed if needed
  36438. * @param {Function} doneFn - a callback that is executed only once all requests have
  36439. * succeeded or failed
  36440. * @return {Function} a function that, when invoked, immediately aborts all
  36441. * outstanding requests
  36442. */
  36443. const mediaSegmentRequest = ({
  36444. xhr,
  36445. xhrOptions,
  36446. decryptionWorker,
  36447. segment,
  36448. abortFn,
  36449. progressFn,
  36450. trackInfoFn,
  36451. timingInfoFn,
  36452. videoSegmentTimingInfoFn,
  36453. audioSegmentTimingInfoFn,
  36454. id3Fn,
  36455. captionsFn,
  36456. isEndOfTimeline,
  36457. endedTimelineFn,
  36458. dataFn,
  36459. doneFn,
  36460. onTransmuxerLog
  36461. }) => {
  36462. const activeXhrs = [];
  36463. const finishProcessingFn = waitForCompletion({
  36464. activeXhrs,
  36465. decryptionWorker,
  36466. trackInfoFn,
  36467. timingInfoFn,
  36468. videoSegmentTimingInfoFn,
  36469. audioSegmentTimingInfoFn,
  36470. id3Fn,
  36471. captionsFn,
  36472. isEndOfTimeline,
  36473. endedTimelineFn,
  36474. dataFn,
  36475. doneFn,
  36476. onTransmuxerLog
  36477. }); // optionally, request the decryption key
  36478. if (segment.key && !segment.key.bytes) {
  36479. const objects = [segment.key];
  36480. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  36481. objects.push(segment.map.key);
  36482. }
  36483. const keyRequestOptions = merge(xhrOptions, {
  36484. uri: segment.key.resolvedUri,
  36485. responseType: 'arraybuffer'
  36486. });
  36487. const keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  36488. const keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  36489. activeXhrs.push(keyXhr);
  36490. } // optionally, request the associated media init segment
  36491. if (segment.map && !segment.map.bytes) {
  36492. const differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  36493. if (differentMapKey) {
  36494. const mapKeyRequestOptions = merge(xhrOptions, {
  36495. uri: segment.map.key.resolvedUri,
  36496. responseType: 'arraybuffer'
  36497. });
  36498. const mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  36499. const mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  36500. activeXhrs.push(mapKeyXhr);
  36501. }
  36502. const initSegmentOptions = merge(xhrOptions, {
  36503. uri: segment.map.resolvedUri,
  36504. responseType: 'arraybuffer',
  36505. headers: segmentXhrHeaders(segment.map)
  36506. });
  36507. const initSegmentRequestCallback = handleInitSegmentResponse({
  36508. segment,
  36509. finishProcessingFn
  36510. });
  36511. const initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  36512. activeXhrs.push(initSegmentXhr);
  36513. }
  36514. const segmentRequestOptions = merge(xhrOptions, {
  36515. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  36516. responseType: 'arraybuffer',
  36517. headers: segmentXhrHeaders(segment)
  36518. });
  36519. const segmentRequestCallback = handleSegmentResponse({
  36520. segment,
  36521. finishProcessingFn,
  36522. responseType: segmentRequestOptions.responseType
  36523. });
  36524. const segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  36525. segmentXhr.addEventListener('progress', handleProgress({
  36526. segment,
  36527. progressFn,
  36528. trackInfoFn,
  36529. timingInfoFn,
  36530. videoSegmentTimingInfoFn,
  36531. audioSegmentTimingInfoFn,
  36532. id3Fn,
  36533. captionsFn,
  36534. isEndOfTimeline,
  36535. endedTimelineFn,
  36536. dataFn
  36537. }));
  36538. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  36539. // multiple times, provide a shared state object
  36540. const loadendState = {};
  36541. activeXhrs.forEach(activeXhr => {
  36542. activeXhr.addEventListener('loadend', handleLoadEnd({
  36543. loadendState,
  36544. abortFn
  36545. }));
  36546. });
  36547. return () => abortAll(activeXhrs);
  36548. };
  36549. /**
  36550. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  36551. * codec strings, or translating codec strings into objects that can be examined.
  36552. */
  36553. const logFn$1 = logger('CodecUtils');
  36554. /**
  36555. * Returns a set of codec strings parsed from the playlist or the default
  36556. * codec strings if no codecs were specified in the playlist
  36557. *
  36558. * @param {Playlist} media the current media playlist
  36559. * @return {Object} an object with the video and audio codecs
  36560. */
  36561. const getCodecs = function (media) {
  36562. // if the codecs were explicitly specified, use them instead of the
  36563. // defaults
  36564. const mediaAttributes = media.attributes || {};
  36565. if (mediaAttributes.CODECS) {
  36566. return parseCodecs(mediaAttributes.CODECS);
  36567. }
  36568. };
  36569. const isMaat = (main, media) => {
  36570. const mediaAttributes = media.attributes || {};
  36571. return main && main.mediaGroups && main.mediaGroups.AUDIO && mediaAttributes.AUDIO && main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  36572. };
  36573. const isMuxed = (main, media) => {
  36574. if (!isMaat(main, media)) {
  36575. return true;
  36576. }
  36577. const mediaAttributes = media.attributes || {};
  36578. const audioGroup = main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  36579. for (const groupId in audioGroup) {
  36580. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  36581. // or there are listed playlists (the case for DASH, as the manifest will have already
  36582. // provided all of the details necessary to generate the audio playlist, as opposed to
  36583. // HLS' externally requested playlists), then the content is demuxed.
  36584. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  36585. return true;
  36586. }
  36587. }
  36588. return false;
  36589. };
  36590. const unwrapCodecList = function (codecList) {
  36591. const codecs = {};
  36592. codecList.forEach(({
  36593. mediaType,
  36594. type,
  36595. details
  36596. }) => {
  36597. codecs[mediaType] = codecs[mediaType] || [];
  36598. codecs[mediaType].push(translateLegacyCodec(`${type}${details}`));
  36599. });
  36600. Object.keys(codecs).forEach(function (mediaType) {
  36601. if (codecs[mediaType].length > 1) {
  36602. 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.`);
  36603. codecs[mediaType] = null;
  36604. return;
  36605. }
  36606. codecs[mediaType] = codecs[mediaType][0];
  36607. });
  36608. return codecs;
  36609. };
  36610. const codecCount = function (codecObj) {
  36611. let count = 0;
  36612. if (codecObj.audio) {
  36613. count++;
  36614. }
  36615. if (codecObj.video) {
  36616. count++;
  36617. }
  36618. return count;
  36619. };
  36620. /**
  36621. * Calculates the codec strings for a working configuration of
  36622. * SourceBuffers to play variant streams in a main playlist. If
  36623. * there is no possible working configuration, an empty object will be
  36624. * returned.
  36625. *
  36626. * @param main {Object} the m3u8 object for the main playlist
  36627. * @param media {Object} the m3u8 object for the variant playlist
  36628. * @return {Object} the codec strings.
  36629. *
  36630. * @private
  36631. */
  36632. const codecsForPlaylist = function (main, media) {
  36633. const mediaAttributes = media.attributes || {};
  36634. const codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  36635. // Put another way, there is no way to have a video-only multiple-audio HLS!
  36636. if (isMaat(main, media) && !codecInfo.audio) {
  36637. if (!isMuxed(main, media)) {
  36638. // It is possible for codecs to be specified on the audio media group playlist but
  36639. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  36640. // video are always separate (and separately specified).
  36641. const defaultCodecs = unwrapCodecList(codecsFromDefault(main, mediaAttributes.AUDIO) || []);
  36642. if (defaultCodecs.audio) {
  36643. codecInfo.audio = defaultCodecs.audio;
  36644. }
  36645. }
  36646. }
  36647. return codecInfo;
  36648. };
  36649. const logFn = logger('PlaylistSelector');
  36650. const representationToString = function (representation) {
  36651. if (!representation || !representation.playlist) {
  36652. return;
  36653. }
  36654. const playlist = representation.playlist;
  36655. return JSON.stringify({
  36656. id: playlist.id,
  36657. bandwidth: representation.bandwidth,
  36658. width: representation.width,
  36659. height: representation.height,
  36660. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  36661. });
  36662. }; // Utilities
  36663. /**
  36664. * Returns the CSS value for the specified property on an element
  36665. * using `getComputedStyle`. Firefox has a long-standing issue where
  36666. * getComputedStyle() may return null when running in an iframe with
  36667. * `display: none`.
  36668. *
  36669. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  36670. * @param {HTMLElement} el the htmlelement to work on
  36671. * @param {string} the proprety to get the style for
  36672. */
  36673. const safeGetComputedStyle = function (el, property) {
  36674. if (!el) {
  36675. return '';
  36676. }
  36677. const result = window$1.getComputedStyle(el);
  36678. if (!result) {
  36679. return '';
  36680. }
  36681. return result[property];
  36682. };
  36683. /**
  36684. * Resuable stable sort function
  36685. *
  36686. * @param {Playlists} array
  36687. * @param {Function} sortFn Different comparators
  36688. * @function stableSort
  36689. */
  36690. const stableSort = function (array, sortFn) {
  36691. const newArray = array.slice();
  36692. array.sort(function (left, right) {
  36693. const cmp = sortFn(left, right);
  36694. if (cmp === 0) {
  36695. return newArray.indexOf(left) - newArray.indexOf(right);
  36696. }
  36697. return cmp;
  36698. });
  36699. };
  36700. /**
  36701. * A comparator function to sort two playlist object by bandwidth.
  36702. *
  36703. * @param {Object} left a media playlist object
  36704. * @param {Object} right a media playlist object
  36705. * @return {number} Greater than zero if the bandwidth attribute of
  36706. * left is greater than the corresponding attribute of right. Less
  36707. * than zero if the bandwidth of right is greater than left and
  36708. * exactly zero if the two are equal.
  36709. */
  36710. const comparePlaylistBandwidth = function (left, right) {
  36711. let leftBandwidth;
  36712. let rightBandwidth;
  36713. if (left.attributes.BANDWIDTH) {
  36714. leftBandwidth = left.attributes.BANDWIDTH;
  36715. }
  36716. leftBandwidth = leftBandwidth || window$1.Number.MAX_VALUE;
  36717. if (right.attributes.BANDWIDTH) {
  36718. rightBandwidth = right.attributes.BANDWIDTH;
  36719. }
  36720. rightBandwidth = rightBandwidth || window$1.Number.MAX_VALUE;
  36721. return leftBandwidth - rightBandwidth;
  36722. };
  36723. /**
  36724. * A comparator function to sort two playlist object by resolution (width).
  36725. *
  36726. * @param {Object} left a media playlist object
  36727. * @param {Object} right a media playlist object
  36728. * @return {number} Greater than zero if the resolution.width attribute of
  36729. * left is greater than the corresponding attribute of right. Less
  36730. * than zero if the resolution.width of right is greater than left and
  36731. * exactly zero if the two are equal.
  36732. */
  36733. const comparePlaylistResolution = function (left, right) {
  36734. let leftWidth;
  36735. let rightWidth;
  36736. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  36737. leftWidth = left.attributes.RESOLUTION.width;
  36738. }
  36739. leftWidth = leftWidth || window$1.Number.MAX_VALUE;
  36740. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  36741. rightWidth = right.attributes.RESOLUTION.width;
  36742. }
  36743. rightWidth = rightWidth || window$1.Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  36744. // have the same media dimensions/ resolution
  36745. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  36746. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  36747. }
  36748. return leftWidth - rightWidth;
  36749. };
  36750. /**
  36751. * Chooses the appropriate media playlist based on bandwidth and player size
  36752. *
  36753. * @param {Object} main
  36754. * Object representation of the main manifest
  36755. * @param {number} playerBandwidth
  36756. * Current calculated bandwidth of the player
  36757. * @param {number} playerWidth
  36758. * Current width of the player element (should account for the device pixel ratio)
  36759. * @param {number} playerHeight
  36760. * Current height of the player element (should account for the device pixel ratio)
  36761. * @param {boolean} limitRenditionByPlayerDimensions
  36762. * True if the player width and height should be used during the selection, false otherwise
  36763. * @param {Object} playlistController
  36764. * the current playlistController object
  36765. * @return {Playlist} the highest bitrate playlist less than the
  36766. * currently detected bandwidth, accounting for some amount of
  36767. * bandwidth variance
  36768. */
  36769. let simpleSelector = function (main, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, playlistController) {
  36770. // If we end up getting called before `main` is available, exit early
  36771. if (!main) {
  36772. return;
  36773. }
  36774. const options = {
  36775. bandwidth: playerBandwidth,
  36776. width: playerWidth,
  36777. height: playerHeight,
  36778. limitRenditionByPlayerDimensions
  36779. };
  36780. let playlists = main.playlists; // if playlist is audio only, select between currently active audio group playlists.
  36781. if (Playlist.isAudioOnly(main)) {
  36782. playlists = playlistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  36783. // at the buttom of this function for debugging.
  36784. options.audioOnly = true;
  36785. } // convert the playlists to an intermediary representation to make comparisons easier
  36786. let sortedPlaylistReps = playlists.map(playlist => {
  36787. let bandwidth;
  36788. const width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  36789. const height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  36790. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  36791. bandwidth = bandwidth || window$1.Number.MAX_VALUE;
  36792. return {
  36793. bandwidth,
  36794. width,
  36795. height,
  36796. playlist
  36797. };
  36798. });
  36799. stableSort(sortedPlaylistReps, (left, right) => left.bandwidth - right.bandwidth); // filter out any playlists that have been excluded due to
  36800. // incompatible configurations
  36801. sortedPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isIncompatible(rep.playlist)); // filter out any playlists that have been disabled manually through the representations
  36802. // api or excluded temporarily due to playback errors.
  36803. let enabledPlaylistReps = sortedPlaylistReps.filter(rep => Playlist.isEnabled(rep.playlist));
  36804. if (!enabledPlaylistReps.length) {
  36805. // if there are no enabled playlists, then they have all been excluded or disabled
  36806. // by the user through the representations api. In this case, ignore exclusion and
  36807. // fallback to what the user wants by using playlists the user has not disabled.
  36808. enabledPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isDisabled(rep.playlist));
  36809. } // filter out any variant that has greater effective bitrate
  36810. // than the current estimated bandwidth
  36811. const bandwidthPlaylistReps = enabledPlaylistReps.filter(rep => rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth);
  36812. let highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  36813. // and then taking the very first element
  36814. 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.
  36815. if (limitRenditionByPlayerDimensions === false) {
  36816. const chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  36817. if (chosenRep && chosenRep.playlist) {
  36818. let type = 'sortedPlaylistReps';
  36819. if (bandwidthBestRep) {
  36820. type = 'bandwidthBestRep';
  36821. }
  36822. if (enabledPlaylistReps[0]) {
  36823. type = 'enabledPlaylistReps';
  36824. }
  36825. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  36826. return chosenRep.playlist;
  36827. }
  36828. logFn('could not choose a playlist with options', options);
  36829. return null;
  36830. } // filter out playlists without resolution information
  36831. const haveResolution = bandwidthPlaylistReps.filter(rep => rep.width && rep.height); // sort variants by resolution
  36832. stableSort(haveResolution, (left, right) => left.width - right.width); // if we have the exact resolution as the player use it
  36833. const resolutionBestRepList = haveResolution.filter(rep => rep.width === playerWidth && rep.height === playerHeight);
  36834. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  36835. const resolutionBestRep = resolutionBestRepList.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  36836. let resolutionPlusOneList;
  36837. let resolutionPlusOneSmallest;
  36838. let resolutionPlusOneRep; // find the smallest variant that is larger than the player
  36839. // if there is no match of exact resolution
  36840. if (!resolutionBestRep) {
  36841. resolutionPlusOneList = haveResolution.filter(rep => rep.width > playerWidth || rep.height > playerHeight); // find all the variants have the same smallest resolution
  36842. resolutionPlusOneSmallest = resolutionPlusOneList.filter(rep => rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height); // ensure that we also pick the highest bandwidth variant that
  36843. // is just-larger-than the video player
  36844. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  36845. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  36846. }
  36847. let leastPixelDiffRep; // If this selector proves to be better than others,
  36848. // resolutionPlusOneRep and resolutionBestRep and all
  36849. // the code involving them should be removed.
  36850. if (playlistController.leastPixelDiffSelector) {
  36851. // find the variant that is closest to the player's pixel size
  36852. const leastPixelDiffList = haveResolution.map(rep => {
  36853. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  36854. return rep;
  36855. }); // get the highest bandwidth, closest resolution playlist
  36856. stableSort(leastPixelDiffList, (left, right) => {
  36857. // sort by highest bandwidth if pixelDiff is the same
  36858. if (left.pixelDiff === right.pixelDiff) {
  36859. return right.bandwidth - left.bandwidth;
  36860. }
  36861. return left.pixelDiff - right.pixelDiff;
  36862. });
  36863. leastPixelDiffRep = leastPixelDiffList[0];
  36864. } // fallback chain of variants
  36865. const chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  36866. if (chosenRep && chosenRep.playlist) {
  36867. let type = 'sortedPlaylistReps';
  36868. if (leastPixelDiffRep) {
  36869. type = 'leastPixelDiffRep';
  36870. } else if (resolutionPlusOneRep) {
  36871. type = 'resolutionPlusOneRep';
  36872. } else if (resolutionBestRep) {
  36873. type = 'resolutionBestRep';
  36874. } else if (bandwidthBestRep) {
  36875. type = 'bandwidthBestRep';
  36876. } else if (enabledPlaylistReps[0]) {
  36877. type = 'enabledPlaylistReps';
  36878. }
  36879. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  36880. return chosenRep.playlist;
  36881. }
  36882. logFn('could not choose a playlist with options', options);
  36883. return null;
  36884. };
  36885. /**
  36886. * Chooses the appropriate media playlist based on the most recent
  36887. * bandwidth estimate and the player size.
  36888. *
  36889. * Expects to be called within the context of an instance of VhsHandler
  36890. *
  36891. * @return {Playlist} the highest bitrate playlist less than the
  36892. * currently detected bandwidth, accounting for some amount of
  36893. * bandwidth variance
  36894. */
  36895. const lastBandwidthSelector = function () {
  36896. const pixelRatio = this.useDevicePixelRatio ? window$1.devicePixelRatio || 1 : 1;
  36897. 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_);
  36898. };
  36899. /**
  36900. * Chooses the appropriate media playlist based on an
  36901. * exponential-weighted moving average of the bandwidth after
  36902. * filtering for player size.
  36903. *
  36904. * Expects to be called within the context of an instance of VhsHandler
  36905. *
  36906. * @param {number} decay - a number between 0 and 1. Higher values of
  36907. * this parameter will cause previous bandwidth estimates to lose
  36908. * significance more quickly.
  36909. * @return {Function} a function which can be invoked to create a new
  36910. * playlist selector function.
  36911. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  36912. */
  36913. const movingAverageBandwidthSelector = function (decay) {
  36914. let average = -1;
  36915. let lastSystemBandwidth = -1;
  36916. if (decay < 0 || decay > 1) {
  36917. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  36918. }
  36919. return function () {
  36920. const pixelRatio = this.useDevicePixelRatio ? window$1.devicePixelRatio || 1 : 1;
  36921. if (average < 0) {
  36922. average = this.systemBandwidth;
  36923. lastSystemBandwidth = this.systemBandwidth;
  36924. } // stop the average value from decaying for every 250ms
  36925. // when the systemBandwidth is constant
  36926. // and
  36927. // stop average from setting to a very low value when the
  36928. // systemBandwidth becomes 0 in case of chunk cancellation
  36929. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  36930. average = decay * this.systemBandwidth + (1 - decay) * average;
  36931. lastSystemBandwidth = this.systemBandwidth;
  36932. }
  36933. 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_);
  36934. };
  36935. };
  36936. /**
  36937. * Chooses the appropriate media playlist based on the potential to rebuffer
  36938. *
  36939. * @param {Object} settings
  36940. * Object of information required to use this selector
  36941. * @param {Object} settings.main
  36942. * Object representation of the main manifest
  36943. * @param {number} settings.currentTime
  36944. * The current time of the player
  36945. * @param {number} settings.bandwidth
  36946. * Current measured bandwidth
  36947. * @param {number} settings.duration
  36948. * Duration of the media
  36949. * @param {number} settings.segmentDuration
  36950. * Segment duration to be used in round trip time calculations
  36951. * @param {number} settings.timeUntilRebuffer
  36952. * Time left in seconds until the player has to rebuffer
  36953. * @param {number} settings.currentTimeline
  36954. * The current timeline segments are being loaded from
  36955. * @param {SyncController} settings.syncController
  36956. * SyncController for determining if we have a sync point for a given playlist
  36957. * @return {Object|null}
  36958. * {Object} return.playlist
  36959. * The highest bandwidth playlist with the least amount of rebuffering
  36960. * {Number} return.rebufferingImpact
  36961. * The amount of time in seconds switching to this playlist will rebuffer. A
  36962. * negative value means that switching will cause zero rebuffering.
  36963. */
  36964. const minRebufferMaxBandwidthSelector = function (settings) {
  36965. const {
  36966. main,
  36967. currentTime,
  36968. bandwidth,
  36969. duration,
  36970. segmentDuration,
  36971. timeUntilRebuffer,
  36972. currentTimeline,
  36973. syncController
  36974. } = settings; // filter out any playlists that have been excluded due to
  36975. // incompatible configurations
  36976. const compatiblePlaylists = main.playlists.filter(playlist => !Playlist.isIncompatible(playlist)); // filter out any playlists that have been disabled manually through the representations
  36977. // api or excluded temporarily due to playback errors.
  36978. let enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  36979. if (!enabledPlaylists.length) {
  36980. // if there are no enabled playlists, then they have all been excluded or disabled
  36981. // by the user through the representations api. In this case, ignore exclusion and
  36982. // fallback to what the user wants by using playlists the user has not disabled.
  36983. enabledPlaylists = compatiblePlaylists.filter(playlist => !Playlist.isDisabled(playlist));
  36984. }
  36985. const bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  36986. const rebufferingEstimates = bandwidthPlaylists.map(playlist => {
  36987. const syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  36988. // sync request first. This will double the request time
  36989. const numRequests = syncPoint ? 1 : 2;
  36990. const requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  36991. const rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  36992. return {
  36993. playlist,
  36994. rebufferingImpact
  36995. };
  36996. });
  36997. const noRebufferingPlaylists = rebufferingEstimates.filter(estimate => estimate.rebufferingImpact <= 0); // Sort by bandwidth DESC
  36998. stableSort(noRebufferingPlaylists, (a, b) => comparePlaylistBandwidth(b.playlist, a.playlist));
  36999. if (noRebufferingPlaylists.length) {
  37000. return noRebufferingPlaylists[0];
  37001. }
  37002. stableSort(rebufferingEstimates, (a, b) => a.rebufferingImpact - b.rebufferingImpact);
  37003. return rebufferingEstimates[0] || null;
  37004. };
  37005. /**
  37006. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  37007. * one with video. If no renditions with video exist, return the lowest audio rendition.
  37008. *
  37009. * Expects to be called within the context of an instance of VhsHandler
  37010. *
  37011. * @return {Object|null}
  37012. * {Object} return.playlist
  37013. * The lowest bitrate playlist that contains a video codec. If no such rendition
  37014. * exists pick the lowest audio rendition.
  37015. */
  37016. const lowestBitrateCompatibleVariantSelector = function () {
  37017. // filter out any playlists that have been excluded due to
  37018. // incompatible configurations or playback errors
  37019. const playlists = this.playlists.main.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  37020. stableSort(playlists, (a, b) => comparePlaylistBandwidth(a, b)); // Parse and assume that playlists with no video codec have no video
  37021. // (this is not necessarily true, although it is generally true).
  37022. //
  37023. // If an entire manifest has no valid videos everything will get filtered
  37024. // out.
  37025. const playlistsWithVideo = playlists.filter(playlist => !!codecsForPlaylist(this.playlists.main, playlist).video);
  37026. return playlistsWithVideo[0] || null;
  37027. };
  37028. /**
  37029. * Combine all segments into a single Uint8Array
  37030. *
  37031. * @param {Object} segmentObj
  37032. * @return {Uint8Array} concatenated bytes
  37033. * @private
  37034. */
  37035. const concatSegments = segmentObj => {
  37036. let offset = 0;
  37037. let tempBuffer;
  37038. if (segmentObj.bytes) {
  37039. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  37040. segmentObj.segments.forEach(segment => {
  37041. tempBuffer.set(segment, offset);
  37042. offset += segment.byteLength;
  37043. });
  37044. }
  37045. return tempBuffer;
  37046. };
  37047. /**
  37048. * @file text-tracks.js
  37049. */
  37050. /**
  37051. * Create captions text tracks on video.js if they do not exist
  37052. *
  37053. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  37054. * @param {Object} tech the video.js tech
  37055. * @param {Object} captionStream the caption stream to create
  37056. * @private
  37057. */
  37058. const createCaptionsTrackIfNotExists = function (inbandTextTracks, tech, captionStream) {
  37059. if (!inbandTextTracks[captionStream]) {
  37060. tech.trigger({
  37061. type: 'usage',
  37062. name: 'vhs-608'
  37063. });
  37064. let instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  37065. if (/^cc708_/.test(captionStream)) {
  37066. instreamId = 'SERVICE' + captionStream.split('_')[1];
  37067. }
  37068. const track = tech.textTracks().getTrackById(instreamId);
  37069. if (track) {
  37070. // Resuse an existing track with a CC# id because this was
  37071. // very likely created by videojs-contrib-hls from information
  37072. // in the m3u8 for us to use
  37073. inbandTextTracks[captionStream] = track;
  37074. } else {
  37075. // This section gets called when we have caption services that aren't specified in the manifest.
  37076. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  37077. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  37078. let label = captionStream;
  37079. let language = captionStream;
  37080. let def = false;
  37081. const captionService = captionServices[instreamId];
  37082. if (captionService) {
  37083. label = captionService.label;
  37084. language = captionService.language;
  37085. def = captionService.default;
  37086. } // Otherwise, create a track with the default `CC#` label and
  37087. // without a language
  37088. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  37089. kind: 'captions',
  37090. id: instreamId,
  37091. // TODO: investigate why this doesn't seem to turn the caption on by default
  37092. default: def,
  37093. label,
  37094. language
  37095. }, false).track;
  37096. }
  37097. }
  37098. };
  37099. /**
  37100. * Add caption text track data to a source handler given an array of captions
  37101. *
  37102. * @param {Object}
  37103. * @param {Object} inbandTextTracks the inband text tracks
  37104. * @param {number} timestampOffset the timestamp offset of the source buffer
  37105. * @param {Array} captionArray an array of caption data
  37106. * @private
  37107. */
  37108. const addCaptionData = function ({
  37109. inbandTextTracks,
  37110. captionArray,
  37111. timestampOffset
  37112. }) {
  37113. if (!captionArray) {
  37114. return;
  37115. }
  37116. const Cue = window$1.WebKitDataCue || window$1.VTTCue;
  37117. captionArray.forEach(caption => {
  37118. const track = caption.stream;
  37119. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  37120. });
  37121. };
  37122. /**
  37123. * Define properties on a cue for backwards compatability,
  37124. * but warn the user that the way that they are using it
  37125. * is depricated and will be removed at a later date.
  37126. *
  37127. * @param {Cue} cue the cue to add the properties on
  37128. * @private
  37129. */
  37130. const deprecateOldCue = function (cue) {
  37131. Object.defineProperties(cue.frame, {
  37132. id: {
  37133. get() {
  37134. videojs.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  37135. return cue.value.key;
  37136. }
  37137. },
  37138. value: {
  37139. get() {
  37140. videojs.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  37141. return cue.value.data;
  37142. }
  37143. },
  37144. privateData: {
  37145. get() {
  37146. videojs.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  37147. return cue.value.data;
  37148. }
  37149. }
  37150. });
  37151. };
  37152. /**
  37153. * Add metadata text track data to a source handler given an array of metadata
  37154. *
  37155. * @param {Object}
  37156. * @param {Object} inbandTextTracks the inband text tracks
  37157. * @param {Array} metadataArray an array of meta data
  37158. * @param {number} timestampOffset the timestamp offset of the source buffer
  37159. * @param {number} videoDuration the duration of the video
  37160. * @private
  37161. */
  37162. const addMetadata = ({
  37163. inbandTextTracks,
  37164. metadataArray,
  37165. timestampOffset,
  37166. videoDuration
  37167. }) => {
  37168. if (!metadataArray) {
  37169. return;
  37170. }
  37171. const Cue = window$1.WebKitDataCue || window$1.VTTCue;
  37172. const metadataTrack = inbandTextTracks.metadataTrack_;
  37173. if (!metadataTrack) {
  37174. return;
  37175. }
  37176. metadataArray.forEach(metadata => {
  37177. const time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  37178. // ignore this bit of metadata.
  37179. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  37180. // which is the "Title/Songname/Content description" frame
  37181. if (typeof time !== 'number' || window$1.isNaN(time) || time < 0 || !(time < Infinity)) {
  37182. return;
  37183. }
  37184. metadata.frames.forEach(frame => {
  37185. const cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  37186. cue.frame = frame;
  37187. cue.value = frame;
  37188. deprecateOldCue(cue);
  37189. metadataTrack.addCue(cue);
  37190. });
  37191. });
  37192. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  37193. return;
  37194. } // Updating the metadeta cues so that
  37195. // the endTime of each cue is the startTime of the next cue
  37196. // the endTime of last cue is the duration of the video
  37197. const cues = metadataTrack.cues;
  37198. const cuesArray = []; // Create a copy of the TextTrackCueList...
  37199. // ...disregarding cues with a falsey value
  37200. for (let i = 0; i < cues.length; i++) {
  37201. if (cues[i]) {
  37202. cuesArray.push(cues[i]);
  37203. }
  37204. } // Group cues by their startTime value
  37205. const cuesGroupedByStartTime = cuesArray.reduce((obj, cue) => {
  37206. const timeSlot = obj[cue.startTime] || [];
  37207. timeSlot.push(cue);
  37208. obj[cue.startTime] = timeSlot;
  37209. return obj;
  37210. }, {}); // Sort startTimes by ascending order
  37211. const sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort((a, b) => Number(a) - Number(b)); // Map each cue group's endTime to the next group's startTime
  37212. sortedStartTimes.forEach((startTime, idx) => {
  37213. const cueGroup = cuesGroupedByStartTime[startTime];
  37214. const nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
  37215. cueGroup.forEach(cue => {
  37216. cue.endTime = nextTime;
  37217. });
  37218. });
  37219. };
  37220. /**
  37221. * Create metadata text track on video.js if it does not exist
  37222. *
  37223. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  37224. * @param {string} dispatchType the inband metadata track dispatch type
  37225. * @param {Object} tech the video.js tech
  37226. * @private
  37227. */
  37228. const createMetadataTrackIfNotExists = (inbandTextTracks, dispatchType, tech) => {
  37229. if (inbandTextTracks.metadataTrack_) {
  37230. return;
  37231. }
  37232. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  37233. kind: 'metadata',
  37234. label: 'Timed Metadata'
  37235. }, false).track;
  37236. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  37237. };
  37238. /**
  37239. * Remove cues from a track on video.js.
  37240. *
  37241. * @param {Double} start start of where we should remove the cue
  37242. * @param {Double} end end of where the we should remove the cue
  37243. * @param {Object} track the text track to remove the cues from
  37244. * @private
  37245. */
  37246. const removeCuesFromTrack = function (start, end, track) {
  37247. let i;
  37248. let cue;
  37249. if (!track) {
  37250. return;
  37251. }
  37252. if (!track.cues) {
  37253. return;
  37254. }
  37255. i = track.cues.length;
  37256. while (i--) {
  37257. cue = track.cues[i]; // Remove any cue within the provided start and end time
  37258. if (cue.startTime >= start && cue.endTime <= end) {
  37259. track.removeCue(cue);
  37260. }
  37261. }
  37262. };
  37263. /**
  37264. * Remove duplicate cues from a track on video.js (a cue is considered a
  37265. * duplicate if it has the same time interval and text as another)
  37266. *
  37267. * @param {Object} track the text track to remove the duplicate cues from
  37268. * @private
  37269. */
  37270. const removeDuplicateCuesFromTrack = function (track) {
  37271. const cues = track.cues;
  37272. if (!cues) {
  37273. return;
  37274. }
  37275. for (let i = 0; i < cues.length; i++) {
  37276. const duplicates = [];
  37277. let occurrences = 0;
  37278. for (let j = 0; j < cues.length; j++) {
  37279. if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
  37280. occurrences++;
  37281. if (occurrences > 1) {
  37282. duplicates.push(cues[j]);
  37283. }
  37284. }
  37285. }
  37286. if (duplicates.length) {
  37287. duplicates.forEach(dupe => track.removeCue(dupe));
  37288. }
  37289. }
  37290. };
  37291. /**
  37292. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  37293. * front of current time.
  37294. *
  37295. * @param {Array} buffer
  37296. * The current buffer of gop information
  37297. * @param {number} currentTime
  37298. * The current time
  37299. * @param {Double} mapping
  37300. * Offset to map display time to stream presentation time
  37301. * @return {Array}
  37302. * List of gops considered safe to append over
  37303. */
  37304. const gopsSafeToAlignWith = (buffer, currentTime, mapping) => {
  37305. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  37306. return [];
  37307. } // pts value for current time + 3 seconds to give a bit more wiggle room
  37308. const currentTimePts = Math.ceil((currentTime - mapping + 3) * ONE_SECOND_IN_TS);
  37309. let i;
  37310. for (i = 0; i < buffer.length; i++) {
  37311. if (buffer[i].pts > currentTimePts) {
  37312. break;
  37313. }
  37314. }
  37315. return buffer.slice(i);
  37316. };
  37317. /**
  37318. * Appends gop information (timing and byteLength) received by the transmuxer for the
  37319. * gops appended in the last call to appendBuffer
  37320. *
  37321. * @param {Array} buffer
  37322. * The current buffer of gop information
  37323. * @param {Array} gops
  37324. * List of new gop information
  37325. * @param {boolean} replace
  37326. * If true, replace the buffer with the new gop information. If false, append the
  37327. * new gop information to the buffer in the right location of time.
  37328. * @return {Array}
  37329. * Updated list of gop information
  37330. */
  37331. const updateGopBuffer = (buffer, gops, replace) => {
  37332. if (!gops.length) {
  37333. return buffer;
  37334. }
  37335. if (replace) {
  37336. // If we are in safe append mode, then completely overwrite the gop buffer
  37337. // with the most recent appeneded data. This will make sure that when appending
  37338. // future segments, we only try to align with gops that are both ahead of current
  37339. // time and in the last segment appended.
  37340. return gops.slice();
  37341. }
  37342. const start = gops[0].pts;
  37343. let i = 0;
  37344. for (i; i < buffer.length; i++) {
  37345. if (buffer[i].pts >= start) {
  37346. break;
  37347. }
  37348. }
  37349. return buffer.slice(0, i).concat(gops);
  37350. };
  37351. /**
  37352. * Removes gop information in buffer that overlaps with provided start and end
  37353. *
  37354. * @param {Array} buffer
  37355. * The current buffer of gop information
  37356. * @param {Double} start
  37357. * position to start the remove at
  37358. * @param {Double} end
  37359. * position to end the remove at
  37360. * @param {Double} mapping
  37361. * Offset to map display time to stream presentation time
  37362. */
  37363. const removeGopBuffer = (buffer, start, end, mapping) => {
  37364. const startPts = Math.ceil((start - mapping) * ONE_SECOND_IN_TS);
  37365. const endPts = Math.ceil((end - mapping) * ONE_SECOND_IN_TS);
  37366. const updatedBuffer = buffer.slice();
  37367. let i = buffer.length;
  37368. while (i--) {
  37369. if (buffer[i].pts <= endPts) {
  37370. break;
  37371. }
  37372. }
  37373. if (i === -1) {
  37374. // no removal because end of remove range is before start of buffer
  37375. return updatedBuffer;
  37376. }
  37377. let j = i + 1;
  37378. while (j--) {
  37379. if (buffer[j].pts <= startPts) {
  37380. break;
  37381. }
  37382. } // clamp remove range start to 0 index
  37383. j = Math.max(j, 0);
  37384. updatedBuffer.splice(j, i - j + 1);
  37385. return updatedBuffer;
  37386. };
  37387. const shallowEqual = function (a, b) {
  37388. // if both are undefined
  37389. // or one or the other is undefined
  37390. // they are not equal
  37391. if (!a && !b || !a && b || a && !b) {
  37392. return false;
  37393. } // they are the same object and thus, equal
  37394. if (a === b) {
  37395. return true;
  37396. } // sort keys so we can make sure they have
  37397. // all the same keys later.
  37398. const akeys = Object.keys(a).sort();
  37399. const bkeys = Object.keys(b).sort(); // different number of keys, not equal
  37400. if (akeys.length !== bkeys.length) {
  37401. return false;
  37402. }
  37403. for (let i = 0; i < akeys.length; i++) {
  37404. const key = akeys[i]; // different sorted keys, not equal
  37405. if (key !== bkeys[i]) {
  37406. return false;
  37407. } // different values, not equal
  37408. if (a[key] !== b[key]) {
  37409. return false;
  37410. }
  37411. }
  37412. return true;
  37413. };
  37414. // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  37415. const QUOTA_EXCEEDED_ERR = 22;
  37416. /**
  37417. * The segment loader has no recourse except to fetch a segment in the
  37418. * current playlist and use the internal timestamps in that segment to
  37419. * generate a syncPoint. This function returns a good candidate index
  37420. * for that process.
  37421. *
  37422. * @param {Array} segments - the segments array from a playlist.
  37423. * @return {number} An index of a segment from the playlist to load
  37424. */
  37425. const getSyncSegmentCandidate = function (currentTimeline, segments, targetTime) {
  37426. segments = segments || [];
  37427. const timelineSegments = [];
  37428. let time = 0;
  37429. for (let i = 0; i < segments.length; i++) {
  37430. const segment = segments[i];
  37431. if (currentTimeline === segment.timeline) {
  37432. timelineSegments.push(i);
  37433. time += segment.duration;
  37434. if (time > targetTime) {
  37435. return i;
  37436. }
  37437. }
  37438. }
  37439. if (timelineSegments.length === 0) {
  37440. return 0;
  37441. } // default to the last timeline segment
  37442. return timelineSegments[timelineSegments.length - 1];
  37443. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  37444. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  37445. // as a start to prevent any potential issues with removing content too close to the
  37446. // playhead.
  37447. const MIN_BACK_BUFFER = 1; // in ms
  37448. const CHECK_BUFFER_DELAY = 500;
  37449. const finite = num => typeof num === 'number' && isFinite(num); // With most content hovering around 30fps, if a segment has a duration less than a half
  37450. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  37451. // not accurately reflect the rest of the content.
  37452. const MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  37453. const illegalMediaSwitch = (loaderType, startingMedia, trackInfo) => {
  37454. // Although these checks should most likely cover non 'main' types, for now it narrows
  37455. // the scope of our checks.
  37456. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  37457. return null;
  37458. }
  37459. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  37460. return 'Neither audio nor video found in segment.';
  37461. }
  37462. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  37463. 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.';
  37464. }
  37465. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  37466. 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.';
  37467. }
  37468. return null;
  37469. };
  37470. /**
  37471. * Calculates a time value that is safe to remove from the back buffer without interrupting
  37472. * playback.
  37473. *
  37474. * @param {TimeRange} seekable
  37475. * The current seekable range
  37476. * @param {number} currentTime
  37477. * The current time of the player
  37478. * @param {number} targetDuration
  37479. * The target duration of the current playlist
  37480. * @return {number}
  37481. * Time that is safe to remove from the back buffer without interrupting playback
  37482. */
  37483. const safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {
  37484. // 30 seconds before the playhead provides a safe default for trimming.
  37485. //
  37486. // Choosing a reasonable default is particularly important for high bitrate content and
  37487. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  37488. // throw an APPEND_BUFFER_ERR.
  37489. let trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  37490. if (seekable.length) {
  37491. // Some live playlists may have a shorter window of content than the full allowed back
  37492. // buffer. For these playlists, don't save content that's no longer within the window.
  37493. trimTime = Math.max(trimTime, seekable.start(0));
  37494. } // Don't remove within target duration of the current time to avoid the possibility of
  37495. // removing the GOP currently being played, as removing it can cause playback stalls.
  37496. const maxTrimTime = currentTime - targetDuration;
  37497. return Math.min(maxTrimTime, trimTime);
  37498. };
  37499. const segmentInfoString = segmentInfo => {
  37500. const {
  37501. startOfSegment,
  37502. duration,
  37503. segment,
  37504. part,
  37505. playlist: {
  37506. mediaSequence: seq,
  37507. id,
  37508. segments = []
  37509. },
  37510. mediaIndex: index,
  37511. partIndex,
  37512. timeline
  37513. } = segmentInfo;
  37514. const segmentLen = segments.length - 1;
  37515. let selection = 'mediaIndex/partIndex increment';
  37516. if (segmentInfo.getMediaInfoForTime) {
  37517. selection = `getMediaInfoForTime (${segmentInfo.getMediaInfoForTime})`;
  37518. } else if (segmentInfo.isSyncRequest) {
  37519. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  37520. }
  37521. if (segmentInfo.independent) {
  37522. selection += ` with independent ${segmentInfo.independent}`;
  37523. }
  37524. const hasPartIndex = typeof partIndex === 'number';
  37525. const name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  37526. const zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  37527. preloadSegment: segment
  37528. }) - 1 : 0;
  37529. 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}]`;
  37530. };
  37531. const timingInfoPropertyForMedia = mediaType => `${mediaType}TimingInfo`;
  37532. /**
  37533. * Returns the timestamp offset to use for the segment.
  37534. *
  37535. * @param {number} segmentTimeline
  37536. * The timeline of the segment
  37537. * @param {number} currentTimeline
  37538. * The timeline currently being followed by the loader
  37539. * @param {number} startOfSegment
  37540. * The estimated segment start
  37541. * @param {TimeRange[]} buffered
  37542. * The loader's buffer
  37543. * @param {boolean} overrideCheck
  37544. * If true, no checks are made to see if the timestamp offset value should be set,
  37545. * but sets it directly to a value.
  37546. *
  37547. * @return {number|null}
  37548. * Either a number representing a new timestamp offset, or null if the segment is
  37549. * part of the same timeline
  37550. */
  37551. const timestampOffsetForSegment = ({
  37552. segmentTimeline,
  37553. currentTimeline,
  37554. startOfSegment,
  37555. buffered,
  37556. overrideCheck
  37557. }) => {
  37558. // Check to see if we are crossing a discontinuity to see if we need to set the
  37559. // timestamp offset on the transmuxer and source buffer.
  37560. //
  37561. // Previously, we changed the timestampOffset if the start of this segment was less than
  37562. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  37563. // behavior, especially around long running live streams.
  37564. if (!overrideCheck && segmentTimeline === currentTimeline) {
  37565. return null;
  37566. } // When changing renditions, it's possible to request a segment on an older timeline. For
  37567. // instance, given two renditions with the following:
  37568. //
  37569. // #EXTINF:10
  37570. // segment1
  37571. // #EXT-X-DISCONTINUITY
  37572. // #EXTINF:10
  37573. // segment2
  37574. // #EXTINF:10
  37575. // segment3
  37576. //
  37577. // And the current player state:
  37578. //
  37579. // current time: 8
  37580. // buffer: 0 => 20
  37581. //
  37582. // The next segment on the current rendition would be segment3, filling the buffer from
  37583. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  37584. // then the next segment to be requested will be segment1 from the new rendition in
  37585. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  37586. // content (since it would position segment1 of the new rendition starting at 20s). This
  37587. // case can be identified when the new segment's timeline is a prior value. Instead of
  37588. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  37589. // more accurate to the actual start time of the segment.
  37590. if (segmentTimeline < currentTimeline) {
  37591. return startOfSegment;
  37592. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  37593. // value uses the end of the last segment if it is available. While this value
  37594. // should often be correct, it's better to rely on the buffered end, as the new
  37595. // content post discontinuity should line up with the buffered end as if it were
  37596. // time 0 for the new content.
  37597. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  37598. };
  37599. /**
  37600. * Returns whether or not the loader should wait for a timeline change from the timeline
  37601. * change controller before processing the segment.
  37602. *
  37603. * Primary timing in VHS goes by video. This is different from most media players, as
  37604. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  37605. * will continue to use video as the primary timing source, due to the current logic and
  37606. * expectations built around it.
  37607. * Since the timing follows video, in order to maintain sync, the video loader is
  37608. * responsible for setting both audio and video source buffer timestamp offsets.
  37609. *
  37610. * Setting different values for audio and video source buffers could lead to
  37611. * desyncing. The following examples demonstrate some of the situations where this
  37612. * distinction is important. Note that all of these cases involve demuxed content. When
  37613. * content is muxed, the audio and video are packaged together, therefore syncing
  37614. * separate media playlists is not an issue.
  37615. *
  37616. * CASE 1: Audio prepares to load a new timeline before video:
  37617. *
  37618. * Timeline: 0 1
  37619. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37620. * Audio Loader: ^
  37621. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37622. * Video Loader ^
  37623. *
  37624. * In the above example, the audio loader is preparing to load the 6th segment, the first
  37625. * after a discontinuity, while the video loader is still loading the 5th segment, before
  37626. * the discontinuity.
  37627. *
  37628. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  37629. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  37630. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  37631. * the audio loader must provide the audioAppendStart value to trim the content in the
  37632. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  37633. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  37634. * segment until that value is provided.
  37635. *
  37636. * CASE 2: Video prepares to load a new timeline before audio:
  37637. *
  37638. * Timeline: 0 1
  37639. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37640. * Audio Loader: ^
  37641. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37642. * Video Loader ^
  37643. *
  37644. * In the above example, the video loader is preparing to load the 6th segment, the first
  37645. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  37646. * the discontinuity.
  37647. *
  37648. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  37649. * segment is loaded and processed, both the video and audio timestamp offsets will be
  37650. * set, since video is used as the primary timing source. This is to ensure content lines
  37651. * up appropriately, as any modifications to the video timing are reflected by audio when
  37652. * the video loader sets the audio and video timestamp offsets to the same value. However,
  37653. * setting the timestamp offset for audio before audio has had a chance to change
  37654. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  37655. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  37656. *
  37657. * CASE 3: When seeking, audio prepares to load a new timeline before video
  37658. *
  37659. * Timeline: 0 1
  37660. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37661. * Audio Loader: ^
  37662. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37663. * Video Loader ^
  37664. *
  37665. * In the above example, both audio and video loaders are loading segments from timeline
  37666. * 0, but imagine that the seek originated from timeline 1.
  37667. *
  37668. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  37669. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  37670. * must wait for the video loader to load its segment and update both the audio and video
  37671. * timestamp offsets before it may load and append its own segment. This is the case
  37672. * whether the seek results in a mismatched segment request (e.g., the audio loader
  37673. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  37674. * loaders choose to load the same segment index from each playlist, as the segments may
  37675. * not be aligned perfectly, even for matching segment indexes.
  37676. *
  37677. * @param {Object} timelinechangeController
  37678. * @param {number} currentTimeline
  37679. * The timeline currently being followed by the loader
  37680. * @param {number} segmentTimeline
  37681. * The timeline of the segment being loaded
  37682. * @param {('main'|'audio')} loaderType
  37683. * The loader type
  37684. * @param {boolean} audioDisabled
  37685. * Whether the audio is disabled for the loader. This should only be true when the
  37686. * loader may have muxed audio in its segment, but should not append it, e.g., for
  37687. * the main loader when an alternate audio playlist is active.
  37688. *
  37689. * @return {boolean}
  37690. * Whether the loader should wait for a timeline change from the timeline change
  37691. * controller before processing the segment
  37692. */
  37693. const shouldWaitForTimelineChange = ({
  37694. timelineChangeController,
  37695. currentTimeline,
  37696. segmentTimeline,
  37697. loaderType,
  37698. audioDisabled
  37699. }) => {
  37700. if (currentTimeline === segmentTimeline) {
  37701. return false;
  37702. }
  37703. if (loaderType === 'audio') {
  37704. const lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  37705. type: 'main'
  37706. }); // Audio loader should wait if:
  37707. //
  37708. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  37709. // * main hasn't yet changed to the timeline audio is looking to load
  37710. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  37711. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  37712. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  37713. // loader's segments (or the content is audio/video only and handled by the main
  37714. // loader).
  37715. if (loaderType === 'main' && audioDisabled) {
  37716. const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  37717. type: 'audio'
  37718. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  37719. // change to the current timeline.
  37720. //
  37721. // Since the main loader is responsible for setting the timestamp offset for both
  37722. // audio and video, the main loader must wait for audio to be about to change to its
  37723. // timeline before setting the offset, otherwise, if audio is behind in loading,
  37724. // segments from the previous timeline would be adjusted by the new timestamp offset.
  37725. //
  37726. // This requirement means that video will not cross a timeline until the audio is
  37727. // about to cross to it, so that way audio and video will always cross the timeline
  37728. // together.
  37729. //
  37730. // In addition to normal timeline changes, these rules also apply to the start of a
  37731. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  37732. // that these rules apply to the first timeline change because if they did not, it's
  37733. // possible that the main loader will cross two timelines before the audio loader has
  37734. // crossed one. Logic may be implemented to handle the startup as a special case, but
  37735. // it's easier to simply treat all timeline changes the same.
  37736. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  37737. return false;
  37738. }
  37739. return true;
  37740. }
  37741. return false;
  37742. };
  37743. const mediaDuration = timingInfos => {
  37744. let maxDuration = 0;
  37745. ['video', 'audio'].forEach(function (type) {
  37746. const typeTimingInfo = timingInfos[`${type}TimingInfo`];
  37747. if (!typeTimingInfo) {
  37748. return;
  37749. }
  37750. const {
  37751. start,
  37752. end
  37753. } = typeTimingInfo;
  37754. let duration;
  37755. if (typeof start === 'bigint' || typeof end === 'bigint') {
  37756. duration = window$1.BigInt(end) - window$1.BigInt(start);
  37757. } else if (typeof start === 'number' && typeof end === 'number') {
  37758. duration = end - start;
  37759. }
  37760. if (typeof duration !== 'undefined' && duration > maxDuration) {
  37761. maxDuration = duration;
  37762. }
  37763. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  37764. // as we only need BigInt when we are above that.
  37765. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  37766. maxDuration = Number(maxDuration);
  37767. }
  37768. return maxDuration;
  37769. };
  37770. const segmentTooLong = ({
  37771. segmentDuration,
  37772. maxDuration
  37773. }) => {
  37774. // 0 duration segments are most likely due to metadata only segments or a lack of
  37775. // information.
  37776. if (!segmentDuration) {
  37777. return false;
  37778. } // For HLS:
  37779. //
  37780. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  37781. // The EXTINF duration of each Media Segment in the Playlist
  37782. // file, when rounded to the nearest integer, MUST be less than or equal
  37783. // to the target duration; longer segments can trigger playback stalls
  37784. // or other errors.
  37785. //
  37786. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  37787. // duration. Although that reported duration is occasionally approximate (i.e., not
  37788. // exact), a strict check may report that a segment is too long more often in DASH.
  37789. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  37790. };
  37791. const getTroublesomeSegmentDurationMessage = (segmentInfo, sourceType) => {
  37792. // Right now we aren't following DASH's timing model exactly, so only perform
  37793. // this check for HLS content.
  37794. if (sourceType !== 'hls') {
  37795. return null;
  37796. }
  37797. const segmentDuration = mediaDuration({
  37798. audioTimingInfo: segmentInfo.audioTimingInfo,
  37799. videoTimingInfo: segmentInfo.videoTimingInfo
  37800. }); // Don't report if we lack information.
  37801. //
  37802. // If the segment has a duration of 0 it is either a lack of information or a
  37803. // metadata only segment and shouldn't be reported here.
  37804. if (!segmentDuration) {
  37805. return null;
  37806. }
  37807. const targetDuration = segmentInfo.playlist.targetDuration;
  37808. const isSegmentWayTooLong = segmentTooLong({
  37809. segmentDuration,
  37810. maxDuration: targetDuration * 2
  37811. });
  37812. const isSegmentSlightlyTooLong = segmentTooLong({
  37813. segmentDuration,
  37814. maxDuration: targetDuration
  37815. });
  37816. 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';
  37817. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  37818. return {
  37819. severity: isSegmentWayTooLong ? 'warn' : 'info',
  37820. message: segmentTooLongMessage
  37821. };
  37822. }
  37823. return null;
  37824. };
  37825. /**
  37826. * An object that manages segment loading and appending.
  37827. *
  37828. * @class SegmentLoader
  37829. * @param {Object} options required and optional options
  37830. * @extends videojs.EventTarget
  37831. */
  37832. class SegmentLoader extends videojs.EventTarget {
  37833. constructor(settings, options = {}) {
  37834. super(); // check pre-conditions
  37835. if (!settings) {
  37836. throw new TypeError('Initialization settings are required');
  37837. }
  37838. if (typeof settings.currentTime !== 'function') {
  37839. throw new TypeError('No currentTime getter specified');
  37840. }
  37841. if (!settings.mediaSource) {
  37842. throw new TypeError('No MediaSource specified');
  37843. } // public properties
  37844. this.bandwidth = settings.bandwidth;
  37845. this.throughput = {
  37846. rate: 0,
  37847. count: 0
  37848. };
  37849. this.roundTrip = NaN;
  37850. this.resetStats_();
  37851. this.mediaIndex = null;
  37852. this.partIndex = null; // private settings
  37853. this.hasPlayed_ = settings.hasPlayed;
  37854. this.currentTime_ = settings.currentTime;
  37855. this.seekable_ = settings.seekable;
  37856. this.seeking_ = settings.seeking;
  37857. this.duration_ = settings.duration;
  37858. this.mediaSource_ = settings.mediaSource;
  37859. this.vhs_ = settings.vhs;
  37860. this.loaderType_ = settings.loaderType;
  37861. this.currentMediaInfo_ = void 0;
  37862. this.startingMediaInfo_ = void 0;
  37863. this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  37864. this.goalBufferLength_ = settings.goalBufferLength;
  37865. this.sourceType_ = settings.sourceType;
  37866. this.sourceUpdater_ = settings.sourceUpdater;
  37867. this.inbandTextTracks_ = settings.inbandTextTracks;
  37868. this.state_ = 'INIT';
  37869. this.timelineChangeController_ = settings.timelineChangeController;
  37870. this.shouldSaveSegmentTimingInfo_ = true;
  37871. this.parse708captions_ = settings.parse708captions;
  37872. this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  37873. this.captionServices_ = settings.captionServices;
  37874. this.exactManifestTimings = settings.exactManifestTimings; // private instance variables
  37875. this.checkBufferTimeout_ = null;
  37876. this.error_ = void 0;
  37877. this.currentTimeline_ = -1;
  37878. this.pendingSegment_ = null;
  37879. this.xhrOptions_ = null;
  37880. this.pendingSegments_ = [];
  37881. this.audioDisabled_ = false;
  37882. this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  37883. this.gopBuffer_ = [];
  37884. this.timeMapping_ = 0;
  37885. this.safeAppend_ = videojs.browser.IE_VERSION >= 11;
  37886. this.appendInitSegment_ = {
  37887. audio: true,
  37888. video: true
  37889. };
  37890. this.playlistOfLastInitSegment_ = {
  37891. audio: null,
  37892. video: null
  37893. };
  37894. this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  37895. // information yet to start the loading process (e.g., if the audio loader wants to
  37896. // load a segment from the next timeline but the main loader hasn't yet crossed that
  37897. // timeline), then the load call will be added to the queue until it is ready to be
  37898. // processed.
  37899. this.loadQueue_ = [];
  37900. this.metadataQueue_ = {
  37901. id3: [],
  37902. caption: []
  37903. };
  37904. this.waitingOnRemove_ = false;
  37905. this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  37906. this.activeInitSegmentId_ = null;
  37907. this.initSegments_ = {}; // HLSe playback
  37908. this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  37909. this.keyCache_ = {};
  37910. this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  37911. // between a time in the display time and a segment index within
  37912. // a playlist
  37913. this.syncController_ = settings.syncController;
  37914. this.syncPoint_ = {
  37915. segmentIndex: 0,
  37916. time: 0
  37917. };
  37918. this.transmuxer_ = this.createTransmuxer_();
  37919. this.triggerSyncInfoUpdate_ = () => this.trigger('syncinfoupdate');
  37920. this.syncController_.on('syncinfoupdate', this.triggerSyncInfoUpdate_);
  37921. this.mediaSource_.addEventListener('sourceopen', () => {
  37922. if (!this.isEndOfStream_()) {
  37923. this.ended_ = false;
  37924. }
  37925. }); // ...for determining the fetch location
  37926. this.fetchAtBuffer_ = false;
  37927. this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);
  37928. Object.defineProperty(this, 'state', {
  37929. get() {
  37930. return this.state_;
  37931. },
  37932. set(newState) {
  37933. if (newState !== this.state_) {
  37934. this.logger_(`${this.state_} -> ${newState}`);
  37935. this.state_ = newState;
  37936. this.trigger('statechange');
  37937. }
  37938. }
  37939. });
  37940. this.sourceUpdater_.on('ready', () => {
  37941. if (this.hasEnoughInfoToAppend_()) {
  37942. this.processCallQueue_();
  37943. }
  37944. }); // Only the main loader needs to listen for pending timeline changes, as the main
  37945. // loader should wait for audio to be ready to change its timeline so that both main
  37946. // and audio timelines change together. For more details, see the
  37947. // shouldWaitForTimelineChange function.
  37948. if (this.loaderType_ === 'main') {
  37949. this.timelineChangeController_.on('pendingtimelinechange', () => {
  37950. if (this.hasEnoughInfoToAppend_()) {
  37951. this.processCallQueue_();
  37952. }
  37953. });
  37954. } // The main loader only listens on pending timeline changes, but the audio loader,
  37955. // since its loads follow main, needs to listen on timeline changes. For more details,
  37956. // see the shouldWaitForTimelineChange function.
  37957. if (this.loaderType_ === 'audio') {
  37958. this.timelineChangeController_.on('timelinechange', () => {
  37959. if (this.hasEnoughInfoToLoad_()) {
  37960. this.processLoadQueue_();
  37961. }
  37962. if (this.hasEnoughInfoToAppend_()) {
  37963. this.processCallQueue_();
  37964. }
  37965. });
  37966. }
  37967. }
  37968. createTransmuxer_() {
  37969. return segmentTransmuxer.createTransmuxer({
  37970. remux: false,
  37971. alignGopsAtEnd: this.safeAppend_,
  37972. keepOriginalTimestamps: true,
  37973. parse708captions: this.parse708captions_,
  37974. captionServices: this.captionServices_
  37975. });
  37976. }
  37977. /**
  37978. * reset all of our media stats
  37979. *
  37980. * @private
  37981. */
  37982. resetStats_() {
  37983. this.mediaBytesTransferred = 0;
  37984. this.mediaRequests = 0;
  37985. this.mediaRequestsAborted = 0;
  37986. this.mediaRequestsTimedout = 0;
  37987. this.mediaRequestsErrored = 0;
  37988. this.mediaTransferDuration = 0;
  37989. this.mediaSecondsLoaded = 0;
  37990. this.mediaAppends = 0;
  37991. }
  37992. /**
  37993. * dispose of the SegmentLoader and reset to the default state
  37994. */
  37995. dispose() {
  37996. this.trigger('dispose');
  37997. this.state = 'DISPOSED';
  37998. this.pause();
  37999. this.abort_();
  38000. if (this.transmuxer_) {
  38001. this.transmuxer_.terminate();
  38002. }
  38003. this.resetStats_();
  38004. if (this.checkBufferTimeout_) {
  38005. window$1.clearTimeout(this.checkBufferTimeout_);
  38006. }
  38007. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  38008. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  38009. }
  38010. this.off();
  38011. }
  38012. setAudio(enable) {
  38013. this.audioDisabled_ = !enable;
  38014. if (enable) {
  38015. this.appendInitSegment_.audio = true;
  38016. } else {
  38017. // remove current track audio if it gets disabled
  38018. this.sourceUpdater_.removeAudio(0, this.duration_());
  38019. }
  38020. }
  38021. /**
  38022. * abort anything that is currently doing on with the SegmentLoader
  38023. * and reset to a default state
  38024. */
  38025. abort() {
  38026. if (this.state !== 'WAITING') {
  38027. if (this.pendingSegment_) {
  38028. this.pendingSegment_ = null;
  38029. }
  38030. return;
  38031. }
  38032. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  38033. // since we are no longer "waiting" on any requests. XHR callback is not always run
  38034. // when the request is aborted. This will prevent the loader from being stuck in the
  38035. // WAITING state indefinitely.
  38036. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  38037. // next segment
  38038. if (!this.paused()) {
  38039. this.monitorBuffer_();
  38040. }
  38041. }
  38042. /**
  38043. * abort all pending xhr requests and null any pending segements
  38044. *
  38045. * @private
  38046. */
  38047. abort_() {
  38048. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  38049. this.pendingSegment_.abortRequests();
  38050. } // clear out the segment being processed
  38051. this.pendingSegment_ = null;
  38052. this.callQueue_ = [];
  38053. this.loadQueue_ = [];
  38054. this.metadataQueue_.id3 = [];
  38055. this.metadataQueue_.caption = [];
  38056. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  38057. this.waitingOnRemove_ = false;
  38058. window$1.clearTimeout(this.quotaExceededErrorRetryTimeout_);
  38059. this.quotaExceededErrorRetryTimeout_ = null;
  38060. }
  38061. checkForAbort_(requestId) {
  38062. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  38063. // callback that happens should reset the state to READY so that loading can continue.
  38064. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  38065. this.state = 'READY';
  38066. return true;
  38067. }
  38068. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  38069. return true;
  38070. }
  38071. return false;
  38072. }
  38073. /**
  38074. * set an error on the segment loader and null out any pending segements
  38075. *
  38076. * @param {Error} error the error to set on the SegmentLoader
  38077. * @return {Error} the error that was set or that is currently set
  38078. */
  38079. error(error) {
  38080. if (typeof error !== 'undefined') {
  38081. this.logger_('error occurred:', error);
  38082. this.error_ = error;
  38083. }
  38084. this.pendingSegment_ = null;
  38085. return this.error_;
  38086. }
  38087. endOfStream() {
  38088. this.ended_ = true;
  38089. if (this.transmuxer_) {
  38090. // need to clear out any cached data to prepare for the new segment
  38091. segmentTransmuxer.reset(this.transmuxer_);
  38092. }
  38093. this.gopBuffer_.length = 0;
  38094. this.pause();
  38095. this.trigger('ended');
  38096. }
  38097. /**
  38098. * Indicates which time ranges are buffered
  38099. *
  38100. * @return {TimeRange}
  38101. * TimeRange object representing the current buffered ranges
  38102. */
  38103. buffered_() {
  38104. const trackInfo = this.getMediaInfo_();
  38105. if (!this.sourceUpdater_ || !trackInfo) {
  38106. return createTimeRanges();
  38107. }
  38108. if (this.loaderType_ === 'main') {
  38109. const {
  38110. hasAudio,
  38111. hasVideo,
  38112. isMuxed
  38113. } = trackInfo;
  38114. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  38115. return this.sourceUpdater_.buffered();
  38116. }
  38117. if (hasVideo) {
  38118. return this.sourceUpdater_.videoBuffered();
  38119. }
  38120. } // One case that can be ignored for now is audio only with alt audio,
  38121. // as we don't yet have proper support for that.
  38122. return this.sourceUpdater_.audioBuffered();
  38123. }
  38124. /**
  38125. * Gets and sets init segment for the provided map
  38126. *
  38127. * @param {Object} map
  38128. * The map object representing the init segment to get or set
  38129. * @param {boolean=} set
  38130. * If true, the init segment for the provided map should be saved
  38131. * @return {Object}
  38132. * map object for desired init segment
  38133. */
  38134. initSegmentForMap(map, set = false) {
  38135. if (!map) {
  38136. return null;
  38137. }
  38138. const id = initSegmentId(map);
  38139. let storedMap = this.initSegments_[id];
  38140. if (set && !storedMap && map.bytes) {
  38141. this.initSegments_[id] = storedMap = {
  38142. resolvedUri: map.resolvedUri,
  38143. byterange: map.byterange,
  38144. bytes: map.bytes,
  38145. tracks: map.tracks,
  38146. timescales: map.timescales
  38147. };
  38148. }
  38149. return storedMap || map;
  38150. }
  38151. /**
  38152. * Gets and sets key for the provided key
  38153. *
  38154. * @param {Object} key
  38155. * The key object representing the key to get or set
  38156. * @param {boolean=} set
  38157. * If true, the key for the provided key should be saved
  38158. * @return {Object}
  38159. * Key object for desired key
  38160. */
  38161. segmentKey(key, set = false) {
  38162. if (!key) {
  38163. return null;
  38164. }
  38165. const id = segmentKeyId(key);
  38166. let storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  38167. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  38168. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  38169. this.keyCache_[id] = storedKey = {
  38170. resolvedUri: key.resolvedUri,
  38171. bytes: key.bytes
  38172. };
  38173. }
  38174. const result = {
  38175. resolvedUri: (storedKey || key).resolvedUri
  38176. };
  38177. if (storedKey) {
  38178. result.bytes = storedKey.bytes;
  38179. }
  38180. return result;
  38181. }
  38182. /**
  38183. * Returns true if all configuration required for loading is present, otherwise false.
  38184. *
  38185. * @return {boolean} True if the all configuration is ready for loading
  38186. * @private
  38187. */
  38188. couldBeginLoading_() {
  38189. return this.playlist_ && !this.paused();
  38190. }
  38191. /**
  38192. * load a playlist and start to fill the buffer
  38193. */
  38194. load() {
  38195. // un-pause
  38196. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  38197. // specified
  38198. if (!this.playlist_) {
  38199. return;
  38200. } // if all the configuration is ready, initialize and begin loading
  38201. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  38202. return this.init_();
  38203. } // if we're in the middle of processing a segment already, don't
  38204. // kick off an additional segment request
  38205. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  38206. return;
  38207. }
  38208. this.state = 'READY';
  38209. }
  38210. /**
  38211. * Once all the starting parameters have been specified, begin
  38212. * operation. This method should only be invoked from the INIT
  38213. * state.
  38214. *
  38215. * @private
  38216. */
  38217. init_() {
  38218. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  38219. // audio data from the muxed content should be removed
  38220. this.resetEverything();
  38221. return this.monitorBuffer_();
  38222. }
  38223. /**
  38224. * set a playlist on the segment loader
  38225. *
  38226. * @param {PlaylistLoader} media the playlist to set on the segment loader
  38227. */
  38228. playlist(newPlaylist, options = {}) {
  38229. if (!newPlaylist) {
  38230. return;
  38231. }
  38232. const oldPlaylist = this.playlist_;
  38233. const segmentInfo = this.pendingSegment_;
  38234. this.playlist_ = newPlaylist;
  38235. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  38236. // is always our zero-time so force a sync update each time the playlist
  38237. // is refreshed from the server
  38238. //
  38239. // Use the INIT state to determine if playback has started, as the playlist sync info
  38240. // should be fixed once requests begin (as sync points are generated based on sync
  38241. // info), but not before then.
  38242. if (this.state === 'INIT') {
  38243. newPlaylist.syncInfo = {
  38244. mediaSequence: newPlaylist.mediaSequence,
  38245. time: 0
  38246. }; // Setting the date time mapping means mapping the program date time (if available)
  38247. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  38248. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  38249. // be updated as the playlist is refreshed before the loader starts loading, the
  38250. // program date time mapping needs to be updated as well.
  38251. //
  38252. // This mapping is only done for the main loader because a program date time should
  38253. // map equivalently between playlists.
  38254. if (this.loaderType_ === 'main') {
  38255. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  38256. }
  38257. }
  38258. let oldId = null;
  38259. if (oldPlaylist) {
  38260. if (oldPlaylist.id) {
  38261. oldId = oldPlaylist.id;
  38262. } else if (oldPlaylist.uri) {
  38263. oldId = oldPlaylist.uri;
  38264. }
  38265. }
  38266. this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  38267. // in LIVE, we always want to update with new playlists (including refreshes)
  38268. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  38269. // buffering now
  38270. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  38271. return this.init_();
  38272. }
  38273. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  38274. if (this.mediaIndex !== null) {
  38275. // we must reset/resync the segment loader when we switch renditions and
  38276. // the segment loader is already synced to the previous rendition
  38277. // on playlist changes we want it to be possible to fetch
  38278. // at the buffer for vod but not for live. So we use resetLoader
  38279. // for live and resyncLoader for vod. We want this because
  38280. // if a playlist uses independent and non-independent segments/parts the
  38281. // buffer may not accurately reflect the next segment that we should try
  38282. // downloading.
  38283. if (!newPlaylist.endList) {
  38284. this.resetLoader();
  38285. } else {
  38286. this.resyncLoader();
  38287. }
  38288. }
  38289. this.currentMediaInfo_ = void 0;
  38290. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  38291. return;
  38292. } // we reloaded the same playlist so we are in a live scenario
  38293. // and we will likely need to adjust the mediaIndex
  38294. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  38295. this.logger_(`live window shift [${mediaSequenceDiff}]`); // update the mediaIndex on the SegmentLoader
  38296. // this is important because we can abort a request and this value must be
  38297. // equal to the last appended mediaIndex
  38298. if (this.mediaIndex !== null) {
  38299. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  38300. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  38301. // new playlist was incremented by 1.
  38302. if (this.mediaIndex < 0) {
  38303. this.mediaIndex = null;
  38304. this.partIndex = null;
  38305. } else {
  38306. const segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  38307. // unless parts fell off of the playlist for this segment.
  38308. // In that case we need to reset partIndex and resync
  38309. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  38310. const mediaIndex = this.mediaIndex;
  38311. this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`);
  38312. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  38313. // as the part was dropped from our current playlists segment.
  38314. // The mediaIndex will still be valid so keep that around.
  38315. this.mediaIndex = mediaIndex;
  38316. }
  38317. }
  38318. } // update the mediaIndex on the SegmentInfo object
  38319. // this is important because we will update this.mediaIndex with this value
  38320. // in `handleAppendsDone_` after the segment has been successfully appended
  38321. if (segmentInfo) {
  38322. segmentInfo.mediaIndex -= mediaSequenceDiff;
  38323. if (segmentInfo.mediaIndex < 0) {
  38324. segmentInfo.mediaIndex = null;
  38325. segmentInfo.partIndex = null;
  38326. } else {
  38327. // we need to update the referenced segment so that timing information is
  38328. // saved for the new playlist's segment, however, if the segment fell off the
  38329. // playlist, we can leave the old reference and just lose the timing info
  38330. if (segmentInfo.mediaIndex >= 0) {
  38331. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  38332. }
  38333. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  38334. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  38335. }
  38336. }
  38337. }
  38338. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  38339. }
  38340. /**
  38341. * Prevent the loader from fetching additional segments. If there
  38342. * is a segment request outstanding, it will finish processing
  38343. * before the loader halts. A segment loader can be unpaused by
  38344. * calling load().
  38345. */
  38346. pause() {
  38347. if (this.checkBufferTimeout_) {
  38348. window$1.clearTimeout(this.checkBufferTimeout_);
  38349. this.checkBufferTimeout_ = null;
  38350. }
  38351. }
  38352. /**
  38353. * Returns whether the segment loader is fetching additional
  38354. * segments when given the opportunity. This property can be
  38355. * modified through calls to pause() and load().
  38356. */
  38357. paused() {
  38358. return this.checkBufferTimeout_ === null;
  38359. }
  38360. /**
  38361. * Delete all the buffered data and reset the SegmentLoader
  38362. *
  38363. * @param {Function} [done] an optional callback to be executed when the remove
  38364. * operation is complete
  38365. */
  38366. resetEverything(done) {
  38367. this.ended_ = false;
  38368. this.activeInitSegmentId_ = null;
  38369. this.appendInitSegment_ = {
  38370. audio: true,
  38371. video: true
  38372. };
  38373. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  38374. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  38375. // we then clamp the value to duration if necessary.
  38376. this.remove(0, Infinity, done); // clears fmp4 captions
  38377. if (this.transmuxer_) {
  38378. this.transmuxer_.postMessage({
  38379. action: 'clearAllMp4Captions'
  38380. }); // reset the cache in the transmuxer
  38381. this.transmuxer_.postMessage({
  38382. action: 'reset'
  38383. });
  38384. }
  38385. }
  38386. /**
  38387. * Force the SegmentLoader to resync and start loading around the currentTime instead
  38388. * of starting at the end of the buffer
  38389. *
  38390. * Useful for fast quality changes
  38391. */
  38392. resetLoader() {
  38393. this.fetchAtBuffer_ = false;
  38394. this.resyncLoader();
  38395. }
  38396. /**
  38397. * Force the SegmentLoader to restart synchronization and make a conservative guess
  38398. * before returning to the simple walk-forward method
  38399. */
  38400. resyncLoader() {
  38401. if (this.transmuxer_) {
  38402. // need to clear out any cached data to prepare for the new segment
  38403. segmentTransmuxer.reset(this.transmuxer_);
  38404. }
  38405. this.mediaIndex = null;
  38406. this.partIndex = null;
  38407. this.syncPoint_ = null;
  38408. this.isPendingTimestampOffset_ = false;
  38409. this.callQueue_ = [];
  38410. this.loadQueue_ = [];
  38411. this.metadataQueue_.id3 = [];
  38412. this.metadataQueue_.caption = [];
  38413. this.abort();
  38414. if (this.transmuxer_) {
  38415. this.transmuxer_.postMessage({
  38416. action: 'clearParsedMp4Captions'
  38417. });
  38418. }
  38419. }
  38420. /**
  38421. * Remove any data in the source buffer between start and end times
  38422. *
  38423. * @param {number} start - the start time of the region to remove from the buffer
  38424. * @param {number} end - the end time of the region to remove from the buffer
  38425. * @param {Function} [done] - an optional callback to be executed when the remove
  38426. * @param {boolean} force - force all remove operations to happen
  38427. * operation is complete
  38428. */
  38429. remove(start, end, done = () => {}, force = false) {
  38430. // clamp end to duration if we need to remove everything.
  38431. // This is due to a browser bug that causes issues if we remove to Infinity.
  38432. // videojs/videojs-contrib-hls#1225
  38433. if (end === Infinity) {
  38434. end = this.duration_();
  38435. } // skip removes that would throw an error
  38436. // commonly happens during a rendition switch at the start of a video
  38437. // from start 0 to end 0
  38438. if (end <= start) {
  38439. this.logger_('skipping remove because end ${end} is <= start ${start}');
  38440. return;
  38441. }
  38442. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  38443. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  38444. return;
  38445. } // set it to one to complete this function's removes
  38446. let removesRemaining = 1;
  38447. const removeFinished = () => {
  38448. removesRemaining--;
  38449. if (removesRemaining === 0) {
  38450. done();
  38451. }
  38452. };
  38453. if (force || !this.audioDisabled_) {
  38454. removesRemaining++;
  38455. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  38456. } // While it would be better to only remove video if the main loader has video, this
  38457. // should be safe with audio only as removeVideo will call back even if there's no
  38458. // video buffer.
  38459. //
  38460. // In theory we can check to see if there's video before calling the remove, but in
  38461. // the event that we're switching between renditions and from video to audio only
  38462. // (when we add support for that), we may need to clear the video contents despite
  38463. // what the new media will contain.
  38464. if (force || this.loaderType_ === 'main') {
  38465. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  38466. removesRemaining++;
  38467. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  38468. } // remove any captions and ID3 tags
  38469. for (const track in this.inbandTextTracks_) {
  38470. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  38471. }
  38472. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  38473. removeFinished();
  38474. }
  38475. /**
  38476. * (re-)schedule monitorBufferTick_ to run as soon as possible
  38477. *
  38478. * @private
  38479. */
  38480. monitorBuffer_() {
  38481. if (this.checkBufferTimeout_) {
  38482. window$1.clearTimeout(this.checkBufferTimeout_);
  38483. }
  38484. this.checkBufferTimeout_ = window$1.setTimeout(this.monitorBufferTick_.bind(this), 1);
  38485. }
  38486. /**
  38487. * As long as the SegmentLoader is in the READY state, periodically
  38488. * invoke fillBuffer_().
  38489. *
  38490. * @private
  38491. */
  38492. monitorBufferTick_() {
  38493. if (this.state === 'READY') {
  38494. this.fillBuffer_();
  38495. }
  38496. if (this.checkBufferTimeout_) {
  38497. window$1.clearTimeout(this.checkBufferTimeout_);
  38498. }
  38499. this.checkBufferTimeout_ = window$1.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  38500. }
  38501. /**
  38502. * fill the buffer with segements unless the sourceBuffers are
  38503. * currently updating
  38504. *
  38505. * Note: this function should only ever be called by monitorBuffer_
  38506. * and never directly
  38507. *
  38508. * @private
  38509. */
  38510. fillBuffer_() {
  38511. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  38512. // except when we're ready for the next segment, this check can most likely be removed
  38513. if (this.sourceUpdater_.updating()) {
  38514. return;
  38515. } // see if we need to begin loading immediately
  38516. const segmentInfo = this.chooseNextRequest_();
  38517. if (!segmentInfo) {
  38518. return;
  38519. }
  38520. if (typeof segmentInfo.timestampOffset === 'number') {
  38521. this.isPendingTimestampOffset_ = false;
  38522. this.timelineChangeController_.pendingTimelineChange({
  38523. type: this.loaderType_,
  38524. from: this.currentTimeline_,
  38525. to: segmentInfo.timeline
  38526. });
  38527. }
  38528. this.loadSegment_(segmentInfo);
  38529. }
  38530. /**
  38531. * Determines if we should call endOfStream on the media source based
  38532. * on the state of the buffer or if appened segment was the final
  38533. * segment in the playlist.
  38534. *
  38535. * @param {number} [mediaIndex] the media index of segment we last appended
  38536. * @param {Object} [playlist] a media playlist object
  38537. * @return {boolean} do we need to call endOfStream on the MediaSource
  38538. */
  38539. isEndOfStream_(mediaIndex = this.mediaIndex, playlist = this.playlist_, partIndex = this.partIndex) {
  38540. if (!playlist || !this.mediaSource_) {
  38541. return false;
  38542. }
  38543. const segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  38544. const appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  38545. 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
  38546. // so that MediaSources can trigger the `ended` event when it runs out of
  38547. // buffered data instead of waiting for me
  38548. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  38549. }
  38550. /**
  38551. * Determines what request should be made given current segment loader state.
  38552. *
  38553. * @return {Object} a request object that describes the segment/part to load
  38554. */
  38555. chooseNextRequest_() {
  38556. const buffered = this.buffered_();
  38557. const bufferedEnd = lastBufferedEnd(buffered) || 0;
  38558. const bufferedTime = timeAheadOf(buffered, this.currentTime_());
  38559. const preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  38560. const haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  38561. const segments = this.playlist_.segments; // return no segment if:
  38562. // 1. we don't have segments
  38563. // 2. The video has not yet played and we already downloaded a segment
  38564. // 3. we already have enough buffered time
  38565. if (!segments.length || preloaded || haveEnoughBuffer) {
  38566. return null;
  38567. }
  38568. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
  38569. const next = {
  38570. partIndex: null,
  38571. mediaIndex: null,
  38572. startOfSegment: null,
  38573. playlist: this.playlist_,
  38574. isSyncRequest: Boolean(!this.syncPoint_)
  38575. };
  38576. if (next.isSyncRequest) {
  38577. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  38578. } else if (this.mediaIndex !== null) {
  38579. const segment = segments[this.mediaIndex];
  38580. const partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  38581. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  38582. if (segment.parts && segment.parts[partIndex + 1]) {
  38583. next.mediaIndex = this.mediaIndex;
  38584. next.partIndex = partIndex + 1;
  38585. } else {
  38586. next.mediaIndex = this.mediaIndex + 1;
  38587. }
  38588. } else {
  38589. // Find the segment containing the end of the buffer or current time.
  38590. const {
  38591. segmentIndex,
  38592. startTime,
  38593. partIndex
  38594. } = Playlist.getMediaInfoForTime({
  38595. exactManifestTimings: this.exactManifestTimings,
  38596. playlist: this.playlist_,
  38597. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  38598. startingPartIndex: this.syncPoint_.partIndex,
  38599. startingSegmentIndex: this.syncPoint_.segmentIndex,
  38600. startTime: this.syncPoint_.time
  38601. });
  38602. next.getMediaInfoForTime = this.fetchAtBuffer_ ? `bufferedEnd ${bufferedEnd}` : `currentTime ${this.currentTime_()}`;
  38603. next.mediaIndex = segmentIndex;
  38604. next.startOfSegment = startTime;
  38605. next.partIndex = partIndex;
  38606. }
  38607. const nextSegment = segments[next.mediaIndex];
  38608. let nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  38609. // the next partIndex is invalid do not choose a next segment.
  38610. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  38611. return null;
  38612. } // if the next segment has parts, and we don't have a partIndex.
  38613. // Set partIndex to 0
  38614. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  38615. next.partIndex = 0;
  38616. nextPart = nextSegment.parts[0];
  38617. } // if we have no buffered data then we need to make sure
  38618. // that the next part we append is "independent" if possible.
  38619. // So we check if the previous part is independent, and request
  38620. // it if it is.
  38621. if (!bufferedTime && nextPart && !nextPart.independent) {
  38622. if (next.partIndex === 0) {
  38623. const lastSegment = segments[next.mediaIndex - 1];
  38624. const lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  38625. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  38626. next.mediaIndex -= 1;
  38627. next.partIndex = lastSegment.parts.length - 1;
  38628. next.independent = 'previous segment';
  38629. }
  38630. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  38631. next.partIndex -= 1;
  38632. next.independent = 'previous part';
  38633. }
  38634. }
  38635. const ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  38636. // 1. this is the last segment in the playlist
  38637. // 2. end of stream has been called on the media source already
  38638. // 3. the player is not seeking
  38639. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  38640. return null;
  38641. }
  38642. return this.generateSegmentInfo_(next);
  38643. }
  38644. generateSegmentInfo_(options) {
  38645. const {
  38646. independent,
  38647. playlist,
  38648. mediaIndex,
  38649. startOfSegment,
  38650. isSyncRequest,
  38651. partIndex,
  38652. forceTimestampOffset,
  38653. getMediaInfoForTime
  38654. } = options;
  38655. const segment = playlist.segments[mediaIndex];
  38656. const part = typeof partIndex === 'number' && segment.parts[partIndex];
  38657. const segmentInfo = {
  38658. requestId: 'segment-loader-' + Math.random(),
  38659. // resolve the segment URL relative to the playlist
  38660. uri: part && part.resolvedUri || segment.resolvedUri,
  38661. // the segment's mediaIndex at the time it was requested
  38662. mediaIndex,
  38663. partIndex: part ? partIndex : null,
  38664. // whether or not to update the SegmentLoader's state with this
  38665. // segment's mediaIndex
  38666. isSyncRequest,
  38667. startOfSegment,
  38668. // the segment's playlist
  38669. playlist,
  38670. // unencrypted bytes of the segment
  38671. bytes: null,
  38672. // when a key is defined for this segment, the encrypted bytes
  38673. encryptedBytes: null,
  38674. // The target timestampOffset for this segment when we append it
  38675. // to the source buffer
  38676. timestampOffset: null,
  38677. // The timeline that the segment is in
  38678. timeline: segment.timeline,
  38679. // The expected duration of the segment in seconds
  38680. duration: part && part.duration || segment.duration,
  38681. // retain the segment in case the playlist updates while doing an async process
  38682. segment,
  38683. part,
  38684. byteLength: 0,
  38685. transmuxer: this.transmuxer_,
  38686. // type of getMediaInfoForTime that was used to get this segment
  38687. getMediaInfoForTime,
  38688. independent
  38689. };
  38690. const overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  38691. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  38692. segmentTimeline: segment.timeline,
  38693. currentTimeline: this.currentTimeline_,
  38694. startOfSegment,
  38695. buffered: this.buffered_(),
  38696. overrideCheck
  38697. });
  38698. const audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  38699. if (typeof audioBufferedEnd === 'number') {
  38700. // since the transmuxer is using the actual timing values, but the buffer is
  38701. // adjusted by the timestamp offset, we must adjust the value here
  38702. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  38703. }
  38704. if (this.sourceUpdater_.videoBuffered().length) {
  38705. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_,
  38706. // since the transmuxer is using the actual timing values, but the time is
  38707. // adjusted by the timestmap offset, we must adjust the value here
  38708. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  38709. }
  38710. return segmentInfo;
  38711. } // get the timestampoffset for a segment,
  38712. // added so that vtt segment loader can override and prevent
  38713. // adding timestamp offsets.
  38714. timestampOffsetForSegment_(options) {
  38715. return timestampOffsetForSegment(options);
  38716. }
  38717. /**
  38718. * Determines if the network has enough bandwidth to complete the current segment
  38719. * request in a timely manner. If not, the request will be aborted early and bandwidth
  38720. * updated to trigger a playlist switch.
  38721. *
  38722. * @param {Object} stats
  38723. * Object containing stats about the request timing and size
  38724. * @private
  38725. */
  38726. earlyAbortWhenNeeded_(stats) {
  38727. if (this.vhs_.tech_.paused() ||
  38728. // Don't abort if the current playlist is on the lowestEnabledRendition
  38729. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  38730. // the lowestEnabledRendition.
  38731. !this.xhrOptions_.timeout ||
  38732. // Don't abort if we have no bandwidth information to estimate segment sizes
  38733. !this.playlist_.attributes.BANDWIDTH) {
  38734. return;
  38735. } // Wait at least 1 second since the first byte of data has been received before
  38736. // using the calculated bandwidth from the progress event to allow the bitrate
  38737. // to stabilize
  38738. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  38739. return;
  38740. }
  38741. const currentTime = this.currentTime_();
  38742. const measuredBandwidth = stats.bandwidth;
  38743. const segmentDuration = this.pendingSegment_.duration;
  38744. const requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  38745. // if we are only left with less than 1 second when the request completes.
  38746. // A negative timeUntilRebuffering indicates we are already rebuffering
  38747. const timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  38748. // is larger than the estimated time until the player runs out of forward buffer
  38749. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  38750. return;
  38751. }
  38752. const switchCandidate = minRebufferMaxBandwidthSelector({
  38753. main: this.vhs_.playlists.main,
  38754. currentTime,
  38755. bandwidth: measuredBandwidth,
  38756. duration: this.duration_(),
  38757. segmentDuration,
  38758. timeUntilRebuffer: timeUntilRebuffer$1,
  38759. currentTimeline: this.currentTimeline_,
  38760. syncController: this.syncController_
  38761. });
  38762. if (!switchCandidate) {
  38763. return;
  38764. }
  38765. const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  38766. const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  38767. let minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  38768. // potential round trip time of the new request so that we are not too aggressive
  38769. // with switching to a playlist that might save us a fraction of a second.
  38770. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  38771. minimumTimeSaving = 1;
  38772. }
  38773. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  38774. return;
  38775. } // set the bandwidth to that of the desired playlist being sure to scale by
  38776. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  38777. // don't trigger a bandwidthupdate as the bandwidth is artifial
  38778. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  38779. this.trigger('earlyabort');
  38780. }
  38781. handleAbort_(segmentInfo) {
  38782. this.logger_(`Aborting ${segmentInfoString(segmentInfo)}`);
  38783. this.mediaRequestsAborted += 1;
  38784. }
  38785. /**
  38786. * XHR `progress` event handler
  38787. *
  38788. * @param {Event}
  38789. * The XHR `progress` event
  38790. * @param {Object} simpleSegment
  38791. * A simplified segment object copy
  38792. * @private
  38793. */
  38794. handleProgress_(event, simpleSegment) {
  38795. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38796. if (this.checkForAbort_(simpleSegment.requestId)) {
  38797. return;
  38798. }
  38799. this.trigger('progress');
  38800. }
  38801. handleTrackInfo_(simpleSegment, trackInfo) {
  38802. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38803. if (this.checkForAbort_(simpleSegment.requestId)) {
  38804. return;
  38805. }
  38806. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  38807. return;
  38808. }
  38809. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  38810. // Guard against cases where we're not getting track info at all until we are
  38811. // certain that all streams will provide it.
  38812. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  38813. this.appendInitSegment_ = {
  38814. audio: true,
  38815. video: true
  38816. };
  38817. this.startingMediaInfo_ = trackInfo;
  38818. this.currentMediaInfo_ = trackInfo;
  38819. this.logger_('trackinfo update', trackInfo);
  38820. this.trigger('trackinfo');
  38821. } // trackinfo may cause an abort if the trackinfo
  38822. // causes a codec change to an unsupported codec.
  38823. if (this.checkForAbort_(simpleSegment.requestId)) {
  38824. return;
  38825. } // set trackinfo on the pending segment so that
  38826. // it can append.
  38827. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  38828. if (this.hasEnoughInfoToAppend_()) {
  38829. this.processCallQueue_();
  38830. }
  38831. }
  38832. handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  38833. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38834. if (this.checkForAbort_(simpleSegment.requestId)) {
  38835. return;
  38836. }
  38837. const segmentInfo = this.pendingSegment_;
  38838. const timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  38839. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  38840. segmentInfo[timingInfoProperty][timeType] = time;
  38841. this.logger_(`timinginfo: ${mediaType} - ${timeType} - ${time}`); // check if any calls were waiting on the timing info
  38842. if (this.hasEnoughInfoToAppend_()) {
  38843. this.processCallQueue_();
  38844. }
  38845. }
  38846. handleCaptions_(simpleSegment, captionData) {
  38847. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38848. if (this.checkForAbort_(simpleSegment.requestId)) {
  38849. return;
  38850. } // This could only happen with fmp4 segments, but
  38851. // should still not happen in general
  38852. if (captionData.length === 0) {
  38853. this.logger_('SegmentLoader received no captions from a caption event');
  38854. return;
  38855. }
  38856. const segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  38857. // can be adjusted by the timestamp offset
  38858. if (!segmentInfo.hasAppendedData_) {
  38859. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  38860. return;
  38861. }
  38862. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  38863. const captionTracks = {}; // get total start/end and captions for each track/stream
  38864. captionData.forEach(caption => {
  38865. // caption.stream is actually a track name...
  38866. // set to the existing values in tracks or default values
  38867. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  38868. // Infinity, as any other value will be less than this
  38869. startTime: Infinity,
  38870. captions: [],
  38871. // 0 as an other value will be more than this
  38872. endTime: 0
  38873. };
  38874. const captionTrack = captionTracks[caption.stream];
  38875. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  38876. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  38877. captionTrack.captions.push(caption);
  38878. });
  38879. Object.keys(captionTracks).forEach(trackName => {
  38880. const {
  38881. startTime,
  38882. endTime,
  38883. captions
  38884. } = captionTracks[trackName];
  38885. const inbandTextTracks = this.inbandTextTracks_;
  38886. this.logger_(`adding cues from ${startTime} -> ${endTime} for ${trackName}`);
  38887. createCaptionsTrackIfNotExists(inbandTextTracks, this.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  38888. // We do this because a rendition change that also changes the timescale for captions
  38889. // will result in captions being re-parsed for certain segments. If we add them again
  38890. // without clearing we will have two of the same captions visible.
  38891. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  38892. addCaptionData({
  38893. captionArray: captions,
  38894. inbandTextTracks,
  38895. timestampOffset
  38896. });
  38897. }); // Reset stored captions since we added parsed
  38898. // captions to a text track at this point
  38899. if (this.transmuxer_) {
  38900. this.transmuxer_.postMessage({
  38901. action: 'clearParsedMp4Captions'
  38902. });
  38903. }
  38904. }
  38905. handleId3_(simpleSegment, id3Frames, dispatchType) {
  38906. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38907. if (this.checkForAbort_(simpleSegment.requestId)) {
  38908. return;
  38909. }
  38910. const segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  38911. if (!segmentInfo.hasAppendedData_) {
  38912. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  38913. return;
  38914. }
  38915. 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
  38916. // audio/video source with a metadata track, and an alt audio with a metadata track.
  38917. // However, this probably won't happen, and if it does it can be handled then.
  38918. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
  38919. addMetadata({
  38920. inbandTextTracks: this.inbandTextTracks_,
  38921. metadataArray: id3Frames,
  38922. timestampOffset,
  38923. videoDuration: this.duration_()
  38924. });
  38925. }
  38926. processMetadataQueue_() {
  38927. this.metadataQueue_.id3.forEach(fn => fn());
  38928. this.metadataQueue_.caption.forEach(fn => fn());
  38929. this.metadataQueue_.id3 = [];
  38930. this.metadataQueue_.caption = [];
  38931. }
  38932. processCallQueue_() {
  38933. const callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  38934. // functions may check the length of the load queue and default to pushing themselves
  38935. // back onto the queue.
  38936. this.callQueue_ = [];
  38937. callQueue.forEach(fun => fun());
  38938. }
  38939. processLoadQueue_() {
  38940. const loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  38941. // functions may check the length of the load queue and default to pushing themselves
  38942. // back onto the queue.
  38943. this.loadQueue_ = [];
  38944. loadQueue.forEach(fun => fun());
  38945. }
  38946. /**
  38947. * Determines whether the loader has enough info to load the next segment.
  38948. *
  38949. * @return {boolean}
  38950. * Whether or not the loader has enough info to load the next segment
  38951. */
  38952. hasEnoughInfoToLoad_() {
  38953. // Since primary timing goes by video, only the audio loader potentially needs to wait
  38954. // to load.
  38955. if (this.loaderType_ !== 'audio') {
  38956. return true;
  38957. }
  38958. const segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  38959. // enough info to load.
  38960. if (!segmentInfo) {
  38961. return false;
  38962. } // The first segment can and should be loaded immediately so that source buffers are
  38963. // created together (before appending). Source buffer creation uses the presence of
  38964. // audio and video data to determine whether to create audio/video source buffers, and
  38965. // uses processed (transmuxed or parsed) media to determine the types required.
  38966. if (!this.getCurrentMediaInfo_()) {
  38967. return true;
  38968. }
  38969. if (
  38970. // Technically, instead of waiting to load a segment on timeline changes, a segment
  38971. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  38972. // But in practice, there are a few reasons why it is better to wait until a loader
  38973. // is ready to append that segment before requesting and downloading:
  38974. //
  38975. // 1. Because audio and main loaders cross discontinuities together, if this loader
  38976. // is waiting for the other to catch up, then instead of requesting another
  38977. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  38978. // allotted to the loader currently behind.
  38979. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  38980. // is ready to be processed or not, isolating the queueing behavior to the loader.
  38981. // 3. The audio loader bases some of its segment properties on timing information
  38982. // provided by the main loader, meaning that, if the logic for waiting on
  38983. // processing was in media-segment-request, then it would also need to know how
  38984. // to re-generate the segment information after the main loader caught up.
  38985. shouldWaitForTimelineChange({
  38986. timelineChangeController: this.timelineChangeController_,
  38987. currentTimeline: this.currentTimeline_,
  38988. segmentTimeline: segmentInfo.timeline,
  38989. loaderType: this.loaderType_,
  38990. audioDisabled: this.audioDisabled_
  38991. })) {
  38992. return false;
  38993. }
  38994. return true;
  38995. }
  38996. getCurrentMediaInfo_(segmentInfo = this.pendingSegment_) {
  38997. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  38998. }
  38999. getMediaInfo_(segmentInfo = this.pendingSegment_) {
  39000. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  39001. }
  39002. getPendingSegmentPlaylist() {
  39003. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  39004. }
  39005. hasEnoughInfoToAppend_() {
  39006. if (!this.sourceUpdater_.ready()) {
  39007. return false;
  39008. } // If content needs to be removed or the loader is waiting on an append reattempt,
  39009. // then no additional content should be appended until the prior append is resolved.
  39010. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  39011. return false;
  39012. }
  39013. const segmentInfo = this.pendingSegment_;
  39014. const trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  39015. // we do not have information on this specific
  39016. // segment yet
  39017. if (!segmentInfo || !trackInfo) {
  39018. return false;
  39019. }
  39020. const {
  39021. hasAudio,
  39022. hasVideo,
  39023. isMuxed
  39024. } = trackInfo;
  39025. if (hasVideo && !segmentInfo.videoTimingInfo) {
  39026. return false;
  39027. } // muxed content only relies on video timing information for now.
  39028. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  39029. return false;
  39030. }
  39031. if (shouldWaitForTimelineChange({
  39032. timelineChangeController: this.timelineChangeController_,
  39033. currentTimeline: this.currentTimeline_,
  39034. segmentTimeline: segmentInfo.timeline,
  39035. loaderType: this.loaderType_,
  39036. audioDisabled: this.audioDisabled_
  39037. })) {
  39038. return false;
  39039. }
  39040. return true;
  39041. }
  39042. handleData_(simpleSegment, result) {
  39043. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  39044. if (this.checkForAbort_(simpleSegment.requestId)) {
  39045. return;
  39046. } // If there's anything in the call queue, then this data came later and should be
  39047. // executed after the calls currently queued.
  39048. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  39049. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  39050. return;
  39051. }
  39052. const segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  39053. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  39054. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  39055. // logic may change behavior depending on the state, and changing state too early may
  39056. // inflate our estimates of bandwidth. In the future this should be re-examined to
  39057. // note more granular states.
  39058. // don't process and append data if the mediaSource is closed
  39059. if (this.mediaSource_.readyState === 'closed') {
  39060. return;
  39061. } // if this request included an initialization segment, save that data
  39062. // to the initSegment cache
  39063. if (simpleSegment.map) {
  39064. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  39065. segmentInfo.segment.map = simpleSegment.map;
  39066. } // if this request included a segment key, save that data in the cache
  39067. if (simpleSegment.key) {
  39068. this.segmentKey(simpleSegment.key, true);
  39069. }
  39070. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  39071. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  39072. if (segmentInfo.isFmp4) {
  39073. this.trigger('fmp4');
  39074. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  39075. } else {
  39076. const trackInfo = this.getCurrentMediaInfo_();
  39077. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  39078. let firstVideoFrameTimeForData;
  39079. if (useVideoTimingInfo) {
  39080. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  39081. } // Segment loader knows more about segment timing than the transmuxer (in certain
  39082. // aspects), so make any changes required for a more accurate start time.
  39083. // Don't set the end time yet, as the segment may not be finished processing.
  39084. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  39085. currentStart: segmentInfo.timingInfo.start,
  39086. playlist: segmentInfo.playlist,
  39087. mediaIndex: segmentInfo.mediaIndex,
  39088. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  39089. useVideoTimingInfo,
  39090. firstVideoFrameTimeForData,
  39091. videoTimingInfo: segmentInfo.videoTimingInfo,
  39092. audioTimingInfo: segmentInfo.audioTimingInfo
  39093. });
  39094. } // Init segments for audio and video only need to be appended in certain cases. Now
  39095. // that data is about to be appended, we can check the final cases to determine
  39096. // whether we should append an init segment.
  39097. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  39098. // as we use the start of the segment to offset the best guess (playlist provided)
  39099. // timestamp offset.
  39100. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  39101. // be appended or not.
  39102. if (segmentInfo.isSyncRequest) {
  39103. // first save/update our timing info for this segment.
  39104. // this is what allows us to choose an accurate segment
  39105. // and the main reason we make a sync request.
  39106. this.updateTimingInfoEnd_(segmentInfo);
  39107. this.syncController_.saveSegmentTimingInfo({
  39108. segmentInfo,
  39109. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  39110. });
  39111. const next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  39112. // after taking into account its timing info, do not append it.
  39113. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  39114. this.logger_('sync segment was incorrect, not appending');
  39115. return;
  39116. } // otherwise append it like any other segment as our guess was correct.
  39117. this.logger_('sync segment was correct, appending');
  39118. } // Save some state so that in the future anything waiting on first append (and/or
  39119. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  39120. // we need some notion of whether the timestamp offset or other relevant information
  39121. // has had a chance to be set.
  39122. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  39123. this.processMetadataQueue_();
  39124. this.appendData_(segmentInfo, result);
  39125. }
  39126. updateAppendInitSegmentStatus(segmentInfo, type) {
  39127. // alt audio doesn't manage timestamp offset
  39128. if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' &&
  39129. // in the case that we're handling partial data, we don't want to append an init
  39130. // segment for each chunk
  39131. !segmentInfo.changedTimestampOffset) {
  39132. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  39133. // append init segments
  39134. this.appendInitSegment_ = {
  39135. audio: true,
  39136. video: true
  39137. };
  39138. }
  39139. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  39140. // make sure we append init segment on playlist changes, in case the media config
  39141. // changed
  39142. this.appendInitSegment_[type] = true;
  39143. }
  39144. }
  39145. getInitSegmentAndUpdateState_({
  39146. type,
  39147. initSegment,
  39148. map,
  39149. playlist
  39150. }) {
  39151. // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  39152. // (Section 3) required to parse the applicable Media Segments. It applies to every
  39153. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  39154. // or until the end of the playlist."
  39155. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  39156. if (map) {
  39157. const id = initSegmentId(map);
  39158. if (this.activeInitSegmentId_ === id) {
  39159. // don't need to re-append the init segment if the ID matches
  39160. return null;
  39161. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  39162. // obtained) init segment
  39163. //
  39164. // this also caches the init segment for later use
  39165. initSegment = this.initSegmentForMap(map, true).bytes;
  39166. this.activeInitSegmentId_ = id;
  39167. } // We used to always prepend init segments for video, however, that shouldn't be
  39168. // necessary. Instead, we should only append on changes, similar to what we've always
  39169. // done for audio. This is more important (though may not be that important) for
  39170. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  39171. // appends.
  39172. if (initSegment && this.appendInitSegment_[type]) {
  39173. // Make sure we track the playlist that we last used for the init segment, so that
  39174. // we can re-append the init segment in the event that we get data from a new
  39175. // playlist. Discontinuities and track changes are handled in other sections.
  39176. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  39177. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  39178. // we are appending the muxer init segment
  39179. this.activeInitSegmentId_ = null;
  39180. return initSegment;
  39181. }
  39182. return null;
  39183. }
  39184. handleQuotaExceededError_({
  39185. segmentInfo,
  39186. type,
  39187. bytes
  39188. }, error) {
  39189. const audioBuffered = this.sourceUpdater_.audioBuffered();
  39190. const videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  39191. // should be cleared out during the buffer removals. However, log in case it helps
  39192. // debug.
  39193. if (audioBuffered.length > 1) {
  39194. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  39195. }
  39196. if (videoBuffered.length > 1) {
  39197. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  39198. }
  39199. const audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  39200. const audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  39201. const videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  39202. const videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  39203. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  39204. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  39205. // allow for appends of segments this size). In the future, it may be possible to
  39206. // split up the segment and append in pieces, but for now, error out this playlist
  39207. // in an attempt to switch to a more manageable rendition.
  39208. 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(', ')}, `);
  39209. this.error({
  39210. message: 'Quota exceeded error with append of a single segment of content',
  39211. excludeUntil: Infinity
  39212. });
  39213. this.trigger('error');
  39214. return;
  39215. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  39216. // that the segment-loader should block on future events until this one is handled, so
  39217. // that it doesn't keep moving onto further segments. Adding the call to the call
  39218. // queue will prevent further appends until waitingOnRemove_ and
  39219. // quotaExceededErrorRetryTimeout_ are cleared.
  39220. //
  39221. // Note that this will only block the current loader. In the case of demuxed content,
  39222. // the other load may keep filling as fast as possible. In practice, this should be
  39223. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  39224. // source buffer, or video fills without enough room for audio to append (and without
  39225. // the availability of clearing out seconds of back buffer to make room for audio).
  39226. // But it might still be good to handle this case in the future as a TODO.
  39227. this.waitingOnRemove_ = true;
  39228. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  39229. segmentInfo,
  39230. type,
  39231. bytes
  39232. }));
  39233. const currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  39234. // before retrying.
  39235. const timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  39236. this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${timeToRemoveUntil}`);
  39237. this.remove(0, timeToRemoveUntil, () => {
  39238. this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${MIN_BACK_BUFFER}s`);
  39239. this.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  39240. // attempts (since we can't clear less than the minimum)
  39241. this.quotaExceededErrorRetryTimeout_ = window$1.setTimeout(() => {
  39242. this.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  39243. this.quotaExceededErrorRetryTimeout_ = null;
  39244. this.processCallQueue_();
  39245. }, MIN_BACK_BUFFER * 1000);
  39246. }, true);
  39247. }
  39248. handleAppendError_({
  39249. segmentInfo,
  39250. type,
  39251. bytes
  39252. }, error) {
  39253. // if there's no error, nothing to do
  39254. if (!error) {
  39255. return;
  39256. }
  39257. if (error.code === QUOTA_EXCEEDED_ERR) {
  39258. this.handleQuotaExceededError_({
  39259. segmentInfo,
  39260. type,
  39261. bytes
  39262. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  39263. // to trigger an append error.
  39264. return;
  39265. }
  39266. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  39267. 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.
  39268. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  39269. //
  39270. // Trigger a special error so that it can be handled separately from normal,
  39271. // recoverable errors.
  39272. this.trigger('appenderror');
  39273. }
  39274. appendToSourceBuffer_({
  39275. segmentInfo,
  39276. type,
  39277. initSegment,
  39278. data,
  39279. bytes
  39280. }) {
  39281. // If this is a re-append, bytes were already created and don't need to be recreated
  39282. if (!bytes) {
  39283. const segments = [data];
  39284. let byteLength = data.byteLength;
  39285. if (initSegment) {
  39286. // if the media initialization segment is changing, append it before the content
  39287. // segment
  39288. segments.unshift(initSegment);
  39289. byteLength += initSegment.byteLength;
  39290. } // Technically we should be OK appending the init segment separately, however, we
  39291. // haven't yet tested that, and prepending is how we have always done things.
  39292. bytes = concatSegments({
  39293. bytes: byteLength,
  39294. segments
  39295. });
  39296. }
  39297. this.sourceUpdater_.appendBuffer({
  39298. segmentInfo,
  39299. type,
  39300. bytes
  39301. }, this.handleAppendError_.bind(this, {
  39302. segmentInfo,
  39303. type,
  39304. bytes
  39305. }));
  39306. }
  39307. handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  39308. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  39309. return;
  39310. }
  39311. const segment = this.pendingSegment_.segment;
  39312. const timingInfoProperty = `${type}TimingInfo`;
  39313. if (!segment[timingInfoProperty]) {
  39314. segment[timingInfoProperty] = {};
  39315. }
  39316. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  39317. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  39318. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  39319. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  39320. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  39321. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  39322. }
  39323. appendData_(segmentInfo, result) {
  39324. const {
  39325. type,
  39326. data
  39327. } = result;
  39328. if (!data || !data.byteLength) {
  39329. return;
  39330. }
  39331. if (type === 'audio' && this.audioDisabled_) {
  39332. return;
  39333. }
  39334. const initSegment = this.getInitSegmentAndUpdateState_({
  39335. type,
  39336. initSegment: result.initSegment,
  39337. playlist: segmentInfo.playlist,
  39338. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  39339. });
  39340. this.appendToSourceBuffer_({
  39341. segmentInfo,
  39342. type,
  39343. initSegment,
  39344. data
  39345. });
  39346. }
  39347. /**
  39348. * load a specific segment from a request into the buffer
  39349. *
  39350. * @private
  39351. */
  39352. loadSegment_(segmentInfo) {
  39353. this.state = 'WAITING';
  39354. this.pendingSegment_ = segmentInfo;
  39355. this.trimBackBuffer_(segmentInfo);
  39356. if (typeof segmentInfo.timestampOffset === 'number') {
  39357. if (this.transmuxer_) {
  39358. this.transmuxer_.postMessage({
  39359. action: 'clearAllMp4Captions'
  39360. });
  39361. }
  39362. }
  39363. if (!this.hasEnoughInfoToLoad_()) {
  39364. this.loadQueue_.push(() => {
  39365. // regenerate the audioAppendStart, timestampOffset, etc as they
  39366. // may have changed since this function was added to the queue.
  39367. const options = _extends({}, segmentInfo, {
  39368. forceTimestampOffset: true
  39369. });
  39370. _extends(segmentInfo, this.generateSegmentInfo_(options));
  39371. this.isPendingTimestampOffset_ = false;
  39372. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  39373. });
  39374. return;
  39375. }
  39376. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  39377. }
  39378. updateTransmuxerAndRequestSegment_(segmentInfo) {
  39379. // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  39380. // the transmuxer still needs to be updated before then.
  39381. //
  39382. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  39383. // offset must be passed to the transmuxer for stream correcting adjustments.
  39384. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  39385. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  39386. segmentInfo.gopsToAlignWith = [];
  39387. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  39388. this.transmuxer_.postMessage({
  39389. action: 'reset'
  39390. });
  39391. this.transmuxer_.postMessage({
  39392. action: 'setTimestampOffset',
  39393. timestampOffset: segmentInfo.timestampOffset
  39394. });
  39395. }
  39396. const simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  39397. const isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  39398. const isWalkingForward = this.mediaIndex !== null;
  39399. const isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ &&
  39400. // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  39401. // the first timeline
  39402. segmentInfo.timeline > 0;
  39403. const isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  39404. 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),
  39405. // then this init segment has never been seen before and should be appended.
  39406. //
  39407. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  39408. // both to true and leave the decision of whether to append the init segment to append time.
  39409. if (simpleSegment.map && !simpleSegment.map.bytes) {
  39410. this.logger_('going to request init segment.');
  39411. this.appendInitSegment_ = {
  39412. video: true,
  39413. audio: true
  39414. };
  39415. }
  39416. segmentInfo.abortRequests = mediaSegmentRequest({
  39417. xhr: this.vhs_.xhr,
  39418. xhrOptions: this.xhrOptions_,
  39419. decryptionWorker: this.decrypter_,
  39420. segment: simpleSegment,
  39421. abortFn: this.handleAbort_.bind(this, segmentInfo),
  39422. progressFn: this.handleProgress_.bind(this),
  39423. trackInfoFn: this.handleTrackInfo_.bind(this),
  39424. timingInfoFn: this.handleTimingInfo_.bind(this),
  39425. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  39426. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  39427. captionsFn: this.handleCaptions_.bind(this),
  39428. isEndOfTimeline,
  39429. endedTimelineFn: () => {
  39430. this.logger_('received endedtimeline callback');
  39431. },
  39432. id3Fn: this.handleId3_.bind(this),
  39433. dataFn: this.handleData_.bind(this),
  39434. doneFn: this.segmentRequestFinished_.bind(this),
  39435. onTransmuxerLog: ({
  39436. message,
  39437. level,
  39438. stream
  39439. }) => {
  39440. this.logger_(`${segmentInfoString(segmentInfo)} logged from transmuxer stream ${stream} as a ${level}: ${message}`);
  39441. }
  39442. });
  39443. }
  39444. /**
  39445. * trim the back buffer so that we don't have too much data
  39446. * in the source buffer
  39447. *
  39448. * @private
  39449. *
  39450. * @param {Object} segmentInfo - the current segment
  39451. */
  39452. trimBackBuffer_(segmentInfo) {
  39453. const removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  39454. // buffer and a very conservative "garbage collector"
  39455. // We manually clear out the old buffer to ensure
  39456. // we don't trigger the QuotaExceeded error
  39457. // on the source buffer during subsequent appends
  39458. if (removeToTime > 0) {
  39459. this.remove(0, removeToTime);
  39460. }
  39461. }
  39462. /**
  39463. * created a simplified copy of the segment object with just the
  39464. * information necessary to perform the XHR and decryption
  39465. *
  39466. * @private
  39467. *
  39468. * @param {Object} segmentInfo - the current segment
  39469. * @return {Object} a simplified segment object copy
  39470. */
  39471. createSimplifiedSegmentObj_(segmentInfo) {
  39472. const segment = segmentInfo.segment;
  39473. const part = segmentInfo.part;
  39474. const simpleSegment = {
  39475. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  39476. byterange: part ? part.byterange : segment.byterange,
  39477. requestId: segmentInfo.requestId,
  39478. transmuxer: segmentInfo.transmuxer,
  39479. audioAppendStart: segmentInfo.audioAppendStart,
  39480. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  39481. part: segmentInfo.part
  39482. };
  39483. const previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  39484. if (previousSegment && previousSegment.timeline === segment.timeline) {
  39485. // The baseStartTime of a segment is used to handle rollover when probing the TS
  39486. // segment to retrieve timing information. Since the probe only looks at the media's
  39487. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  39488. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  39489. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  39490. // seconds of media time, so should be used here. The previous segment is used since
  39491. // the end of the previous segment should represent the beginning of the current
  39492. // segment, so long as they are on the same timeline.
  39493. if (previousSegment.videoTimingInfo) {
  39494. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  39495. } else if (previousSegment.audioTimingInfo) {
  39496. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  39497. }
  39498. }
  39499. if (segment.key) {
  39500. // if the media sequence is greater than 2^32, the IV will be incorrect
  39501. // assuming 10s segments, that would be about 1300 years
  39502. const iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  39503. simpleSegment.key = this.segmentKey(segment.key);
  39504. simpleSegment.key.iv = iv;
  39505. }
  39506. if (segment.map) {
  39507. simpleSegment.map = this.initSegmentForMap(segment.map);
  39508. }
  39509. return simpleSegment;
  39510. }
  39511. saveTransferStats_(stats) {
  39512. // every request counts as a media request even if it has been aborted
  39513. // or canceled due to a timeout
  39514. this.mediaRequests += 1;
  39515. if (stats) {
  39516. this.mediaBytesTransferred += stats.bytesReceived;
  39517. this.mediaTransferDuration += stats.roundTripTime;
  39518. }
  39519. }
  39520. saveBandwidthRelatedStats_(duration, stats) {
  39521. // byteLength will be used for throughput, and should be based on bytes receieved,
  39522. // which we only know at the end of the request and should reflect total bytes
  39523. // downloaded rather than just bytes processed from components of the segment
  39524. this.pendingSegment_.byteLength = stats.bytesReceived;
  39525. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  39526. this.logger_(`Ignoring segment's bandwidth because its duration of ${duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
  39527. return;
  39528. }
  39529. this.bandwidth = stats.bandwidth;
  39530. this.roundTrip = stats.roundTripTime;
  39531. }
  39532. handleTimeout_() {
  39533. // although the VTT segment loader bandwidth isn't really used, it's good to
  39534. // maintain functinality between segment loaders
  39535. this.mediaRequestsTimedout += 1;
  39536. this.bandwidth = 1;
  39537. this.roundTrip = NaN;
  39538. this.trigger('bandwidthupdate');
  39539. this.trigger('timeout');
  39540. }
  39541. /**
  39542. * Handle the callback from the segmentRequest function and set the
  39543. * associated SegmentLoader state and errors if necessary
  39544. *
  39545. * @private
  39546. */
  39547. segmentRequestFinished_(error, simpleSegment, result) {
  39548. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  39549. // check the call queue directly since this function doesn't need to deal with any
  39550. // data, and can continue even if the source buffers are not set up and we didn't get
  39551. // any data from the segment
  39552. if (this.callQueue_.length) {
  39553. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  39554. return;
  39555. }
  39556. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  39557. if (!this.pendingSegment_) {
  39558. return;
  39559. } // the request was aborted and the SegmentLoader has already started
  39560. // another request. this can happen when the timeout for an aborted
  39561. // request triggers due to a limitation in the XHR library
  39562. // do not count this as any sort of request or we risk double-counting
  39563. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  39564. return;
  39565. } // an error occurred from the active pendingSegment_ so reset everything
  39566. if (error) {
  39567. this.pendingSegment_ = null;
  39568. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  39569. if (error.code === REQUEST_ERRORS.ABORTED) {
  39570. return;
  39571. }
  39572. this.pause(); // the error is really just that at least one of the requests timed-out
  39573. // set the bandwidth to a very low value and trigger an ABR switch to
  39574. // take emergency action
  39575. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  39576. this.handleTimeout_();
  39577. return;
  39578. } // if control-flow has arrived here, then the error is real
  39579. // emit an error event to exclude the current playlist
  39580. this.mediaRequestsErrored += 1;
  39581. this.error(error);
  39582. this.trigger('error');
  39583. return;
  39584. }
  39585. const segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  39586. // generated for ABR purposes
  39587. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  39588. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  39589. if (result.gopInfo) {
  39590. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  39591. } // Although we may have already started appending on progress, we shouldn't switch the
  39592. // state away from loading until we are officially done loading the segment data.
  39593. this.state = 'APPENDING'; // used for testing
  39594. this.trigger('appending');
  39595. this.waitForAppendsToComplete_(segmentInfo);
  39596. }
  39597. setTimeMapping_(timeline) {
  39598. const timelineMapping = this.syncController_.mappingForTimeline(timeline);
  39599. if (timelineMapping !== null) {
  39600. this.timeMapping_ = timelineMapping;
  39601. }
  39602. }
  39603. updateMediaSecondsLoaded_(segment) {
  39604. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  39605. this.mediaSecondsLoaded += segment.end - segment.start;
  39606. } else {
  39607. this.mediaSecondsLoaded += segment.duration;
  39608. }
  39609. }
  39610. shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  39611. if (timestampOffset === null) {
  39612. return false;
  39613. } // note that we're potentially using the same timestamp offset for both video and
  39614. // audio
  39615. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  39616. return true;
  39617. }
  39618. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  39619. return true;
  39620. }
  39621. return false;
  39622. }
  39623. trueSegmentStart_({
  39624. currentStart,
  39625. playlist,
  39626. mediaIndex,
  39627. firstVideoFrameTimeForData,
  39628. currentVideoTimestampOffset,
  39629. useVideoTimingInfo,
  39630. videoTimingInfo,
  39631. audioTimingInfo
  39632. }) {
  39633. if (typeof currentStart !== 'undefined') {
  39634. // if start was set once, keep using it
  39635. return currentStart;
  39636. }
  39637. if (!useVideoTimingInfo) {
  39638. return audioTimingInfo.start;
  39639. }
  39640. const previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  39641. // within that segment. Since the transmuxer maintains a cache of incomplete data
  39642. // from and/or the last frame seen, the start time may reflect a frame that starts
  39643. // in the previous segment. Check for that case and ensure the start time is
  39644. // accurate for the segment.
  39645. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  39646. return firstVideoFrameTimeForData;
  39647. }
  39648. return videoTimingInfo.start;
  39649. }
  39650. waitForAppendsToComplete_(segmentInfo) {
  39651. const trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  39652. if (!trackInfo) {
  39653. this.error({
  39654. message: 'No starting media returned, likely due to an unsupported media format.',
  39655. playlistExclusionDuration: Infinity
  39656. });
  39657. this.trigger('error');
  39658. return;
  39659. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  39660. // on each queue this loader is responsible for to ensure that the appends are
  39661. // complete.
  39662. const {
  39663. hasAudio,
  39664. hasVideo,
  39665. isMuxed
  39666. } = trackInfo;
  39667. const waitForVideo = this.loaderType_ === 'main' && hasVideo;
  39668. const waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  39669. segmentInfo.waitingOnAppends = 0; // segments with no data
  39670. if (!segmentInfo.hasAppendedData_) {
  39671. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  39672. // When there's no audio or video data in the segment, there's no audio or video
  39673. // timing information.
  39674. //
  39675. // If there's no audio or video timing information, then the timestamp offset
  39676. // can't be adjusted to the appropriate value for the transmuxer and source
  39677. // buffers.
  39678. //
  39679. // Therefore, the next segment should be used to set the timestamp offset.
  39680. this.isPendingTimestampOffset_ = true;
  39681. } // override settings for metadata only segments
  39682. segmentInfo.timingInfo = {
  39683. start: 0
  39684. };
  39685. segmentInfo.waitingOnAppends++;
  39686. if (!this.isPendingTimestampOffset_) {
  39687. // update the timestampoffset
  39688. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  39689. // no video/audio data.
  39690. this.processMetadataQueue_();
  39691. } // append is "done" instantly with no data.
  39692. this.checkAppendsDone_(segmentInfo);
  39693. return;
  39694. } // Since source updater could call back synchronously, do the increments first.
  39695. if (waitForVideo) {
  39696. segmentInfo.waitingOnAppends++;
  39697. }
  39698. if (waitForAudio) {
  39699. segmentInfo.waitingOnAppends++;
  39700. }
  39701. if (waitForVideo) {
  39702. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  39703. }
  39704. if (waitForAudio) {
  39705. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  39706. }
  39707. }
  39708. checkAppendsDone_(segmentInfo) {
  39709. if (this.checkForAbort_(segmentInfo.requestId)) {
  39710. return;
  39711. }
  39712. segmentInfo.waitingOnAppends--;
  39713. if (segmentInfo.waitingOnAppends === 0) {
  39714. this.handleAppendsDone_();
  39715. }
  39716. }
  39717. checkForIllegalMediaSwitch(trackInfo) {
  39718. const illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  39719. if (illegalMediaSwitchError) {
  39720. this.error({
  39721. message: illegalMediaSwitchError,
  39722. playlistExclusionDuration: Infinity
  39723. });
  39724. this.trigger('error');
  39725. return true;
  39726. }
  39727. return false;
  39728. }
  39729. updateSourceBufferTimestampOffset_(segmentInfo) {
  39730. if (segmentInfo.timestampOffset === null ||
  39731. // we don't yet have the start for whatever media type (video or audio) has
  39732. // priority, timing-wise, so we must wait
  39733. typeof segmentInfo.timingInfo.start !== 'number' ||
  39734. // already updated the timestamp offset for this segment
  39735. segmentInfo.changedTimestampOffset ||
  39736. // the alt audio loader should not be responsible for setting the timestamp offset
  39737. this.loaderType_ !== 'main') {
  39738. return;
  39739. }
  39740. let didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  39741. // the timing info here comes from video. In the event that the audio is longer than
  39742. // the video, this will trim the start of the audio.
  39743. // This also trims any offset from 0 at the beginning of the media
  39744. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  39745. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  39746. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  39747. timingInfo: segmentInfo.timingInfo
  39748. }); // In the event that there are part segment downloads, each will try to update the
  39749. // timestamp offset. Retaining this bit of state prevents us from updating in the
  39750. // future (within the same segment), however, there may be a better way to handle it.
  39751. segmentInfo.changedTimestampOffset = true;
  39752. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  39753. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  39754. didChange = true;
  39755. }
  39756. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  39757. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  39758. didChange = true;
  39759. }
  39760. if (didChange) {
  39761. this.trigger('timestampoffset');
  39762. }
  39763. }
  39764. getSegmentStartTimeForTimestampOffsetCalculation_({
  39765. videoTimingInfo,
  39766. audioTimingInfo,
  39767. timingInfo
  39768. }) {
  39769. if (!this.useDtsForTimestampOffset_) {
  39770. return timingInfo.start;
  39771. }
  39772. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  39773. return videoTimingInfo.transmuxedDecodeStart;
  39774. } // handle audio only
  39775. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  39776. return audioTimingInfo.transmuxedDecodeStart;
  39777. } // handle content not transmuxed (e.g., MP4)
  39778. return timingInfo.start;
  39779. }
  39780. updateTimingInfoEnd_(segmentInfo) {
  39781. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  39782. const trackInfo = this.getMediaInfo_();
  39783. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  39784. const prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  39785. if (!prioritizedTimingInfo) {
  39786. return;
  39787. }
  39788. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ?
  39789. // End time may not exist in a case where we aren't parsing the full segment (one
  39790. // current example is the case of fmp4), so use the rough duration to calculate an
  39791. // end time.
  39792. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  39793. }
  39794. /**
  39795. * callback to run when appendBuffer is finished. detects if we are
  39796. * in a good state to do things with the data we got, or if we need
  39797. * to wait for more
  39798. *
  39799. * @private
  39800. */
  39801. handleAppendsDone_() {
  39802. // appendsdone can cause an abort
  39803. if (this.pendingSegment_) {
  39804. this.trigger('appendsdone');
  39805. }
  39806. if (!this.pendingSegment_) {
  39807. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  39808. // all appending cases?
  39809. if (!this.paused()) {
  39810. this.monitorBuffer_();
  39811. }
  39812. return;
  39813. }
  39814. const segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  39815. // best to wait until all appends are done so we're sure that the primary media is
  39816. // finished (and we have its end time).
  39817. this.updateTimingInfoEnd_(segmentInfo);
  39818. if (this.shouldSaveSegmentTimingInfo_) {
  39819. // Timeline mappings should only be saved for the main loader. This is for multiple
  39820. // reasons:
  39821. //
  39822. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  39823. // and the main loader try to save the timeline mapping, whichever comes later
  39824. // will overwrite the first. In theory this is OK, as the mappings should be the
  39825. // same, however, it breaks for (2)
  39826. // 2) In the event of a live stream, the initial live point will make for a somewhat
  39827. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  39828. // the mapping will be off for one of the streams, dependent on which one was
  39829. // first saved (see (1)).
  39830. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  39831. //
  39832. // Since the audio loader will wait for the main loader to load the first segment,
  39833. // the main loader will save the first timeline mapping, and ensure that there won't
  39834. // be a case where audio loads two segments without saving a mapping (thus leading
  39835. // to missing segment timing info).
  39836. this.syncController_.saveSegmentTimingInfo({
  39837. segmentInfo,
  39838. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  39839. });
  39840. }
  39841. const segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  39842. if (segmentDurationMessage) {
  39843. if (segmentDurationMessage.severity === 'warn') {
  39844. videojs.log.warn(segmentDurationMessage.message);
  39845. } else {
  39846. this.logger_(segmentDurationMessage.message);
  39847. }
  39848. }
  39849. this.recordThroughput_(segmentInfo);
  39850. this.pendingSegment_ = null;
  39851. this.state = 'READY';
  39852. if (segmentInfo.isSyncRequest) {
  39853. this.trigger('syncinfoupdate'); // if the sync request was not appended
  39854. // then it was not the correct segment.
  39855. // throw it away and use the data it gave us
  39856. // to get the correct one.
  39857. if (!segmentInfo.hasAppendedData_) {
  39858. this.logger_(`Throwing away un-appended sync request ${segmentInfoString(segmentInfo)}`);
  39859. return;
  39860. }
  39861. }
  39862. this.logger_(`Appended ${segmentInfoString(segmentInfo)}`);
  39863. this.addSegmentMetadataCue_(segmentInfo);
  39864. this.fetchAtBuffer_ = true;
  39865. if (this.currentTimeline_ !== segmentInfo.timeline) {
  39866. this.timelineChangeController_.lastTimelineChange({
  39867. type: this.loaderType_,
  39868. from: this.currentTimeline_,
  39869. to: segmentInfo.timeline
  39870. }); // If audio is not disabled, the main segment loader is responsible for updating
  39871. // the audio timeline as well. If the content is video only, this won't have any
  39872. // impact.
  39873. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  39874. this.timelineChangeController_.lastTimelineChange({
  39875. type: 'audio',
  39876. from: this.currentTimeline_,
  39877. to: segmentInfo.timeline
  39878. });
  39879. }
  39880. }
  39881. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  39882. // the following conditional otherwise it may consider this a bad "guess"
  39883. // and attempt to resync when the post-update seekable window and live
  39884. // point would mean that this was the perfect segment to fetch
  39885. this.trigger('syncinfoupdate');
  39886. const segment = segmentInfo.segment;
  39887. const part = segmentInfo.part;
  39888. const badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  39889. 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
  39890. // the currentTime_ that means that our conservative guess was too conservative.
  39891. // In that case, reset the loader state so that we try to use any information gained
  39892. // from the previous request to create a new, more accurate, sync-point.
  39893. if (badSegmentGuess || badPartGuess) {
  39894. this.logger_(`bad ${badSegmentGuess ? 'segment' : 'part'} ${segmentInfoString(segmentInfo)}`);
  39895. this.resetEverything();
  39896. return;
  39897. }
  39898. const isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  39899. // and conservatively guess
  39900. if (isWalkingForward) {
  39901. this.trigger('bandwidthupdate');
  39902. }
  39903. this.trigger('progress');
  39904. this.mediaIndex = segmentInfo.mediaIndex;
  39905. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  39906. // buffer, end the stream. this ensures the "ended" event will
  39907. // fire if playback reaches that point.
  39908. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  39909. this.endOfStream();
  39910. } // used for testing
  39911. this.trigger('appended');
  39912. if (segmentInfo.hasAppendedData_) {
  39913. this.mediaAppends++;
  39914. }
  39915. if (!this.paused()) {
  39916. this.monitorBuffer_();
  39917. }
  39918. }
  39919. /**
  39920. * Records the current throughput of the decrypt, transmux, and append
  39921. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  39922. * moving average of the throughput. `throughput.count` is the number of
  39923. * data points in the average.
  39924. *
  39925. * @private
  39926. * @param {Object} segmentInfo the object returned by loadSegment
  39927. */
  39928. recordThroughput_(segmentInfo) {
  39929. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  39930. 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}`);
  39931. return;
  39932. }
  39933. const rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  39934. // by zero in the case where the throughput is ridiculously high
  39935. const segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  39936. const segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  39937. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  39938. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  39939. }
  39940. /**
  39941. * Adds a cue to the segment-metadata track with some metadata information about the
  39942. * segment
  39943. *
  39944. * @private
  39945. * @param {Object} segmentInfo
  39946. * the object returned by loadSegment
  39947. * @method addSegmentMetadataCue_
  39948. */
  39949. addSegmentMetadataCue_(segmentInfo) {
  39950. if (!this.segmentMetadataTrack_) {
  39951. return;
  39952. }
  39953. const segment = segmentInfo.segment;
  39954. const start = segment.start;
  39955. const end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  39956. if (!finite(start) || !finite(end)) {
  39957. return;
  39958. }
  39959. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  39960. const Cue = window$1.WebKitDataCue || window$1.VTTCue;
  39961. const value = {
  39962. custom: segment.custom,
  39963. dateTimeObject: segment.dateTimeObject,
  39964. dateTimeString: segment.dateTimeString,
  39965. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  39966. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  39967. codecs: segmentInfo.playlist.attributes.CODECS,
  39968. byteLength: segmentInfo.byteLength,
  39969. uri: segmentInfo.uri,
  39970. timeline: segmentInfo.timeline,
  39971. playlist: segmentInfo.playlist.id,
  39972. start,
  39973. end
  39974. };
  39975. const data = JSON.stringify(value);
  39976. const cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  39977. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  39978. cue.value = value;
  39979. this.segmentMetadataTrack_.addCue(cue);
  39980. }
  39981. }
  39982. function noop() {}
  39983. const toTitleCase = function (string) {
  39984. if (typeof string !== 'string') {
  39985. return string;
  39986. }
  39987. return string.replace(/./, w => w.toUpperCase());
  39988. };
  39989. /**
  39990. * @file source-updater.js
  39991. */
  39992. const bufferTypes = ['video', 'audio'];
  39993. const updating = (type, sourceUpdater) => {
  39994. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  39995. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  39996. };
  39997. const nextQueueIndexOfType = (type, queue) => {
  39998. for (let i = 0; i < queue.length; i++) {
  39999. const queueEntry = queue[i];
  40000. if (queueEntry.type === 'mediaSource') {
  40001. // If the next entry is a media source entry (uses multiple source buffers), block
  40002. // processing to allow it to go through first.
  40003. return null;
  40004. }
  40005. if (queueEntry.type === type) {
  40006. return i;
  40007. }
  40008. }
  40009. return null;
  40010. };
  40011. const shiftQueue = (type, sourceUpdater) => {
  40012. if (sourceUpdater.queue.length === 0) {
  40013. return;
  40014. }
  40015. let queueIndex = 0;
  40016. let queueEntry = sourceUpdater.queue[queueIndex];
  40017. if (queueEntry.type === 'mediaSource') {
  40018. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  40019. sourceUpdater.queue.shift();
  40020. queueEntry.action(sourceUpdater);
  40021. if (queueEntry.doneFn) {
  40022. queueEntry.doneFn();
  40023. } // Only specific source buffer actions must wait for async updateend events. Media
  40024. // Source actions process synchronously. Therefore, both audio and video source
  40025. // buffers are now clear to process the next queue entries.
  40026. shiftQueue('audio', sourceUpdater);
  40027. shiftQueue('video', sourceUpdater);
  40028. } // Media Source actions require both source buffers, so if the media source action
  40029. // couldn't process yet (because one or both source buffers are busy), block other
  40030. // queue actions until both are available and the media source action can process.
  40031. return;
  40032. }
  40033. if (type === 'mediaSource') {
  40034. // If the queue was shifted by a media source action (this happens when pushing a
  40035. // media source action onto the queue), then it wasn't from an updateend event from an
  40036. // audio or video source buffer, so there's no change from previous state, and no
  40037. // processing should be done.
  40038. return;
  40039. } // Media source queue entries don't need to consider whether the source updater is
  40040. // started (i.e., source buffers are created) as they don't need the source buffers, but
  40041. // source buffer queue entries do.
  40042. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || updating(type, sourceUpdater)) {
  40043. return;
  40044. }
  40045. if (queueEntry.type !== type) {
  40046. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  40047. if (queueIndex === null) {
  40048. // Either there's no queue entry that uses this source buffer type in the queue, or
  40049. // there's a media source queue entry before the next entry of this type, in which
  40050. // case wait for that action to process first.
  40051. return;
  40052. }
  40053. queueEntry = sourceUpdater.queue[queueIndex];
  40054. }
  40055. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  40056. //
  40057. // The queue pending operation must be set before the action is performed in the event
  40058. // that the action results in a synchronous event that is acted upon. For instance, if
  40059. // an exception is thrown that can be handled, it's possible that new actions will be
  40060. // appended to an empty queue and immediately executed, but would not have the correct
  40061. // pending information if this property was set after the action was performed.
  40062. sourceUpdater.queuePending[type] = queueEntry;
  40063. queueEntry.action(type, sourceUpdater);
  40064. if (!queueEntry.doneFn) {
  40065. // synchronous operation, process next entry
  40066. sourceUpdater.queuePending[type] = null;
  40067. shiftQueue(type, sourceUpdater);
  40068. return;
  40069. }
  40070. };
  40071. const cleanupBuffer = (type, sourceUpdater) => {
  40072. const buffer = sourceUpdater[`${type}Buffer`];
  40073. const titleType = toTitleCase(type);
  40074. if (!buffer) {
  40075. return;
  40076. }
  40077. buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  40078. buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  40079. sourceUpdater.codecs[type] = null;
  40080. sourceUpdater[`${type}Buffer`] = null;
  40081. };
  40082. const inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  40083. const actions = {
  40084. appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {
  40085. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  40086. // or the media source does not contain this source buffer.
  40087. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  40088. return;
  40089. }
  40090. sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);
  40091. try {
  40092. sourceBuffer.appendBuffer(bytes);
  40093. } catch (e) {
  40094. sourceUpdater.logger_(`Error with code ${e.code} ` + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);
  40095. sourceUpdater.queuePending[type] = null;
  40096. onError(e);
  40097. }
  40098. },
  40099. remove: (start, end) => (type, sourceUpdater) => {
  40100. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  40101. // or the media source does not contain this source buffer.
  40102. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  40103. return;
  40104. }
  40105. sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);
  40106. try {
  40107. sourceBuffer.remove(start, end);
  40108. } catch (e) {
  40109. sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);
  40110. }
  40111. },
  40112. timestampOffset: offset => (type, sourceUpdater) => {
  40113. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  40114. // or the media source does not contain this source buffer.
  40115. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  40116. return;
  40117. }
  40118. sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);
  40119. sourceBuffer.timestampOffset = offset;
  40120. },
  40121. callback: callback => (type, sourceUpdater) => {
  40122. callback();
  40123. },
  40124. endOfStream: error => sourceUpdater => {
  40125. if (sourceUpdater.mediaSource.readyState !== 'open') {
  40126. return;
  40127. }
  40128. sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);
  40129. try {
  40130. sourceUpdater.mediaSource.endOfStream(error);
  40131. } catch (e) {
  40132. videojs.log.warn('Failed to call media source endOfStream', e);
  40133. }
  40134. },
  40135. duration: duration => sourceUpdater => {
  40136. sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);
  40137. try {
  40138. sourceUpdater.mediaSource.duration = duration;
  40139. } catch (e) {
  40140. videojs.log.warn('Failed to set media source duration', e);
  40141. }
  40142. },
  40143. abort: () => (type, sourceUpdater) => {
  40144. if (sourceUpdater.mediaSource.readyState !== 'open') {
  40145. return;
  40146. }
  40147. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  40148. // or the media source does not contain this source buffer.
  40149. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  40150. return;
  40151. }
  40152. sourceUpdater.logger_(`calling abort on ${type}Buffer`);
  40153. try {
  40154. sourceBuffer.abort();
  40155. } catch (e) {
  40156. videojs.log.warn(`Failed to abort on ${type}Buffer`, e);
  40157. }
  40158. },
  40159. addSourceBuffer: (type, codec) => sourceUpdater => {
  40160. const titleType = toTitleCase(type);
  40161. const mime = getMimeForCodec(codec);
  40162. sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);
  40163. const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  40164. sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  40165. sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  40166. sourceUpdater.codecs[type] = codec;
  40167. sourceUpdater[`${type}Buffer`] = sourceBuffer;
  40168. },
  40169. removeSourceBuffer: type => sourceUpdater => {
  40170. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  40171. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  40172. // or the media source does not contain this source buffer.
  40173. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  40174. return;
  40175. }
  40176. sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);
  40177. try {
  40178. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  40179. } catch (e) {
  40180. videojs.log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);
  40181. }
  40182. },
  40183. changeType: codec => (type, sourceUpdater) => {
  40184. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  40185. const mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  40186. // or the media source does not contain this source buffer.
  40187. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  40188. return;
  40189. } // do not update codec if we don't need to.
  40190. if (sourceUpdater.codecs[type] === codec) {
  40191. return;
  40192. }
  40193. sourceUpdater.logger_(`changing ${type}Buffer codec from ${sourceUpdater.codecs[type]} to ${codec}`);
  40194. sourceBuffer.changeType(mime);
  40195. sourceUpdater.codecs[type] = codec;
  40196. }
  40197. };
  40198. const pushQueue = ({
  40199. type,
  40200. sourceUpdater,
  40201. action,
  40202. doneFn,
  40203. name
  40204. }) => {
  40205. sourceUpdater.queue.push({
  40206. type,
  40207. action,
  40208. doneFn,
  40209. name
  40210. });
  40211. shiftQueue(type, sourceUpdater);
  40212. };
  40213. const onUpdateend = (type, sourceUpdater) => e => {
  40214. // Although there should, in theory, be a pending action for any updateend receieved,
  40215. // there are some actions that may trigger updateend events without set definitions in
  40216. // the w3c spec. For instance, setting the duration on the media source may trigger
  40217. // updateend events on source buffers. This does not appear to be in the spec. As such,
  40218. // if we encounter an updateend without a corresponding pending action from our queue
  40219. // for that source buffer type, process the next action.
  40220. if (sourceUpdater.queuePending[type]) {
  40221. const doneFn = sourceUpdater.queuePending[type].doneFn;
  40222. sourceUpdater.queuePending[type] = null;
  40223. if (doneFn) {
  40224. // if there's an error, report it
  40225. doneFn(sourceUpdater[`${type}Error_`]);
  40226. }
  40227. }
  40228. shiftQueue(type, sourceUpdater);
  40229. };
  40230. /**
  40231. * A queue of callbacks to be serialized and applied when a
  40232. * MediaSource and its associated SourceBuffers are not in the
  40233. * updating state. It is used by the segment loader to update the
  40234. * underlying SourceBuffers when new data is loaded, for instance.
  40235. *
  40236. * @class SourceUpdater
  40237. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  40238. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  40239. */
  40240. class SourceUpdater extends videojs.EventTarget {
  40241. constructor(mediaSource) {
  40242. super();
  40243. this.mediaSource = mediaSource;
  40244. this.sourceopenListener_ = () => shiftQueue('mediaSource', this);
  40245. this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);
  40246. this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  40247. this.audioTimestampOffset_ = 0;
  40248. this.videoTimestampOffset_ = 0;
  40249. this.queue = [];
  40250. this.queuePending = {
  40251. audio: null,
  40252. video: null
  40253. };
  40254. this.delayedAudioAppendQueue_ = [];
  40255. this.videoAppendQueued_ = false;
  40256. this.codecs = {};
  40257. this.onVideoUpdateEnd_ = onUpdateend('video', this);
  40258. this.onAudioUpdateEnd_ = onUpdateend('audio', this);
  40259. this.onVideoError_ = e => {
  40260. // used for debugging
  40261. this.videoError_ = e;
  40262. };
  40263. this.onAudioError_ = e => {
  40264. // used for debugging
  40265. this.audioError_ = e;
  40266. };
  40267. this.createdSourceBuffers_ = false;
  40268. this.initializedEme_ = false;
  40269. this.triggeredReady_ = false;
  40270. }
  40271. initializedEme() {
  40272. this.initializedEme_ = true;
  40273. this.triggerReady();
  40274. }
  40275. hasCreatedSourceBuffers() {
  40276. // if false, likely waiting on one of the segment loaders to get enough data to create
  40277. // source buffers
  40278. return this.createdSourceBuffers_;
  40279. }
  40280. hasInitializedAnyEme() {
  40281. return this.initializedEme_;
  40282. }
  40283. ready() {
  40284. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  40285. }
  40286. createSourceBuffers(codecs) {
  40287. if (this.hasCreatedSourceBuffers()) {
  40288. // already created them before
  40289. return;
  40290. } // the intial addOrChangeSourceBuffers will always be
  40291. // two add buffers.
  40292. this.addOrChangeSourceBuffers(codecs);
  40293. this.createdSourceBuffers_ = true;
  40294. this.trigger('createdsourcebuffers');
  40295. this.triggerReady();
  40296. }
  40297. triggerReady() {
  40298. // only allow ready to be triggered once, this prevents the case
  40299. // where:
  40300. // 1. we trigger createdsourcebuffers
  40301. // 2. ie 11 synchronously initializates eme
  40302. // 3. the synchronous initialization causes us to trigger ready
  40303. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  40304. if (this.ready() && !this.triggeredReady_) {
  40305. this.triggeredReady_ = true;
  40306. this.trigger('ready');
  40307. }
  40308. }
  40309. /**
  40310. * Add a type of source buffer to the media source.
  40311. *
  40312. * @param {string} type
  40313. * The type of source buffer to add.
  40314. *
  40315. * @param {string} codec
  40316. * The codec to add the source buffer with.
  40317. */
  40318. addSourceBuffer(type, codec) {
  40319. pushQueue({
  40320. type: 'mediaSource',
  40321. sourceUpdater: this,
  40322. action: actions.addSourceBuffer(type, codec),
  40323. name: 'addSourceBuffer'
  40324. });
  40325. }
  40326. /**
  40327. * call abort on a source buffer.
  40328. *
  40329. * @param {string} type
  40330. * The type of source buffer to call abort on.
  40331. */
  40332. abort(type) {
  40333. pushQueue({
  40334. type,
  40335. sourceUpdater: this,
  40336. action: actions.abort(type),
  40337. name: 'abort'
  40338. });
  40339. }
  40340. /**
  40341. * Call removeSourceBuffer and remove a specific type
  40342. * of source buffer on the mediaSource.
  40343. *
  40344. * @param {string} type
  40345. * The type of source buffer to remove.
  40346. */
  40347. removeSourceBuffer(type) {
  40348. if (!this.canRemoveSourceBuffer()) {
  40349. videojs.log.error('removeSourceBuffer is not supported!');
  40350. return;
  40351. }
  40352. pushQueue({
  40353. type: 'mediaSource',
  40354. sourceUpdater: this,
  40355. action: actions.removeSourceBuffer(type),
  40356. name: 'removeSourceBuffer'
  40357. });
  40358. }
  40359. /**
  40360. * Whether or not the removeSourceBuffer function is supported
  40361. * on the mediaSource.
  40362. *
  40363. * @return {boolean}
  40364. * if removeSourceBuffer can be called.
  40365. */
  40366. canRemoveSourceBuffer() {
  40367. // IE reports that it supports removeSourceBuffer, but often throws
  40368. // errors when attempting to use the function. So we report that it
  40369. // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
  40370. // throws errors, so we report that it does not support this as well.
  40371. return !videojs.browser.IE_VERSION && !videojs.browser.IS_FIREFOX && window$1.MediaSource && window$1.MediaSource.prototype && typeof window$1.MediaSource.prototype.removeSourceBuffer === 'function';
  40372. }
  40373. /**
  40374. * Whether or not the changeType function is supported
  40375. * on our SourceBuffers.
  40376. *
  40377. * @return {boolean}
  40378. * if changeType can be called.
  40379. */
  40380. static canChangeType() {
  40381. return window$1.SourceBuffer && window$1.SourceBuffer.prototype && typeof window$1.SourceBuffer.prototype.changeType === 'function';
  40382. }
  40383. /**
  40384. * Whether or not the changeType function is supported
  40385. * on our SourceBuffers.
  40386. *
  40387. * @return {boolean}
  40388. * if changeType can be called.
  40389. */
  40390. canChangeType() {
  40391. return this.constructor.canChangeType();
  40392. }
  40393. /**
  40394. * Call the changeType function on a source buffer, given the code and type.
  40395. *
  40396. * @param {string} type
  40397. * The type of source buffer to call changeType on.
  40398. *
  40399. * @param {string} codec
  40400. * The codec string to change type with on the source buffer.
  40401. */
  40402. changeType(type, codec) {
  40403. if (!this.canChangeType()) {
  40404. videojs.log.error('changeType is not supported!');
  40405. return;
  40406. }
  40407. pushQueue({
  40408. type,
  40409. sourceUpdater: this,
  40410. action: actions.changeType(codec),
  40411. name: 'changeType'
  40412. });
  40413. }
  40414. /**
  40415. * Add source buffers with a codec or, if they are already created,
  40416. * call changeType on source buffers using changeType.
  40417. *
  40418. * @param {Object} codecs
  40419. * Codecs to switch to
  40420. */
  40421. addOrChangeSourceBuffers(codecs) {
  40422. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  40423. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  40424. }
  40425. Object.keys(codecs).forEach(type => {
  40426. const codec = codecs[type];
  40427. if (!this.hasCreatedSourceBuffers()) {
  40428. return this.addSourceBuffer(type, codec);
  40429. }
  40430. if (this.canChangeType()) {
  40431. this.changeType(type, codec);
  40432. }
  40433. });
  40434. }
  40435. /**
  40436. * Queue an update to append an ArrayBuffer.
  40437. *
  40438. * @param {MediaObject} object containing audioBytes and/or videoBytes
  40439. * @param {Function} done the function to call when done
  40440. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  40441. */
  40442. appendBuffer(options, doneFn) {
  40443. const {
  40444. segmentInfo,
  40445. type,
  40446. bytes
  40447. } = options;
  40448. this.processedAppend_ = true;
  40449. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  40450. this.delayedAudioAppendQueue_.push([options, doneFn]);
  40451. this.logger_(`delayed audio append of ${bytes.length} until video append`);
  40452. return;
  40453. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  40454. // not be fired. This means that the queue will be blocked until the next action
  40455. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  40456. // these errors by calling the doneFn with the specific error.
  40457. const onError = doneFn;
  40458. pushQueue({
  40459. type,
  40460. sourceUpdater: this,
  40461. action: actions.appendBuffer(bytes, segmentInfo || {
  40462. mediaIndex: -1
  40463. }, onError),
  40464. doneFn,
  40465. name: 'appendBuffer'
  40466. });
  40467. if (type === 'video') {
  40468. this.videoAppendQueued_ = true;
  40469. if (!this.delayedAudioAppendQueue_.length) {
  40470. return;
  40471. }
  40472. const queue = this.delayedAudioAppendQueue_.slice();
  40473. this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);
  40474. this.delayedAudioAppendQueue_.length = 0;
  40475. queue.forEach(que => {
  40476. this.appendBuffer.apply(this, que);
  40477. });
  40478. }
  40479. }
  40480. /**
  40481. * Get the audio buffer's buffered timerange.
  40482. *
  40483. * @return {TimeRange}
  40484. * The audio buffer's buffered time range
  40485. */
  40486. audioBuffered() {
  40487. // no media source/source buffer or it isn't in the media sources
  40488. // source buffer list
  40489. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  40490. return createTimeRanges();
  40491. }
  40492. return this.audioBuffer.buffered ? this.audioBuffer.buffered : createTimeRanges();
  40493. }
  40494. /**
  40495. * Get the video buffer's buffered timerange.
  40496. *
  40497. * @return {TimeRange}
  40498. * The video buffer's buffered time range
  40499. */
  40500. videoBuffered() {
  40501. // no media source/source buffer or it isn't in the media sources
  40502. // source buffer list
  40503. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  40504. return createTimeRanges();
  40505. }
  40506. return this.videoBuffer.buffered ? this.videoBuffer.buffered : createTimeRanges();
  40507. }
  40508. /**
  40509. * Get a combined video/audio buffer's buffered timerange.
  40510. *
  40511. * @return {TimeRange}
  40512. * the combined time range
  40513. */
  40514. buffered() {
  40515. const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  40516. const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  40517. if (audio && !video) {
  40518. return this.audioBuffered();
  40519. }
  40520. if (video && !audio) {
  40521. return this.videoBuffered();
  40522. }
  40523. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  40524. }
  40525. /**
  40526. * Add a callback to the queue that will set duration on the mediaSource.
  40527. *
  40528. * @param {number} duration
  40529. * The duration to set
  40530. *
  40531. * @param {Function} [doneFn]
  40532. * function to run after duration has been set.
  40533. */
  40534. setDuration(duration, doneFn = noop) {
  40535. // In order to set the duration on the media source, it's necessary to wait for all
  40536. // source buffers to no longer be updating. "If the updating attribute equals true on
  40537. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  40538. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  40539. pushQueue({
  40540. type: 'mediaSource',
  40541. sourceUpdater: this,
  40542. action: actions.duration(duration),
  40543. name: 'duration',
  40544. doneFn
  40545. });
  40546. }
  40547. /**
  40548. * Add a mediaSource endOfStream call to the queue
  40549. *
  40550. * @param {Error} [error]
  40551. * Call endOfStream with an error
  40552. *
  40553. * @param {Function} [doneFn]
  40554. * A function that should be called when the
  40555. * endOfStream call has finished.
  40556. */
  40557. endOfStream(error = null, doneFn = noop) {
  40558. if (typeof error !== 'string') {
  40559. error = undefined;
  40560. } // In order to set the duration on the media source, it's necessary to wait for all
  40561. // source buffers to no longer be updating. "If the updating attribute equals true on
  40562. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  40563. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  40564. pushQueue({
  40565. type: 'mediaSource',
  40566. sourceUpdater: this,
  40567. action: actions.endOfStream(error),
  40568. name: 'endOfStream',
  40569. doneFn
  40570. });
  40571. }
  40572. /**
  40573. * Queue an update to remove a time range from the buffer.
  40574. *
  40575. * @param {number} start where to start the removal
  40576. * @param {number} end where to end the removal
  40577. * @param {Function} [done=noop] optional callback to be executed when the remove
  40578. * operation is complete
  40579. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  40580. */
  40581. removeAudio(start, end, done = noop) {
  40582. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  40583. done();
  40584. return;
  40585. }
  40586. pushQueue({
  40587. type: 'audio',
  40588. sourceUpdater: this,
  40589. action: actions.remove(start, end),
  40590. doneFn: done,
  40591. name: 'remove'
  40592. });
  40593. }
  40594. /**
  40595. * Queue an update to remove a time range from the buffer.
  40596. *
  40597. * @param {number} start where to start the removal
  40598. * @param {number} end where to end the removal
  40599. * @param {Function} [done=noop] optional callback to be executed when the remove
  40600. * operation is complete
  40601. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  40602. */
  40603. removeVideo(start, end, done = noop) {
  40604. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  40605. done();
  40606. return;
  40607. }
  40608. pushQueue({
  40609. type: 'video',
  40610. sourceUpdater: this,
  40611. action: actions.remove(start, end),
  40612. doneFn: done,
  40613. name: 'remove'
  40614. });
  40615. }
  40616. /**
  40617. * Whether the underlying sourceBuffer is updating or not
  40618. *
  40619. * @return {boolean} the updating status of the SourceBuffer
  40620. */
  40621. updating() {
  40622. // the audio/video source buffer is updating
  40623. if (updating('audio', this) || updating('video', this)) {
  40624. return true;
  40625. }
  40626. return false;
  40627. }
  40628. /**
  40629. * Set/get the timestampoffset on the audio SourceBuffer
  40630. *
  40631. * @return {number} the timestamp offset
  40632. */
  40633. audioTimestampOffset(offset) {
  40634. if (typeof offset !== 'undefined' && this.audioBuffer &&
  40635. // no point in updating if it's the same
  40636. this.audioTimestampOffset_ !== offset) {
  40637. pushQueue({
  40638. type: 'audio',
  40639. sourceUpdater: this,
  40640. action: actions.timestampOffset(offset),
  40641. name: 'timestampOffset'
  40642. });
  40643. this.audioTimestampOffset_ = offset;
  40644. }
  40645. return this.audioTimestampOffset_;
  40646. }
  40647. /**
  40648. * Set/get the timestampoffset on the video SourceBuffer
  40649. *
  40650. * @return {number} the timestamp offset
  40651. */
  40652. videoTimestampOffset(offset) {
  40653. if (typeof offset !== 'undefined' && this.videoBuffer &&
  40654. // no point in updating if it's the same
  40655. this.videoTimestampOffset !== offset) {
  40656. pushQueue({
  40657. type: 'video',
  40658. sourceUpdater: this,
  40659. action: actions.timestampOffset(offset),
  40660. name: 'timestampOffset'
  40661. });
  40662. this.videoTimestampOffset_ = offset;
  40663. }
  40664. return this.videoTimestampOffset_;
  40665. }
  40666. /**
  40667. * Add a function to the queue that will be called
  40668. * when it is its turn to run in the audio queue.
  40669. *
  40670. * @param {Function} callback
  40671. * The callback to queue.
  40672. */
  40673. audioQueueCallback(callback) {
  40674. if (!this.audioBuffer) {
  40675. return;
  40676. }
  40677. pushQueue({
  40678. type: 'audio',
  40679. sourceUpdater: this,
  40680. action: actions.callback(callback),
  40681. name: 'callback'
  40682. });
  40683. }
  40684. /**
  40685. * Add a function to the queue that will be called
  40686. * when it is its turn to run in the video queue.
  40687. *
  40688. * @param {Function} callback
  40689. * The callback to queue.
  40690. */
  40691. videoQueueCallback(callback) {
  40692. if (!this.videoBuffer) {
  40693. return;
  40694. }
  40695. pushQueue({
  40696. type: 'video',
  40697. sourceUpdater: this,
  40698. action: actions.callback(callback),
  40699. name: 'callback'
  40700. });
  40701. }
  40702. /**
  40703. * dispose of the source updater and the underlying sourceBuffer
  40704. */
  40705. dispose() {
  40706. this.trigger('dispose');
  40707. bufferTypes.forEach(type => {
  40708. this.abort(type);
  40709. if (this.canRemoveSourceBuffer()) {
  40710. this.removeSourceBuffer(type);
  40711. } else {
  40712. this[`${type}QueueCallback`](() => cleanupBuffer(type, this));
  40713. }
  40714. });
  40715. this.videoAppendQueued_ = false;
  40716. this.delayedAudioAppendQueue_.length = 0;
  40717. if (this.sourceopenListener_) {
  40718. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  40719. }
  40720. this.off();
  40721. }
  40722. }
  40723. const uint8ToUtf8 = uintArray => decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  40724. /**
  40725. * @file vtt-segment-loader.js
  40726. */
  40727. const VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(char => char.charCodeAt(0)));
  40728. class NoVttJsError extends Error {
  40729. constructor() {
  40730. super('Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.');
  40731. }
  40732. }
  40733. /**
  40734. * An object that manages segment loading and appending.
  40735. *
  40736. * @class VTTSegmentLoader
  40737. * @param {Object} options required and optional options
  40738. * @extends videojs.EventTarget
  40739. */
  40740. class VTTSegmentLoader extends SegmentLoader {
  40741. constructor(settings, options = {}) {
  40742. super(settings, options); // SegmentLoader requires a MediaSource be specified or it will throw an error;
  40743. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  40744. this.mediaSource_ = null;
  40745. this.subtitlesTrack_ = null;
  40746. this.loaderType_ = 'subtitle';
  40747. this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  40748. this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  40749. // the sync controller leads to improper behavior.
  40750. this.shouldSaveSegmentTimingInfo_ = false;
  40751. }
  40752. createTransmuxer_() {
  40753. // don't need to transmux any subtitles
  40754. return null;
  40755. }
  40756. /**
  40757. * Indicates which time ranges are buffered
  40758. *
  40759. * @return {TimeRange}
  40760. * TimeRange object representing the current buffered ranges
  40761. */
  40762. buffered_() {
  40763. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  40764. return createTimeRanges();
  40765. }
  40766. const cues = this.subtitlesTrack_.cues;
  40767. const start = cues[0].startTime;
  40768. const end = cues[cues.length - 1].startTime;
  40769. return createTimeRanges([[start, end]]);
  40770. }
  40771. /**
  40772. * Gets and sets init segment for the provided map
  40773. *
  40774. * @param {Object} map
  40775. * The map object representing the init segment to get or set
  40776. * @param {boolean=} set
  40777. * If true, the init segment for the provided map should be saved
  40778. * @return {Object}
  40779. * map object for desired init segment
  40780. */
  40781. initSegmentForMap(map, set = false) {
  40782. if (!map) {
  40783. return null;
  40784. }
  40785. const id = initSegmentId(map);
  40786. let storedMap = this.initSegments_[id];
  40787. if (set && !storedMap && map.bytes) {
  40788. // append WebVTT line terminators to the media initialization segment if it exists
  40789. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  40790. // requires two or more WebVTT line terminators between the WebVTT header and the
  40791. // rest of the file
  40792. const combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  40793. const combinedSegment = new Uint8Array(combinedByteLength);
  40794. combinedSegment.set(map.bytes);
  40795. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  40796. this.initSegments_[id] = storedMap = {
  40797. resolvedUri: map.resolvedUri,
  40798. byterange: map.byterange,
  40799. bytes: combinedSegment
  40800. };
  40801. }
  40802. return storedMap || map;
  40803. }
  40804. /**
  40805. * Returns true if all configuration required for loading is present, otherwise false.
  40806. *
  40807. * @return {boolean} True if the all configuration is ready for loading
  40808. * @private
  40809. */
  40810. couldBeginLoading_() {
  40811. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  40812. }
  40813. /**
  40814. * Once all the starting parameters have been specified, begin
  40815. * operation. This method should only be invoked from the INIT
  40816. * state.
  40817. *
  40818. * @private
  40819. */
  40820. init_() {
  40821. this.state = 'READY';
  40822. this.resetEverything();
  40823. return this.monitorBuffer_();
  40824. }
  40825. /**
  40826. * Set a subtitle track on the segment loader to add subtitles to
  40827. *
  40828. * @param {TextTrack=} track
  40829. * The text track to add loaded subtitles to
  40830. * @return {TextTrack}
  40831. * Returns the subtitles track
  40832. */
  40833. track(track) {
  40834. if (typeof track === 'undefined') {
  40835. return this.subtitlesTrack_;
  40836. }
  40837. this.subtitlesTrack_ = track; // if we were unpaused but waiting for a sourceUpdater, start
  40838. // buffering now
  40839. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  40840. this.init_();
  40841. }
  40842. return this.subtitlesTrack_;
  40843. }
  40844. /**
  40845. * Remove any data in the source buffer between start and end times
  40846. *
  40847. * @param {number} start - the start time of the region to remove from the buffer
  40848. * @param {number} end - the end time of the region to remove from the buffer
  40849. */
  40850. remove(start, end) {
  40851. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  40852. }
  40853. /**
  40854. * fill the buffer with segements unless the sourceBuffers are
  40855. * currently updating
  40856. *
  40857. * Note: this function should only ever be called by monitorBuffer_
  40858. * and never directly
  40859. *
  40860. * @private
  40861. */
  40862. fillBuffer_() {
  40863. // see if we need to begin loading immediately
  40864. const segmentInfo = this.chooseNextRequest_();
  40865. if (!segmentInfo) {
  40866. return;
  40867. }
  40868. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  40869. // We don't have the timestamp offset that we need to sync subtitles.
  40870. // Rerun on a timestamp offset or user interaction.
  40871. const checkTimestampOffset = () => {
  40872. this.state = 'READY';
  40873. if (!this.paused()) {
  40874. // if not paused, queue a buffer check as soon as possible
  40875. this.monitorBuffer_();
  40876. }
  40877. };
  40878. this.syncController_.one('timestampoffset', checkTimestampOffset);
  40879. this.state = 'WAITING_ON_TIMELINE';
  40880. return;
  40881. }
  40882. this.loadSegment_(segmentInfo);
  40883. } // never set a timestamp offset for vtt segments.
  40884. timestampOffsetForSegment_() {
  40885. return null;
  40886. }
  40887. chooseNextRequest_() {
  40888. return this.skipEmptySegments_(super.chooseNextRequest_());
  40889. }
  40890. /**
  40891. * Prevents the segment loader from requesting segments we know contain no subtitles
  40892. * by walking forward until we find the next segment that we don't know whether it is
  40893. * empty or not.
  40894. *
  40895. * @param {Object} segmentInfo
  40896. * a segment info object that describes the current segment
  40897. * @return {Object}
  40898. * a segment info object that describes the current segment
  40899. */
  40900. skipEmptySegments_(segmentInfo) {
  40901. while (segmentInfo && segmentInfo.segment.empty) {
  40902. // stop at the last possible segmentInfo
  40903. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  40904. segmentInfo = null;
  40905. break;
  40906. }
  40907. segmentInfo = this.generateSegmentInfo_({
  40908. playlist: segmentInfo.playlist,
  40909. mediaIndex: segmentInfo.mediaIndex + 1,
  40910. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  40911. isSyncRequest: segmentInfo.isSyncRequest
  40912. });
  40913. }
  40914. return segmentInfo;
  40915. }
  40916. stopForError(error) {
  40917. this.error(error);
  40918. this.state = 'READY';
  40919. this.pause();
  40920. this.trigger('error');
  40921. }
  40922. /**
  40923. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  40924. *
  40925. * @private
  40926. */
  40927. segmentRequestFinished_(error, simpleSegment, result) {
  40928. if (!this.subtitlesTrack_) {
  40929. this.state = 'READY';
  40930. return;
  40931. }
  40932. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  40933. if (!this.pendingSegment_) {
  40934. this.state = 'READY';
  40935. this.mediaRequestsAborted += 1;
  40936. return;
  40937. }
  40938. if (error) {
  40939. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  40940. this.handleTimeout_();
  40941. }
  40942. if (error.code === REQUEST_ERRORS.ABORTED) {
  40943. this.mediaRequestsAborted += 1;
  40944. } else {
  40945. this.mediaRequestsErrored += 1;
  40946. }
  40947. this.stopForError(error);
  40948. return;
  40949. }
  40950. const segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  40951. // maintain functionality between segment loaders
  40952. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  40953. if (simpleSegment.key) {
  40954. this.segmentKey(simpleSegment.key, true);
  40955. }
  40956. this.state = 'APPENDING'; // used for tests
  40957. this.trigger('appending');
  40958. const segment = segmentInfo.segment;
  40959. if (segment.map) {
  40960. segment.map.bytes = simpleSegment.map.bytes;
  40961. }
  40962. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  40963. if (typeof window$1.WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  40964. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  40965. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  40966. this.loadVttJs().then(() => this.segmentRequestFinished_(error, simpleSegment, result), () => this.stopForError({
  40967. message: 'Error loading vtt.js'
  40968. }));
  40969. return;
  40970. }
  40971. segment.requested = true;
  40972. try {
  40973. this.parseVTTCues_(segmentInfo);
  40974. } catch (e) {
  40975. this.stopForError({
  40976. message: e.message
  40977. });
  40978. return;
  40979. }
  40980. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  40981. if (segmentInfo.cues.length) {
  40982. segmentInfo.timingInfo = {
  40983. start: segmentInfo.cues[0].startTime,
  40984. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  40985. };
  40986. } else {
  40987. segmentInfo.timingInfo = {
  40988. start: segmentInfo.startOfSegment,
  40989. end: segmentInfo.startOfSegment + segmentInfo.duration
  40990. };
  40991. }
  40992. if (segmentInfo.isSyncRequest) {
  40993. this.trigger('syncinfoupdate');
  40994. this.pendingSegment_ = null;
  40995. this.state = 'READY';
  40996. return;
  40997. }
  40998. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  40999. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  41000. // the subtitle track
  41001. segmentInfo.cues.forEach(cue => {
  41002. this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_ ? new window$1.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  41003. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  41004. // cues to have identical time-intervals, but if the text is also identical
  41005. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  41006. // "overlaps" VTT segments)
  41007. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  41008. this.handleAppendsDone_();
  41009. }
  41010. handleData_() {// noop as we shouldn't be getting video/audio data captions
  41011. // that we do not support here.
  41012. }
  41013. updateTimingInfoEnd_() {// noop
  41014. }
  41015. /**
  41016. * Uses the WebVTT parser to parse the segment response
  41017. *
  41018. * @throws NoVttJsError
  41019. *
  41020. * @param {Object} segmentInfo
  41021. * a segment info object that describes the current segment
  41022. * @private
  41023. */
  41024. parseVTTCues_(segmentInfo) {
  41025. let decoder;
  41026. let decodeBytesToString = false;
  41027. if (typeof window$1.WebVTT !== 'function') {
  41028. // caller is responsible for exception handling.
  41029. throw new NoVttJsError();
  41030. }
  41031. if (typeof window$1.TextDecoder === 'function') {
  41032. decoder = new window$1.TextDecoder('utf8');
  41033. } else {
  41034. decoder = window$1.WebVTT.StringDecoder();
  41035. decodeBytesToString = true;
  41036. }
  41037. const parser = new window$1.WebVTT.Parser(window$1, window$1.vttjs, decoder);
  41038. segmentInfo.cues = [];
  41039. segmentInfo.timestampmap = {
  41040. MPEGTS: 0,
  41041. LOCAL: 0
  41042. };
  41043. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  41044. parser.ontimestampmap = map => {
  41045. segmentInfo.timestampmap = map;
  41046. };
  41047. parser.onparsingerror = error => {
  41048. videojs.log.warn('Error encountered when parsing cues: ' + error.message);
  41049. };
  41050. if (segmentInfo.segment.map) {
  41051. let mapData = segmentInfo.segment.map.bytes;
  41052. if (decodeBytesToString) {
  41053. mapData = uint8ToUtf8(mapData);
  41054. }
  41055. parser.parse(mapData);
  41056. }
  41057. let segmentData = segmentInfo.bytes;
  41058. if (decodeBytesToString) {
  41059. segmentData = uint8ToUtf8(segmentData);
  41060. }
  41061. parser.parse(segmentData);
  41062. parser.flush();
  41063. }
  41064. /**
  41065. * Updates the start and end times of any cues parsed by the WebVTT parser using
  41066. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  41067. * from the SyncController
  41068. *
  41069. * @param {Object} segmentInfo
  41070. * a segment info object that describes the current segment
  41071. * @param {Object} mappingObj
  41072. * object containing a mapping from TS to media time
  41073. * @param {Object} playlist
  41074. * the playlist object containing the segment
  41075. * @private
  41076. */
  41077. updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  41078. const segment = segmentInfo.segment;
  41079. if (!mappingObj) {
  41080. // If the sync controller does not have a mapping of TS to Media Time for the
  41081. // timeline, then we don't have enough information to update the cue
  41082. // start/end times
  41083. return;
  41084. }
  41085. if (!segmentInfo.cues.length) {
  41086. // If there are no cues, we also do not have enough information to figure out
  41087. // segment timing. Mark that the segment contains no cues so we don't re-request
  41088. // an empty segment.
  41089. segment.empty = true;
  41090. return;
  41091. }
  41092. const timestampmap = segmentInfo.timestampmap;
  41093. const diff = timestampmap.MPEGTS / ONE_SECOND_IN_TS - timestampmap.LOCAL + mappingObj.mapping;
  41094. segmentInfo.cues.forEach(cue => {
  41095. // First convert cue time to TS time using the timestamp-map provided within the vtt
  41096. cue.startTime += diff;
  41097. cue.endTime += diff;
  41098. });
  41099. if (!playlist.syncInfo) {
  41100. const firstStart = segmentInfo.cues[0].startTime;
  41101. const lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  41102. playlist.syncInfo = {
  41103. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  41104. time: Math.min(firstStart, lastStart - segment.duration)
  41105. };
  41106. }
  41107. }
  41108. }
  41109. /**
  41110. * @file ad-cue-tags.js
  41111. */
  41112. /**
  41113. * Searches for an ad cue that overlaps with the given mediaTime
  41114. *
  41115. * @param {Object} track
  41116. * the track to find the cue for
  41117. *
  41118. * @param {number} mediaTime
  41119. * the time to find the cue at
  41120. *
  41121. * @return {Object|null}
  41122. * the found cue or null
  41123. */
  41124. const findAdCue = function (track, mediaTime) {
  41125. const cues = track.cues;
  41126. for (let i = 0; i < cues.length; i++) {
  41127. const cue = cues[i];
  41128. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  41129. return cue;
  41130. }
  41131. }
  41132. return null;
  41133. };
  41134. const updateAdCues = function (media, track, offset = 0) {
  41135. if (!media.segments) {
  41136. return;
  41137. }
  41138. let mediaTime = offset;
  41139. let cue;
  41140. for (let i = 0; i < media.segments.length; i++) {
  41141. const segment = media.segments[i];
  41142. if (!cue) {
  41143. // Since the cues will span for at least the segment duration, adding a fudge
  41144. // factor of half segment duration will prevent duplicate cues from being
  41145. // created when timing info is not exact (e.g. cue start time initialized
  41146. // at 10.006677, but next call mediaTime is 10.003332 )
  41147. cue = findAdCue(track, mediaTime + segment.duration / 2);
  41148. }
  41149. if (cue) {
  41150. if ('cueIn' in segment) {
  41151. // Found a CUE-IN so end the cue
  41152. cue.endTime = mediaTime;
  41153. cue.adEndTime = mediaTime;
  41154. mediaTime += segment.duration;
  41155. cue = null;
  41156. continue;
  41157. }
  41158. if (mediaTime < cue.endTime) {
  41159. // Already processed this mediaTime for this cue
  41160. mediaTime += segment.duration;
  41161. continue;
  41162. } // otherwise extend cue until a CUE-IN is found
  41163. cue.endTime += segment.duration;
  41164. } else {
  41165. if ('cueOut' in segment) {
  41166. cue = new window$1.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  41167. cue.adStartTime = mediaTime; // Assumes tag format to be
  41168. // #EXT-X-CUE-OUT:30
  41169. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  41170. track.addCue(cue);
  41171. }
  41172. if ('cueOutCont' in segment) {
  41173. // Entered into the middle of an ad cue
  41174. // Assumes tag formate to be
  41175. // #EXT-X-CUE-OUT-CONT:10/30
  41176. const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);
  41177. cue = new window$1.VTTCue(mediaTime, mediaTime + segment.duration, '');
  41178. cue.adStartTime = mediaTime - adOffset;
  41179. cue.adEndTime = cue.adStartTime + adTotal;
  41180. track.addCue(cue);
  41181. }
  41182. }
  41183. mediaTime += segment.duration;
  41184. }
  41185. };
  41186. /**
  41187. * @file sync-controller.js
  41188. */
  41189. // synchronize expired playlist segments.
  41190. // the max media sequence diff is 48 hours of live stream
  41191. // content with two second segments. Anything larger than that
  41192. // will likely be invalid.
  41193. const MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  41194. const syncPointStrategies = [
  41195. // Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  41196. // the equivalence display-time 0 === segment-index 0
  41197. {
  41198. name: 'VOD',
  41199. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  41200. if (duration !== Infinity) {
  41201. const syncPoint = {
  41202. time: 0,
  41203. segmentIndex: 0,
  41204. partIndex: null
  41205. };
  41206. return syncPoint;
  41207. }
  41208. return null;
  41209. }
  41210. },
  41211. // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  41212. {
  41213. name: 'ProgramDateTime',
  41214. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  41215. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  41216. return null;
  41217. }
  41218. let syncPoint = null;
  41219. let lastDistance = null;
  41220. const partsAndSegments = getPartsAndSegments(playlist);
  41221. currentTime = currentTime || 0;
  41222. for (let i = 0; i < partsAndSegments.length; i++) {
  41223. // start from the end and loop backwards for live
  41224. // or start from the front and loop forwards for non-live
  41225. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  41226. const partAndSegment = partsAndSegments[index];
  41227. const segment = partAndSegment.segment;
  41228. const datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  41229. if (!datetimeMapping || !segment.dateTimeObject) {
  41230. continue;
  41231. }
  41232. const segmentTime = segment.dateTimeObject.getTime() / 1000;
  41233. let start = segmentTime + datetimeMapping; // take part duration into account.
  41234. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  41235. for (let z = 0; z < partAndSegment.partIndex; z++) {
  41236. start += segment.parts[z].duration;
  41237. }
  41238. }
  41239. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  41240. // currentTime and can stop looking for better candidates
  41241. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  41242. break;
  41243. }
  41244. lastDistance = distance;
  41245. syncPoint = {
  41246. time: start,
  41247. segmentIndex: partAndSegment.segmentIndex,
  41248. partIndex: partAndSegment.partIndex
  41249. };
  41250. }
  41251. return syncPoint;
  41252. }
  41253. },
  41254. // Stategy "Segment": We have a known time mapping for a timeline and a
  41255. // segment in the current timeline with timing data
  41256. {
  41257. name: 'Segment',
  41258. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  41259. let syncPoint = null;
  41260. let lastDistance = null;
  41261. currentTime = currentTime || 0;
  41262. const partsAndSegments = getPartsAndSegments(playlist);
  41263. for (let i = 0; i < partsAndSegments.length; i++) {
  41264. // start from the end and loop backwards for live
  41265. // or start from the front and loop forwards for non-live
  41266. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  41267. const partAndSegment = partsAndSegments[index];
  41268. const segment = partAndSegment.segment;
  41269. const start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  41270. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  41271. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  41272. // currentTime and can stop looking for better candidates
  41273. if (lastDistance !== null && lastDistance < distance) {
  41274. break;
  41275. }
  41276. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  41277. lastDistance = distance;
  41278. syncPoint = {
  41279. time: start,
  41280. segmentIndex: partAndSegment.segmentIndex,
  41281. partIndex: partAndSegment.partIndex
  41282. };
  41283. }
  41284. }
  41285. }
  41286. return syncPoint;
  41287. }
  41288. },
  41289. // Stategy "Discontinuity": We have a discontinuity with a known
  41290. // display-time
  41291. {
  41292. name: 'Discontinuity',
  41293. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  41294. let syncPoint = null;
  41295. currentTime = currentTime || 0;
  41296. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  41297. let lastDistance = null;
  41298. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  41299. const segmentIndex = playlist.discontinuityStarts[i];
  41300. const discontinuity = playlist.discontinuitySequence + i + 1;
  41301. const discontinuitySync = syncController.discontinuities[discontinuity];
  41302. if (discontinuitySync) {
  41303. const distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  41304. // currentTime and can stop looking for better candidates
  41305. if (lastDistance !== null && lastDistance < distance) {
  41306. break;
  41307. }
  41308. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  41309. lastDistance = distance;
  41310. syncPoint = {
  41311. time: discontinuitySync.time,
  41312. segmentIndex,
  41313. partIndex: null
  41314. };
  41315. }
  41316. }
  41317. }
  41318. }
  41319. return syncPoint;
  41320. }
  41321. },
  41322. // Stategy "Playlist": We have a playlist with a known mapping of
  41323. // segment index to display time
  41324. {
  41325. name: 'Playlist',
  41326. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  41327. if (playlist.syncInfo) {
  41328. const syncPoint = {
  41329. time: playlist.syncInfo.time,
  41330. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  41331. partIndex: null
  41332. };
  41333. return syncPoint;
  41334. }
  41335. return null;
  41336. }
  41337. }];
  41338. class SyncController extends videojs.EventTarget {
  41339. constructor(options = {}) {
  41340. super(); // ...for synching across variants
  41341. this.timelines = [];
  41342. this.discontinuities = [];
  41343. this.timelineToDatetimeMappings = {};
  41344. this.logger_ = logger('SyncController');
  41345. }
  41346. /**
  41347. * Find a sync-point for the playlist specified
  41348. *
  41349. * A sync-point is defined as a known mapping from display-time to
  41350. * a segment-index in the current playlist.
  41351. *
  41352. * @param {Playlist} playlist
  41353. * The playlist that needs a sync-point
  41354. * @param {number} duration
  41355. * Duration of the MediaSource (Infinite if playing a live source)
  41356. * @param {number} currentTimeline
  41357. * The last timeline from which a segment was loaded
  41358. * @return {Object}
  41359. * A sync-point object
  41360. */
  41361. getSyncPoint(playlist, duration, currentTimeline, currentTime) {
  41362. const syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
  41363. if (!syncPoints.length) {
  41364. // Signal that we need to attempt to get a sync-point manually
  41365. // by fetching a segment in the playlist and constructing
  41366. // a sync-point from that information
  41367. return null;
  41368. } // Now find the sync-point that is closest to the currentTime because
  41369. // that should result in the most accurate guess about which segment
  41370. // to fetch
  41371. return this.selectSyncPoint_(syncPoints, {
  41372. key: 'time',
  41373. value: currentTime
  41374. });
  41375. }
  41376. /**
  41377. * Calculate the amount of time that has expired off the playlist during playback
  41378. *
  41379. * @param {Playlist} playlist
  41380. * Playlist object to calculate expired from
  41381. * @param {number} duration
  41382. * Duration of the MediaSource (Infinity if playling a live source)
  41383. * @return {number|null}
  41384. * The amount of time that has expired off the playlist during playback. Null
  41385. * if no sync-points for the playlist can be found.
  41386. */
  41387. getExpiredTime(playlist, duration) {
  41388. if (!playlist || !playlist.segments) {
  41389. return null;
  41390. }
  41391. const syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
  41392. if (!syncPoints.length) {
  41393. return null;
  41394. }
  41395. const syncPoint = this.selectSyncPoint_(syncPoints, {
  41396. key: 'segmentIndex',
  41397. value: 0
  41398. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  41399. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  41400. if (syncPoint.segmentIndex > 0) {
  41401. syncPoint.time *= -1;
  41402. }
  41403. return Math.abs(syncPoint.time + sumDurations({
  41404. defaultDuration: playlist.targetDuration,
  41405. durationList: playlist.segments,
  41406. startIndex: syncPoint.segmentIndex,
  41407. endIndex: 0
  41408. }));
  41409. }
  41410. /**
  41411. * Runs each sync-point strategy and returns a list of sync-points returned by the
  41412. * strategies
  41413. *
  41414. * @private
  41415. * @param {Playlist} playlist
  41416. * The playlist that needs a sync-point
  41417. * @param {number} duration
  41418. * Duration of the MediaSource (Infinity if playing a live source)
  41419. * @param {number} currentTimeline
  41420. * The last timeline from which a segment was loaded
  41421. * @return {Array}
  41422. * A list of sync-point objects
  41423. */
  41424. runStrategies_(playlist, duration, currentTimeline, currentTime) {
  41425. const syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  41426. for (let i = 0; i < syncPointStrategies.length; i++) {
  41427. const strategy = syncPointStrategies[i];
  41428. const syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
  41429. if (syncPoint) {
  41430. syncPoint.strategy = strategy.name;
  41431. syncPoints.push({
  41432. strategy: strategy.name,
  41433. syncPoint
  41434. });
  41435. }
  41436. }
  41437. return syncPoints;
  41438. }
  41439. /**
  41440. * Selects the sync-point nearest the specified target
  41441. *
  41442. * @private
  41443. * @param {Array} syncPoints
  41444. * List of sync-points to select from
  41445. * @param {Object} target
  41446. * Object specifying the property and value we are targeting
  41447. * @param {string} target.key
  41448. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  41449. * @param {number} target.value
  41450. * The value to target for the specified key.
  41451. * @return {Object}
  41452. * The sync-point nearest the target
  41453. */
  41454. selectSyncPoint_(syncPoints, target) {
  41455. let bestSyncPoint = syncPoints[0].syncPoint;
  41456. let bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  41457. let bestStrategy = syncPoints[0].strategy;
  41458. for (let i = 1; i < syncPoints.length; i++) {
  41459. const newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  41460. if (newDistance < bestDistance) {
  41461. bestDistance = newDistance;
  41462. bestSyncPoint = syncPoints[i].syncPoint;
  41463. bestStrategy = syncPoints[i].strategy;
  41464. }
  41465. }
  41466. 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}` : '') + ']');
  41467. return bestSyncPoint;
  41468. }
  41469. /**
  41470. * Save any meta-data present on the segments when segments leave
  41471. * the live window to the playlist to allow for synchronization at the
  41472. * playlist level later.
  41473. *
  41474. * @param {Playlist} oldPlaylist - The previous active playlist
  41475. * @param {Playlist} newPlaylist - The updated and most current playlist
  41476. */
  41477. saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  41478. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  41479. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  41480. videojs.log.warn(`Not saving expired segment info. Media sequence gap ${mediaSequenceDiff} is too large.`);
  41481. return;
  41482. } // When a segment expires from the playlist and it has a start time
  41483. // save that information as a possible sync-point reference in future
  41484. for (let i = mediaSequenceDiff - 1; i >= 0; i--) {
  41485. const lastRemovedSegment = oldPlaylist.segments[i];
  41486. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  41487. newPlaylist.syncInfo = {
  41488. mediaSequence: oldPlaylist.mediaSequence + i,
  41489. time: lastRemovedSegment.start
  41490. };
  41491. this.logger_(`playlist refresh sync: [time:${newPlaylist.syncInfo.time},` + ` mediaSequence: ${newPlaylist.syncInfo.mediaSequence}]`);
  41492. this.trigger('syncinfoupdate');
  41493. break;
  41494. }
  41495. }
  41496. }
  41497. /**
  41498. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  41499. * before segments start to load.
  41500. *
  41501. * @param {Playlist} playlist - The currently active playlist
  41502. */
  41503. setDateTimeMappingForStart(playlist) {
  41504. // It's possible for the playlist to be updated before playback starts, meaning time
  41505. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  41506. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  41507. // unless the mappings are cleared.
  41508. this.timelineToDatetimeMappings = {};
  41509. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  41510. const firstSegment = playlist.segments[0];
  41511. const playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  41512. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  41513. }
  41514. }
  41515. /**
  41516. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  41517. * based on the latest timing information.
  41518. *
  41519. * @param {Object} options
  41520. * Options object
  41521. * @param {SegmentInfo} options.segmentInfo
  41522. * The current active request information
  41523. * @param {boolean} options.shouldSaveTimelineMapping
  41524. * If there's a timeline change, determines if the timeline mapping should be
  41525. * saved for timeline mapping and program date time mappings.
  41526. */
  41527. saveSegmentTimingInfo({
  41528. segmentInfo,
  41529. shouldSaveTimelineMapping
  41530. }) {
  41531. const didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  41532. const segment = segmentInfo.segment;
  41533. if (didCalculateSegmentTimeMapping) {
  41534. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  41535. // now with segment timing information
  41536. if (!segmentInfo.playlist.syncInfo) {
  41537. segmentInfo.playlist.syncInfo = {
  41538. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  41539. time: segment.start
  41540. };
  41541. }
  41542. }
  41543. const dateTime = segment.dateTimeObject;
  41544. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  41545. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  41546. }
  41547. }
  41548. timestampOffsetForTimeline(timeline) {
  41549. if (typeof this.timelines[timeline] === 'undefined') {
  41550. return null;
  41551. }
  41552. return this.timelines[timeline].time;
  41553. }
  41554. mappingForTimeline(timeline) {
  41555. if (typeof this.timelines[timeline] === 'undefined') {
  41556. return null;
  41557. }
  41558. return this.timelines[timeline].mapping;
  41559. }
  41560. /**
  41561. * Use the "media time" for a segment to generate a mapping to "display time" and
  41562. * save that display time to the segment.
  41563. *
  41564. * @private
  41565. * @param {SegmentInfo} segmentInfo
  41566. * The current active request information
  41567. * @param {Object} timingInfo
  41568. * The start and end time of the current segment in "media time"
  41569. * @param {boolean} shouldSaveTimelineMapping
  41570. * If there's a timeline change, determines if the timeline mapping should be
  41571. * saved in timelines.
  41572. * @return {boolean}
  41573. * Returns false if segment time mapping could not be calculated
  41574. */
  41575. calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  41576. // TODO: remove side effects
  41577. const segment = segmentInfo.segment;
  41578. const part = segmentInfo.part;
  41579. let mappingObj = this.timelines[segmentInfo.timeline];
  41580. let start;
  41581. let end;
  41582. if (typeof segmentInfo.timestampOffset === 'number') {
  41583. mappingObj = {
  41584. time: segmentInfo.startOfSegment,
  41585. mapping: segmentInfo.startOfSegment - timingInfo.start
  41586. };
  41587. if (shouldSaveTimelineMapping) {
  41588. this.timelines[segmentInfo.timeline] = mappingObj;
  41589. this.trigger('timestampoffset');
  41590. this.logger_(`time mapping for timeline ${segmentInfo.timeline}: ` + `[time: ${mappingObj.time}] [mapping: ${mappingObj.mapping}]`);
  41591. }
  41592. start = segmentInfo.startOfSegment;
  41593. end = timingInfo.end + mappingObj.mapping;
  41594. } else if (mappingObj) {
  41595. start = timingInfo.start + mappingObj.mapping;
  41596. end = timingInfo.end + mappingObj.mapping;
  41597. } else {
  41598. return false;
  41599. }
  41600. if (part) {
  41601. part.start = start;
  41602. part.end = end;
  41603. } // If we don't have a segment start yet or the start value we got
  41604. // is less than our current segment.start value, save a new start value.
  41605. // We have to do this because parts will have segment timing info saved
  41606. // multiple times and we want segment start to be the earliest part start
  41607. // value for that segment.
  41608. if (!segment.start || start < segment.start) {
  41609. segment.start = start;
  41610. }
  41611. segment.end = end;
  41612. return true;
  41613. }
  41614. /**
  41615. * Each time we have discontinuity in the playlist, attempt to calculate the location
  41616. * in display of the start of the discontinuity and save that. We also save an accuracy
  41617. * value so that we save values with the most accuracy (closest to 0.)
  41618. *
  41619. * @private
  41620. * @param {SegmentInfo} segmentInfo - The current active request information
  41621. */
  41622. saveDiscontinuitySyncInfo_(segmentInfo) {
  41623. const playlist = segmentInfo.playlist;
  41624. const segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  41625. // the start of the range and it's accuracy is 0 (greater accuracy values
  41626. // mean more approximation)
  41627. if (segment.discontinuity) {
  41628. this.discontinuities[segment.timeline] = {
  41629. time: segment.start,
  41630. accuracy: 0
  41631. };
  41632. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  41633. // Search for future discontinuities that we can provide better timing
  41634. // information for and save that information for sync purposes
  41635. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  41636. const segmentIndex = playlist.discontinuityStarts[i];
  41637. const discontinuity = playlist.discontinuitySequence + i + 1;
  41638. const mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  41639. const accuracy = Math.abs(mediaIndexDiff);
  41640. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  41641. let time;
  41642. if (mediaIndexDiff < 0) {
  41643. time = segment.start - sumDurations({
  41644. defaultDuration: playlist.targetDuration,
  41645. durationList: playlist.segments,
  41646. startIndex: segmentInfo.mediaIndex,
  41647. endIndex: segmentIndex
  41648. });
  41649. } else {
  41650. time = segment.end + sumDurations({
  41651. defaultDuration: playlist.targetDuration,
  41652. durationList: playlist.segments,
  41653. startIndex: segmentInfo.mediaIndex + 1,
  41654. endIndex: segmentIndex
  41655. });
  41656. }
  41657. this.discontinuities[discontinuity] = {
  41658. time,
  41659. accuracy
  41660. };
  41661. }
  41662. }
  41663. }
  41664. }
  41665. dispose() {
  41666. this.trigger('dispose');
  41667. this.off();
  41668. }
  41669. }
  41670. /**
  41671. * The TimelineChangeController acts as a source for segment loaders to listen for and
  41672. * keep track of latest and pending timeline changes. This is useful to ensure proper
  41673. * sync, as each loader may need to make a consideration for what timeline the other
  41674. * loader is on before making changes which could impact the other loader's media.
  41675. *
  41676. * @class TimelineChangeController
  41677. * @extends videojs.EventTarget
  41678. */
  41679. class TimelineChangeController extends videojs.EventTarget {
  41680. constructor() {
  41681. super();
  41682. this.pendingTimelineChanges_ = {};
  41683. this.lastTimelineChanges_ = {};
  41684. }
  41685. clearPendingTimelineChange(type) {
  41686. this.pendingTimelineChanges_[type] = null;
  41687. this.trigger('pendingtimelinechange');
  41688. }
  41689. pendingTimelineChange({
  41690. type,
  41691. from,
  41692. to
  41693. }) {
  41694. if (typeof from === 'number' && typeof to === 'number') {
  41695. this.pendingTimelineChanges_[type] = {
  41696. type,
  41697. from,
  41698. to
  41699. };
  41700. this.trigger('pendingtimelinechange');
  41701. }
  41702. return this.pendingTimelineChanges_[type];
  41703. }
  41704. lastTimelineChange({
  41705. type,
  41706. from,
  41707. to
  41708. }) {
  41709. if (typeof from === 'number' && typeof to === 'number') {
  41710. this.lastTimelineChanges_[type] = {
  41711. type,
  41712. from,
  41713. to
  41714. };
  41715. delete this.pendingTimelineChanges_[type];
  41716. this.trigger('timelinechange');
  41717. }
  41718. return this.lastTimelineChanges_[type];
  41719. }
  41720. dispose() {
  41721. this.trigger('dispose');
  41722. this.pendingTimelineChanges_ = {};
  41723. this.lastTimelineChanges_ = {};
  41724. this.off();
  41725. }
  41726. }
  41727. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  41728. const workerCode = transform(getWorkerString(function () {
  41729. /**
  41730. * @file stream.js
  41731. */
  41732. /**
  41733. * A lightweight readable stream implemention that handles event dispatching.
  41734. *
  41735. * @class Stream
  41736. */
  41737. var Stream = /*#__PURE__*/function () {
  41738. function Stream() {
  41739. this.listeners = {};
  41740. }
  41741. /**
  41742. * Add a listener for a specified event type.
  41743. *
  41744. * @param {string} type the event name
  41745. * @param {Function} listener the callback to be invoked when an event of
  41746. * the specified type occurs
  41747. */
  41748. var _proto = Stream.prototype;
  41749. _proto.on = function on(type, listener) {
  41750. if (!this.listeners[type]) {
  41751. this.listeners[type] = [];
  41752. }
  41753. this.listeners[type].push(listener);
  41754. }
  41755. /**
  41756. * Remove a listener for a specified event type.
  41757. *
  41758. * @param {string} type the event name
  41759. * @param {Function} listener a function previously registered for this
  41760. * type of event through `on`
  41761. * @return {boolean} if we could turn it off or not
  41762. */;
  41763. _proto.off = function off(type, listener) {
  41764. if (!this.listeners[type]) {
  41765. return false;
  41766. }
  41767. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  41768. // In Video.js we slice listener functions
  41769. // on trigger so that it does not mess up the order
  41770. // while we loop through.
  41771. //
  41772. // Here we slice on off so that the loop in trigger
  41773. // can continue using it's old reference to loop without
  41774. // messing up the order.
  41775. this.listeners[type] = this.listeners[type].slice(0);
  41776. this.listeners[type].splice(index, 1);
  41777. return index > -1;
  41778. }
  41779. /**
  41780. * Trigger an event of the specified type on this stream. Any additional
  41781. * arguments to this function are passed as parameters to event listeners.
  41782. *
  41783. * @param {string} type the event name
  41784. */;
  41785. _proto.trigger = function trigger(type) {
  41786. var callbacks = this.listeners[type];
  41787. if (!callbacks) {
  41788. return;
  41789. } // Slicing the arguments on every invocation of this method
  41790. // can add a significant amount of overhead. Avoid the
  41791. // intermediate object creation for the common case of a
  41792. // single callback argument
  41793. if (arguments.length === 2) {
  41794. var length = callbacks.length;
  41795. for (var i = 0; i < length; ++i) {
  41796. callbacks[i].call(this, arguments[1]);
  41797. }
  41798. } else {
  41799. var args = Array.prototype.slice.call(arguments, 1);
  41800. var _length = callbacks.length;
  41801. for (var _i = 0; _i < _length; ++_i) {
  41802. callbacks[_i].apply(this, args);
  41803. }
  41804. }
  41805. }
  41806. /**
  41807. * Destroys the stream and cleans up.
  41808. */;
  41809. _proto.dispose = function dispose() {
  41810. this.listeners = {};
  41811. }
  41812. /**
  41813. * Forwards all `data` events on this stream to the destination stream. The
  41814. * destination stream should provide a method `push` to receive the data
  41815. * events as they arrive.
  41816. *
  41817. * @param {Stream} destination the stream that will receive all `data` events
  41818. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  41819. */;
  41820. _proto.pipe = function pipe(destination) {
  41821. this.on('data', function (data) {
  41822. destination.push(data);
  41823. });
  41824. };
  41825. return Stream;
  41826. }();
  41827. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  41828. /**
  41829. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  41830. *
  41831. * @param padded {Uint8Array} unencrypted bytes that have been padded
  41832. * @return {Uint8Array} the unpadded bytes
  41833. * @see http://tools.ietf.org/html/rfc5652
  41834. */
  41835. function unpad(padded) {
  41836. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  41837. }
  41838. /*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */
  41839. /**
  41840. * @file aes.js
  41841. *
  41842. * This file contains an adaptation of the AES decryption algorithm
  41843. * from the Standford Javascript Cryptography Library. That work is
  41844. * covered by the following copyright and permissions notice:
  41845. *
  41846. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  41847. * All rights reserved.
  41848. *
  41849. * Redistribution and use in source and binary forms, with or without
  41850. * modification, are permitted provided that the following conditions are
  41851. * met:
  41852. *
  41853. * 1. Redistributions of source code must retain the above copyright
  41854. * notice, this list of conditions and the following disclaimer.
  41855. *
  41856. * 2. Redistributions in binary form must reproduce the above
  41857. * copyright notice, this list of conditions and the following
  41858. * disclaimer in the documentation and/or other materials provided
  41859. * with the distribution.
  41860. *
  41861. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  41862. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  41863. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  41864. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  41865. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  41866. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  41867. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  41868. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  41869. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  41870. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  41871. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41872. *
  41873. * The views and conclusions contained in the software and documentation
  41874. * are those of the authors and should not be interpreted as representing
  41875. * official policies, either expressed or implied, of the authors.
  41876. */
  41877. /**
  41878. * Expand the S-box tables.
  41879. *
  41880. * @private
  41881. */
  41882. const precompute = function () {
  41883. const tables = [[[], [], [], [], []], [[], [], [], [], []]];
  41884. const encTable = tables[0];
  41885. const decTable = tables[1];
  41886. const sbox = encTable[4];
  41887. const sboxInv = decTable[4];
  41888. let i;
  41889. let x;
  41890. let xInv;
  41891. const d = [];
  41892. const th = [];
  41893. let x2;
  41894. let x4;
  41895. let x8;
  41896. let s;
  41897. let tEnc;
  41898. let tDec; // Compute double and third tables
  41899. for (i = 0; i < 256; i++) {
  41900. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  41901. }
  41902. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  41903. // Compute sbox
  41904. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  41905. s = s >> 8 ^ s & 255 ^ 99;
  41906. sbox[x] = s;
  41907. sboxInv[s] = x; // Compute MixColumns
  41908. x8 = d[x4 = d[x2 = d[x]]];
  41909. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  41910. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  41911. for (i = 0; i < 4; i++) {
  41912. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  41913. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  41914. }
  41915. } // Compactify. Considerable speedup on Firefox.
  41916. for (i = 0; i < 5; i++) {
  41917. encTable[i] = encTable[i].slice(0);
  41918. decTable[i] = decTable[i].slice(0);
  41919. }
  41920. return tables;
  41921. };
  41922. let aesTables = null;
  41923. /**
  41924. * Schedule out an AES key for both encryption and decryption. This
  41925. * is a low-level class. Use a cipher mode to do bulk encryption.
  41926. *
  41927. * @class AES
  41928. * @param key {Array} The key as an array of 4, 6 or 8 words.
  41929. */
  41930. class AES {
  41931. constructor(key) {
  41932. /**
  41933. * The expanded S-box and inverse S-box tables. These will be computed
  41934. * on the client so that we don't have to send them down the wire.
  41935. *
  41936. * There are two tables, _tables[0] is for encryption and
  41937. * _tables[1] is for decryption.
  41938. *
  41939. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  41940. * last (_tables[01][4]) is the S-box itself.
  41941. *
  41942. * @private
  41943. */
  41944. // if we have yet to precompute the S-box tables
  41945. // do so now
  41946. if (!aesTables) {
  41947. aesTables = precompute();
  41948. } // then make a copy of that object for use
  41949. 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()]];
  41950. let i;
  41951. let j;
  41952. let tmp;
  41953. const sbox = this._tables[0][4];
  41954. const decTable = this._tables[1];
  41955. const keyLen = key.length;
  41956. let rcon = 1;
  41957. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  41958. throw new Error('Invalid aes key size');
  41959. }
  41960. const encKey = key.slice(0);
  41961. const decKey = [];
  41962. this._key = [encKey, decKey]; // schedule encryption keys
  41963. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  41964. tmp = encKey[i - 1]; // apply sbox
  41965. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  41966. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  41967. if (i % keyLen === 0) {
  41968. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  41969. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  41970. }
  41971. }
  41972. encKey[i] = encKey[i - keyLen] ^ tmp;
  41973. } // schedule decryption keys
  41974. for (j = 0; i; j++, i--) {
  41975. tmp = encKey[j & 3 ? i : i - 4];
  41976. if (i <= 4 || j < 4) {
  41977. decKey[j] = tmp;
  41978. } else {
  41979. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  41980. }
  41981. }
  41982. }
  41983. /**
  41984. * Decrypt 16 bytes, specified as four 32-bit words.
  41985. *
  41986. * @param {number} encrypted0 the first word to decrypt
  41987. * @param {number} encrypted1 the second word to decrypt
  41988. * @param {number} encrypted2 the third word to decrypt
  41989. * @param {number} encrypted3 the fourth word to decrypt
  41990. * @param {Int32Array} out the array to write the decrypted words
  41991. * into
  41992. * @param {number} offset the offset into the output array to start
  41993. * writing results
  41994. * @return {Array} The plaintext.
  41995. */
  41996. decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  41997. const key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  41998. let a = encrypted0 ^ key[0];
  41999. let b = encrypted3 ^ key[1];
  42000. let c = encrypted2 ^ key[2];
  42001. let d = encrypted1 ^ key[3];
  42002. let a2;
  42003. let b2;
  42004. let c2; // key.length === 2 ?
  42005. const nInnerRounds = key.length / 4 - 2;
  42006. let i;
  42007. let kIndex = 4;
  42008. const table = this._tables[1]; // load up the tables
  42009. const table0 = table[0];
  42010. const table1 = table[1];
  42011. const table2 = table[2];
  42012. const table3 = table[3];
  42013. const sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  42014. for (i = 0; i < nInnerRounds; i++) {
  42015. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  42016. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  42017. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  42018. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  42019. kIndex += 4;
  42020. a = a2;
  42021. b = b2;
  42022. c = c2;
  42023. } // Last round.
  42024. for (i = 0; i < 4; i++) {
  42025. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  42026. a2 = a;
  42027. a = b;
  42028. b = c;
  42029. c = d;
  42030. d = a2;
  42031. }
  42032. }
  42033. }
  42034. /**
  42035. * @file async-stream.js
  42036. */
  42037. /**
  42038. * A wrapper around the Stream class to use setTimeout
  42039. * and run stream "jobs" Asynchronously
  42040. *
  42041. * @class AsyncStream
  42042. * @extends Stream
  42043. */
  42044. class AsyncStream extends Stream {
  42045. constructor() {
  42046. super(Stream);
  42047. this.jobs = [];
  42048. this.delay = 1;
  42049. this.timeout_ = null;
  42050. }
  42051. /**
  42052. * process an async job
  42053. *
  42054. * @private
  42055. */
  42056. processJob_() {
  42057. this.jobs.shift()();
  42058. if (this.jobs.length) {
  42059. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  42060. } else {
  42061. this.timeout_ = null;
  42062. }
  42063. }
  42064. /**
  42065. * push a job into the stream
  42066. *
  42067. * @param {Function} job the job to push into the stream
  42068. */
  42069. push(job) {
  42070. this.jobs.push(job);
  42071. if (!this.timeout_) {
  42072. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  42073. }
  42074. }
  42075. }
  42076. /**
  42077. * @file decrypter.js
  42078. *
  42079. * An asynchronous implementation of AES-128 CBC decryption with
  42080. * PKCS#7 padding.
  42081. */
  42082. /**
  42083. * Convert network-order (big-endian) bytes into their little-endian
  42084. * representation.
  42085. */
  42086. const ntoh = function (word) {
  42087. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  42088. };
  42089. /**
  42090. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  42091. *
  42092. * @param {Uint8Array} encrypted the encrypted bytes
  42093. * @param {Uint32Array} key the bytes of the decryption key
  42094. * @param {Uint32Array} initVector the initialization vector (IV) to
  42095. * use for the first round of CBC.
  42096. * @return {Uint8Array} the decrypted bytes
  42097. *
  42098. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  42099. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  42100. * @see https://tools.ietf.org/html/rfc2315
  42101. */
  42102. const decrypt = function (encrypted, key, initVector) {
  42103. // word-level access to the encrypted bytes
  42104. const encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  42105. const decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  42106. const decrypted = new Uint8Array(encrypted.byteLength);
  42107. const decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  42108. // decrypted data
  42109. let init0;
  42110. let init1;
  42111. let init2;
  42112. let init3;
  42113. let encrypted0;
  42114. let encrypted1;
  42115. let encrypted2;
  42116. let encrypted3; // iteration variable
  42117. let wordIx; // pull out the words of the IV to ensure we don't modify the
  42118. // passed-in reference and easier access
  42119. init0 = initVector[0];
  42120. init1 = initVector[1];
  42121. init2 = initVector[2];
  42122. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  42123. // to each decrypted block
  42124. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  42125. // convert big-endian (network order) words into little-endian
  42126. // (javascript order)
  42127. encrypted0 = ntoh(encrypted32[wordIx]);
  42128. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  42129. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  42130. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  42131. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  42132. // plaintext
  42133. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  42134. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  42135. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  42136. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  42137. init0 = encrypted0;
  42138. init1 = encrypted1;
  42139. init2 = encrypted2;
  42140. init3 = encrypted3;
  42141. }
  42142. return decrypted;
  42143. };
  42144. /**
  42145. * The `Decrypter` class that manages decryption of AES
  42146. * data through `AsyncStream` objects and the `decrypt`
  42147. * function
  42148. *
  42149. * @param {Uint8Array} encrypted the encrypted bytes
  42150. * @param {Uint32Array} key the bytes of the decryption key
  42151. * @param {Uint32Array} initVector the initialization vector (IV) to
  42152. * @param {Function} done the function to run when done
  42153. * @class Decrypter
  42154. */
  42155. class Decrypter {
  42156. constructor(encrypted, key, initVector, done) {
  42157. const step = Decrypter.STEP;
  42158. const encrypted32 = new Int32Array(encrypted.buffer);
  42159. const decrypted = new Uint8Array(encrypted.byteLength);
  42160. let i = 0;
  42161. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  42162. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  42163. for (i = step; i < encrypted32.length; i += step) {
  42164. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  42165. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  42166. } // invoke the done() callback when everything is finished
  42167. this.asyncStream_.push(function () {
  42168. // remove pkcs#7 padding from the decrypted bytes
  42169. done(null, unpad(decrypted));
  42170. });
  42171. }
  42172. /**
  42173. * a getter for step the maximum number of bytes to process at one time
  42174. *
  42175. * @return {number} the value of step 32000
  42176. */
  42177. static get STEP() {
  42178. // 4 * 8000;
  42179. return 32000;
  42180. }
  42181. /**
  42182. * @private
  42183. */
  42184. decryptChunk_(encrypted, key, initVector, decrypted) {
  42185. return function () {
  42186. const bytes = decrypt(encrypted, key, initVector);
  42187. decrypted.set(bytes, encrypted.byteOffset);
  42188. };
  42189. }
  42190. }
  42191. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  42192. var win;
  42193. if (typeof window !== "undefined") {
  42194. win = window;
  42195. } else if (typeof commonjsGlobal !== "undefined") {
  42196. win = commonjsGlobal;
  42197. } else if (typeof self !== "undefined") {
  42198. win = self;
  42199. } else {
  42200. win = {};
  42201. }
  42202. var window_1 = win;
  42203. var isArrayBufferView = function isArrayBufferView(obj) {
  42204. if (ArrayBuffer.isView === 'function') {
  42205. return ArrayBuffer.isView(obj);
  42206. }
  42207. return obj && obj.buffer instanceof ArrayBuffer;
  42208. };
  42209. var BigInt = window_1.BigInt || Number;
  42210. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  42211. (function () {
  42212. var a = new Uint16Array([0xFFCC]);
  42213. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  42214. if (b[0] === 0xFF) {
  42215. return 'big';
  42216. }
  42217. if (b[0] === 0xCC) {
  42218. return 'little';
  42219. }
  42220. return 'unknown';
  42221. })();
  42222. /**
  42223. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  42224. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  42225. *
  42226. * @param {Object} message
  42227. * Object of properties and values to send to the web worker
  42228. * @return {Object}
  42229. * Modified message with TypedArray values expanded
  42230. * @function createTransferableMessage
  42231. */
  42232. const createTransferableMessage = function (message) {
  42233. const transferable = {};
  42234. Object.keys(message).forEach(key => {
  42235. const value = message[key];
  42236. if (isArrayBufferView(value)) {
  42237. transferable[key] = {
  42238. bytes: value.buffer,
  42239. byteOffset: value.byteOffset,
  42240. byteLength: value.byteLength
  42241. };
  42242. } else {
  42243. transferable[key] = value;
  42244. }
  42245. });
  42246. return transferable;
  42247. };
  42248. /* global self */
  42249. /**
  42250. * Our web worker interface so that things can talk to aes-decrypter
  42251. * that will be running in a web worker. the scope is passed to this by
  42252. * webworkify.
  42253. */
  42254. self.onmessage = function (event) {
  42255. const data = event.data;
  42256. const encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  42257. const key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  42258. const iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  42259. /* eslint-disable no-new, handle-callback-err */
  42260. new Decrypter(encrypted, key, iv, function (err, bytes) {
  42261. self.postMessage(createTransferableMessage({
  42262. source: data.source,
  42263. decrypted: bytes
  42264. }), [bytes.buffer]);
  42265. });
  42266. /* eslint-enable */
  42267. };
  42268. }));
  42269. var Decrypter = factory(workerCode);
  42270. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  42271. /**
  42272. * Convert the properties of an HLS track into an audioTrackKind.
  42273. *
  42274. * @private
  42275. */
  42276. const audioTrackKind_ = properties => {
  42277. let kind = properties.default ? 'main' : 'alternative';
  42278. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  42279. kind = 'main-desc';
  42280. }
  42281. return kind;
  42282. };
  42283. /**
  42284. * Pause provided segment loader and playlist loader if active
  42285. *
  42286. * @param {SegmentLoader} segmentLoader
  42287. * SegmentLoader to pause
  42288. * @param {Object} mediaType
  42289. * Active media type
  42290. * @function stopLoaders
  42291. */
  42292. const stopLoaders = (segmentLoader, mediaType) => {
  42293. segmentLoader.abort();
  42294. segmentLoader.pause();
  42295. if (mediaType && mediaType.activePlaylistLoader) {
  42296. mediaType.activePlaylistLoader.pause();
  42297. mediaType.activePlaylistLoader = null;
  42298. }
  42299. };
  42300. /**
  42301. * Start loading provided segment loader and playlist loader
  42302. *
  42303. * @param {PlaylistLoader} playlistLoader
  42304. * PlaylistLoader to start loading
  42305. * @param {Object} mediaType
  42306. * Active media type
  42307. * @function startLoaders
  42308. */
  42309. const startLoaders = (playlistLoader, mediaType) => {
  42310. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  42311. // playlist loader
  42312. mediaType.activePlaylistLoader = playlistLoader;
  42313. playlistLoader.load();
  42314. };
  42315. /**
  42316. * Returns a function to be called when the media group changes. It performs a
  42317. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  42318. * change of group is merely a rendition switch of the same content at another encoding,
  42319. * rather than a change of content, such as switching audio from English to Spanish.
  42320. *
  42321. * @param {string} type
  42322. * MediaGroup type
  42323. * @param {Object} settings
  42324. * Object containing required information for media groups
  42325. * @return {Function}
  42326. * Handler for a non-destructive resync of SegmentLoader when the active media
  42327. * group changes.
  42328. * @function onGroupChanged
  42329. */
  42330. const onGroupChanged = (type, settings) => () => {
  42331. const {
  42332. segmentLoaders: {
  42333. [type]: segmentLoader,
  42334. main: mainSegmentLoader
  42335. },
  42336. mediaTypes: {
  42337. [type]: mediaType
  42338. }
  42339. } = settings;
  42340. const activeTrack = mediaType.activeTrack();
  42341. const activeGroup = mediaType.getActiveGroup();
  42342. const previousActiveLoader = mediaType.activePlaylistLoader;
  42343. const lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  42344. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  42345. return;
  42346. }
  42347. mediaType.lastGroup_ = activeGroup;
  42348. mediaType.lastTrack_ = activeTrack;
  42349. stopLoaders(segmentLoader, mediaType);
  42350. if (!activeGroup || activeGroup.isMainPlaylist) {
  42351. // there is no group active or active group is a main playlist and won't change
  42352. return;
  42353. }
  42354. if (!activeGroup.playlistLoader) {
  42355. if (previousActiveLoader) {
  42356. // The previous group had a playlist loader but the new active group does not
  42357. // this means we are switching from demuxed to muxed audio. In this case we want to
  42358. // do a destructive reset of the main segment loader and not restart the audio
  42359. // loaders.
  42360. mainSegmentLoader.resetEverything();
  42361. }
  42362. return;
  42363. } // Non-destructive resync
  42364. segmentLoader.resyncLoader();
  42365. startLoaders(activeGroup.playlistLoader, mediaType);
  42366. };
  42367. const onGroupChanging = (type, settings) => () => {
  42368. const {
  42369. segmentLoaders: {
  42370. [type]: segmentLoader
  42371. },
  42372. mediaTypes: {
  42373. [type]: mediaType
  42374. }
  42375. } = settings;
  42376. mediaType.lastGroup_ = null;
  42377. segmentLoader.abort();
  42378. segmentLoader.pause();
  42379. };
  42380. /**
  42381. * Returns a function to be called when the media track changes. It performs a
  42382. * destructive reset of the SegmentLoader to ensure we start loading as close to
  42383. * currentTime as possible.
  42384. *
  42385. * @param {string} type
  42386. * MediaGroup type
  42387. * @param {Object} settings
  42388. * Object containing required information for media groups
  42389. * @return {Function}
  42390. * Handler for a destructive reset of SegmentLoader when the active media
  42391. * track changes.
  42392. * @function onTrackChanged
  42393. */
  42394. const onTrackChanged = (type, settings) => () => {
  42395. const {
  42396. mainPlaylistLoader,
  42397. segmentLoaders: {
  42398. [type]: segmentLoader,
  42399. main: mainSegmentLoader
  42400. },
  42401. mediaTypes: {
  42402. [type]: mediaType
  42403. }
  42404. } = settings;
  42405. const activeTrack = mediaType.activeTrack();
  42406. const activeGroup = mediaType.getActiveGroup();
  42407. const previousActiveLoader = mediaType.activePlaylistLoader;
  42408. const lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  42409. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  42410. return;
  42411. }
  42412. mediaType.lastGroup_ = activeGroup;
  42413. mediaType.lastTrack_ = activeTrack;
  42414. stopLoaders(segmentLoader, mediaType);
  42415. if (!activeGroup) {
  42416. // there is no group active so we do not want to restart loaders
  42417. return;
  42418. }
  42419. if (activeGroup.isMainPlaylist) {
  42420. // track did not change, do nothing
  42421. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  42422. return;
  42423. }
  42424. const pc = settings.vhs.playlistController_;
  42425. const newPlaylist = pc.selectPlaylist(); // media will not change do nothing
  42426. if (pc.media() === newPlaylist) {
  42427. return;
  42428. }
  42429. mediaType.logger_(`track change. Switching main audio from ${lastTrack.id} to ${activeTrack.id}`);
  42430. mainPlaylistLoader.pause();
  42431. mainSegmentLoader.resetEverything();
  42432. pc.fastQualityChange_(newPlaylist);
  42433. return;
  42434. }
  42435. if (type === 'AUDIO') {
  42436. if (!activeGroup.playlistLoader) {
  42437. // when switching from demuxed audio/video to muxed audio/video (noted by no
  42438. // playlist loader for the audio group), we want to do a destructive reset of the
  42439. // main segment loader and not restart the audio loaders
  42440. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  42441. // it should be stopped
  42442. mainSegmentLoader.resetEverything();
  42443. return;
  42444. } // although the segment loader is an audio segment loader, call the setAudio
  42445. // function to ensure it is prepared to re-append the init segment (or handle other
  42446. // config changes)
  42447. segmentLoader.setAudio(true);
  42448. mainSegmentLoader.setAudio(false);
  42449. }
  42450. if (previousActiveLoader === activeGroup.playlistLoader) {
  42451. // Nothing has actually changed. This can happen because track change events can fire
  42452. // multiple times for a "single" change. One for enabling the new active track, and
  42453. // one for disabling the track that was active
  42454. startLoaders(activeGroup.playlistLoader, mediaType);
  42455. return;
  42456. }
  42457. if (segmentLoader.track) {
  42458. // For WebVTT, set the new text track in the segmentloader
  42459. segmentLoader.track(activeTrack);
  42460. } // destructive reset
  42461. segmentLoader.resetEverything();
  42462. startLoaders(activeGroup.playlistLoader, mediaType);
  42463. };
  42464. const onError = {
  42465. /**
  42466. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  42467. * an error.
  42468. *
  42469. * @param {string} type
  42470. * MediaGroup type
  42471. * @param {Object} settings
  42472. * Object containing required information for media groups
  42473. * @return {Function}
  42474. * Error handler. Logs warning (or error if the playlist is excluded) to
  42475. * console and switches back to default audio track.
  42476. * @function onError.AUDIO
  42477. */
  42478. AUDIO: (type, settings) => () => {
  42479. const {
  42480. segmentLoaders: {
  42481. [type]: segmentLoader
  42482. },
  42483. mediaTypes: {
  42484. [type]: mediaType
  42485. },
  42486. excludePlaylist
  42487. } = settings;
  42488. stopLoaders(segmentLoader, mediaType); // switch back to default audio track
  42489. const activeTrack = mediaType.activeTrack();
  42490. const activeGroup = mediaType.activeGroup();
  42491. const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;
  42492. const defaultTrack = mediaType.tracks[id];
  42493. if (activeTrack === defaultTrack) {
  42494. // Default track encountered an error. All we can do now is exclude the current
  42495. // rendition and hope another will switch audio groups
  42496. excludePlaylist({
  42497. error: {
  42498. message: 'Problem encountered loading the default audio track.'
  42499. }
  42500. });
  42501. return;
  42502. }
  42503. videojs.log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  42504. for (const trackId in mediaType.tracks) {
  42505. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  42506. }
  42507. mediaType.onTrackChanged();
  42508. },
  42509. /**
  42510. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  42511. * an error.
  42512. *
  42513. * @param {string} type
  42514. * MediaGroup type
  42515. * @param {Object} settings
  42516. * Object containing required information for media groups
  42517. * @return {Function}
  42518. * Error handler. Logs warning to console and disables the active subtitle track
  42519. * @function onError.SUBTITLES
  42520. */
  42521. SUBTITLES: (type, settings) => () => {
  42522. const {
  42523. segmentLoaders: {
  42524. [type]: segmentLoader
  42525. },
  42526. mediaTypes: {
  42527. [type]: mediaType
  42528. }
  42529. } = settings;
  42530. videojs.log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  42531. stopLoaders(segmentLoader, mediaType);
  42532. const track = mediaType.activeTrack();
  42533. if (track) {
  42534. track.mode = 'disabled';
  42535. }
  42536. mediaType.onTrackChanged();
  42537. }
  42538. };
  42539. const setupListeners = {
  42540. /**
  42541. * Setup event listeners for audio playlist loader
  42542. *
  42543. * @param {string} type
  42544. * MediaGroup type
  42545. * @param {PlaylistLoader|null} playlistLoader
  42546. * PlaylistLoader to register listeners on
  42547. * @param {Object} settings
  42548. * Object containing required information for media groups
  42549. * @function setupListeners.AUDIO
  42550. */
  42551. AUDIO: (type, playlistLoader, settings) => {
  42552. if (!playlistLoader) {
  42553. // no playlist loader means audio will be muxed with the video
  42554. return;
  42555. }
  42556. const {
  42557. tech,
  42558. requestOptions,
  42559. segmentLoaders: {
  42560. [type]: segmentLoader
  42561. }
  42562. } = settings;
  42563. playlistLoader.on('loadedmetadata', () => {
  42564. const media = playlistLoader.media();
  42565. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  42566. // permits, start downloading segments
  42567. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  42568. segmentLoader.load();
  42569. }
  42570. });
  42571. playlistLoader.on('loadedplaylist', () => {
  42572. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  42573. if (!tech.paused()) {
  42574. segmentLoader.load();
  42575. }
  42576. });
  42577. playlistLoader.on('error', onError[type](type, settings));
  42578. },
  42579. /**
  42580. * Setup event listeners for subtitle playlist loader
  42581. *
  42582. * @param {string} type
  42583. * MediaGroup type
  42584. * @param {PlaylistLoader|null} playlistLoader
  42585. * PlaylistLoader to register listeners on
  42586. * @param {Object} settings
  42587. * Object containing required information for media groups
  42588. * @function setupListeners.SUBTITLES
  42589. */
  42590. SUBTITLES: (type, playlistLoader, settings) => {
  42591. const {
  42592. tech,
  42593. requestOptions,
  42594. segmentLoaders: {
  42595. [type]: segmentLoader
  42596. },
  42597. mediaTypes: {
  42598. [type]: mediaType
  42599. }
  42600. } = settings;
  42601. playlistLoader.on('loadedmetadata', () => {
  42602. const media = playlistLoader.media();
  42603. segmentLoader.playlist(media, requestOptions);
  42604. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  42605. // permits, start downloading segments
  42606. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  42607. segmentLoader.load();
  42608. }
  42609. });
  42610. playlistLoader.on('loadedplaylist', () => {
  42611. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  42612. if (!tech.paused()) {
  42613. segmentLoader.load();
  42614. }
  42615. });
  42616. playlistLoader.on('error', onError[type](type, settings));
  42617. }
  42618. };
  42619. const initialize = {
  42620. /**
  42621. * Setup PlaylistLoaders and AudioTracks for the audio groups
  42622. *
  42623. * @param {string} type
  42624. * MediaGroup type
  42625. * @param {Object} settings
  42626. * Object containing required information for media groups
  42627. * @function initialize.AUDIO
  42628. */
  42629. 'AUDIO': (type, settings) => {
  42630. const {
  42631. vhs,
  42632. sourceType,
  42633. segmentLoaders: {
  42634. [type]: segmentLoader
  42635. },
  42636. requestOptions,
  42637. main: {
  42638. mediaGroups
  42639. },
  42640. mediaTypes: {
  42641. [type]: {
  42642. groups,
  42643. tracks,
  42644. logger_
  42645. }
  42646. },
  42647. mainPlaylistLoader
  42648. } = settings;
  42649. const audioOnlyMain = isAudioOnly(mainPlaylistLoader.main); // force a default if we have none
  42650. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  42651. mediaGroups[type] = {
  42652. main: {
  42653. default: {
  42654. default: true
  42655. }
  42656. }
  42657. };
  42658. if (audioOnlyMain) {
  42659. mediaGroups[type].main.default.playlists = mainPlaylistLoader.main.playlists;
  42660. }
  42661. }
  42662. for (const groupId in mediaGroups[type]) {
  42663. if (!groups[groupId]) {
  42664. groups[groupId] = [];
  42665. }
  42666. for (const variantLabel in mediaGroups[type][groupId]) {
  42667. let properties = mediaGroups[type][groupId][variantLabel];
  42668. let playlistLoader;
  42669. if (audioOnlyMain) {
  42670. logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a main playlist`);
  42671. properties.isMainPlaylist = true;
  42672. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  42673. // use the resolved media playlist object
  42674. } else if (sourceType === 'vhs-json' && properties.playlists) {
  42675. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  42676. } else if (properties.resolvedUri) {
  42677. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  42678. // should we even have properties.playlists in this check.
  42679. } else if (properties.playlists && sourceType === 'dash') {
  42680. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  42681. } else {
  42682. // no resolvedUri means the audio is muxed with the video when using this
  42683. // audio track
  42684. playlistLoader = null;
  42685. }
  42686. properties = merge({
  42687. id: variantLabel,
  42688. playlistLoader
  42689. }, properties);
  42690. setupListeners[type](type, properties.playlistLoader, settings);
  42691. groups[groupId].push(properties);
  42692. if (typeof tracks[variantLabel] === 'undefined') {
  42693. const track = new videojs.AudioTrack({
  42694. id: variantLabel,
  42695. kind: audioTrackKind_(properties),
  42696. enabled: false,
  42697. language: properties.language,
  42698. default: properties.default,
  42699. label: variantLabel
  42700. });
  42701. tracks[variantLabel] = track;
  42702. }
  42703. }
  42704. } // setup single error event handler for the segment loader
  42705. segmentLoader.on('error', onError[type](type, settings));
  42706. },
  42707. /**
  42708. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  42709. *
  42710. * @param {string} type
  42711. * MediaGroup type
  42712. * @param {Object} settings
  42713. * Object containing required information for media groups
  42714. * @function initialize.SUBTITLES
  42715. */
  42716. 'SUBTITLES': (type, settings) => {
  42717. const {
  42718. tech,
  42719. vhs,
  42720. sourceType,
  42721. segmentLoaders: {
  42722. [type]: segmentLoader
  42723. },
  42724. requestOptions,
  42725. main: {
  42726. mediaGroups
  42727. },
  42728. mediaTypes: {
  42729. [type]: {
  42730. groups,
  42731. tracks
  42732. }
  42733. },
  42734. mainPlaylistLoader
  42735. } = settings;
  42736. for (const groupId in mediaGroups[type]) {
  42737. if (!groups[groupId]) {
  42738. groups[groupId] = [];
  42739. }
  42740. for (const variantLabel in mediaGroups[type][groupId]) {
  42741. if (mediaGroups[type][groupId][variantLabel].forced) {
  42742. // Subtitle playlists with the forced attribute are not selectable in Safari.
  42743. // According to Apple's HLS Authoring Specification:
  42744. // If content has forced subtitles and regular subtitles in a given language,
  42745. // the regular subtitles track in that language MUST contain both the forced
  42746. // subtitles and the regular subtitles for that language.
  42747. // Because of this requirement and that Safari does not add forced subtitles,
  42748. // forced subtitles are skipped here to maintain consistent experience across
  42749. // all platforms
  42750. continue;
  42751. }
  42752. let properties = mediaGroups[type][groupId][variantLabel];
  42753. let playlistLoader;
  42754. if (sourceType === 'hls') {
  42755. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  42756. } else if (sourceType === 'dash') {
  42757. const playlists = properties.playlists.filter(p => p.excludeUntil !== Infinity);
  42758. if (!playlists.length) {
  42759. return;
  42760. }
  42761. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  42762. } else if (sourceType === 'vhs-json') {
  42763. playlistLoader = new PlaylistLoader(
  42764. // if the vhs-json object included the media playlist, use the media playlist
  42765. // as provided, otherwise use the resolved URI to load the playlist
  42766. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  42767. }
  42768. properties = merge({
  42769. id: variantLabel,
  42770. playlistLoader
  42771. }, properties);
  42772. setupListeners[type](type, properties.playlistLoader, settings);
  42773. groups[groupId].push(properties);
  42774. if (typeof tracks[variantLabel] === 'undefined') {
  42775. const track = tech.addRemoteTextTrack({
  42776. id: variantLabel,
  42777. kind: 'subtitles',
  42778. default: properties.default && properties.autoselect,
  42779. language: properties.language,
  42780. label: variantLabel
  42781. }, false).track;
  42782. tracks[variantLabel] = track;
  42783. }
  42784. }
  42785. } // setup single error event handler for the segment loader
  42786. segmentLoader.on('error', onError[type](type, settings));
  42787. },
  42788. /**
  42789. * Setup TextTracks for the closed-caption groups
  42790. *
  42791. * @param {String} type
  42792. * MediaGroup type
  42793. * @param {Object} settings
  42794. * Object containing required information for media groups
  42795. * @function initialize['CLOSED-CAPTIONS']
  42796. */
  42797. 'CLOSED-CAPTIONS': (type, settings) => {
  42798. const {
  42799. tech,
  42800. main: {
  42801. mediaGroups
  42802. },
  42803. mediaTypes: {
  42804. [type]: {
  42805. groups,
  42806. tracks
  42807. }
  42808. }
  42809. } = settings;
  42810. for (const groupId in mediaGroups[type]) {
  42811. if (!groups[groupId]) {
  42812. groups[groupId] = [];
  42813. }
  42814. for (const variantLabel in mediaGroups[type][groupId]) {
  42815. const properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  42816. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  42817. continue;
  42818. }
  42819. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  42820. let newProps = {
  42821. label: variantLabel,
  42822. language: properties.language,
  42823. instreamId: properties.instreamId,
  42824. default: properties.default && properties.autoselect
  42825. };
  42826. if (captionServices[newProps.instreamId]) {
  42827. newProps = merge(newProps, captionServices[newProps.instreamId]);
  42828. }
  42829. if (newProps.default === undefined) {
  42830. delete newProps.default;
  42831. } // No PlaylistLoader is required for Closed-Captions because the captions are
  42832. // embedded within the video stream
  42833. groups[groupId].push(merge({
  42834. id: variantLabel
  42835. }, properties));
  42836. if (typeof tracks[variantLabel] === 'undefined') {
  42837. const track = tech.addRemoteTextTrack({
  42838. id: newProps.instreamId,
  42839. kind: 'captions',
  42840. default: newProps.default,
  42841. language: newProps.language,
  42842. label: newProps.label
  42843. }, false).track;
  42844. tracks[variantLabel] = track;
  42845. }
  42846. }
  42847. }
  42848. }
  42849. };
  42850. const groupMatch = (list, media) => {
  42851. for (let i = 0; i < list.length; i++) {
  42852. if (playlistMatch(media, list[i])) {
  42853. return true;
  42854. }
  42855. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  42856. return true;
  42857. }
  42858. }
  42859. return false;
  42860. };
  42861. /**
  42862. * Returns a function used to get the active group of the provided type
  42863. *
  42864. * @param {string} type
  42865. * MediaGroup type
  42866. * @param {Object} settings
  42867. * Object containing required information for media groups
  42868. * @return {Function}
  42869. * Function that returns the active media group for the provided type. Takes an
  42870. * optional parameter {TextTrack} track. If no track is provided, a list of all
  42871. * variants in the group, otherwise the variant corresponding to the provided
  42872. * track is returned.
  42873. * @function activeGroup
  42874. */
  42875. const activeGroup = (type, settings) => track => {
  42876. const {
  42877. mainPlaylistLoader,
  42878. mediaTypes: {
  42879. [type]: {
  42880. groups
  42881. }
  42882. }
  42883. } = settings;
  42884. const media = mainPlaylistLoader.media();
  42885. if (!media) {
  42886. return null;
  42887. }
  42888. let variants = null; // set to variants to main media active group
  42889. if (media.attributes[type]) {
  42890. variants = groups[media.attributes[type]];
  42891. }
  42892. const groupKeys = Object.keys(groups);
  42893. if (!variants) {
  42894. // find the mainPlaylistLoader media
  42895. // that is in a media group if we are dealing
  42896. // with audio only
  42897. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.main)) {
  42898. for (let i = 0; i < groupKeys.length; i++) {
  42899. const groupPropertyList = groups[groupKeys[i]];
  42900. if (groupMatch(groupPropertyList, media)) {
  42901. variants = groupPropertyList;
  42902. break;
  42903. }
  42904. } // use the main group if it exists
  42905. } else if (groups.main) {
  42906. variants = groups.main; // only one group, use that one
  42907. } else if (groupKeys.length === 1) {
  42908. variants = groups[groupKeys[0]];
  42909. }
  42910. }
  42911. if (typeof track === 'undefined') {
  42912. return variants;
  42913. }
  42914. if (track === null || !variants) {
  42915. // An active track was specified so a corresponding group is expected. track === null
  42916. // means no track is currently active so there is no corresponding group
  42917. return null;
  42918. }
  42919. return variants.filter(props => props.id === track.id)[0] || null;
  42920. };
  42921. const activeTrack = {
  42922. /**
  42923. * Returns a function used to get the active track of type provided
  42924. *
  42925. * @param {string} type
  42926. * MediaGroup type
  42927. * @param {Object} settings
  42928. * Object containing required information for media groups
  42929. * @return {Function}
  42930. * Function that returns the active media track for the provided type. Returns
  42931. * null if no track is active
  42932. * @function activeTrack.AUDIO
  42933. */
  42934. AUDIO: (type, settings) => () => {
  42935. const {
  42936. mediaTypes: {
  42937. [type]: {
  42938. tracks
  42939. }
  42940. }
  42941. } = settings;
  42942. for (const id in tracks) {
  42943. if (tracks[id].enabled) {
  42944. return tracks[id];
  42945. }
  42946. }
  42947. return null;
  42948. },
  42949. /**
  42950. * Returns a function used to get the active track of type provided
  42951. *
  42952. * @param {string} type
  42953. * MediaGroup type
  42954. * @param {Object} settings
  42955. * Object containing required information for media groups
  42956. * @return {Function}
  42957. * Function that returns the active media track for the provided type. Returns
  42958. * null if no track is active
  42959. * @function activeTrack.SUBTITLES
  42960. */
  42961. SUBTITLES: (type, settings) => () => {
  42962. const {
  42963. mediaTypes: {
  42964. [type]: {
  42965. tracks
  42966. }
  42967. }
  42968. } = settings;
  42969. for (const id in tracks) {
  42970. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  42971. return tracks[id];
  42972. }
  42973. }
  42974. return null;
  42975. }
  42976. };
  42977. const getActiveGroup = (type, {
  42978. mediaTypes
  42979. }) => () => {
  42980. const activeTrack_ = mediaTypes[type].activeTrack();
  42981. if (!activeTrack_) {
  42982. return null;
  42983. }
  42984. return mediaTypes[type].activeGroup(activeTrack_);
  42985. };
  42986. /**
  42987. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  42988. * Closed-Captions) specified in the main manifest.
  42989. *
  42990. * @param {Object} settings
  42991. * Object containing required information for setting up the media groups
  42992. * @param {Tech} settings.tech
  42993. * The tech of the player
  42994. * @param {Object} settings.requestOptions
  42995. * XHR request options used by the segment loaders
  42996. * @param {PlaylistLoader} settings.mainPlaylistLoader
  42997. * PlaylistLoader for the main source
  42998. * @param {VhsHandler} settings.vhs
  42999. * VHS SourceHandler
  43000. * @param {Object} settings.main
  43001. * The parsed main manifest
  43002. * @param {Object} settings.mediaTypes
  43003. * Object to store the loaders, tracks, and utility methods for each media type
  43004. * @param {Function} settings.excludePlaylist
  43005. * Excludes the current rendition and forces a rendition switch.
  43006. * @function setupMediaGroups
  43007. */
  43008. const setupMediaGroups = settings => {
  43009. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  43010. initialize[type](type, settings);
  43011. });
  43012. const {
  43013. mediaTypes,
  43014. mainPlaylistLoader,
  43015. tech,
  43016. vhs,
  43017. segmentLoaders: {
  43018. ['AUDIO']: audioSegmentLoader,
  43019. main: mainSegmentLoader
  43020. }
  43021. } = settings; // setup active group and track getters and change event handlers
  43022. ['AUDIO', 'SUBTITLES'].forEach(type => {
  43023. mediaTypes[type].activeGroup = activeGroup(type, settings);
  43024. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  43025. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  43026. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  43027. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  43028. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  43029. }); // DO NOT enable the default subtitle or caption track.
  43030. // DO enable the default audio track
  43031. const audioGroup = mediaTypes.AUDIO.activeGroup();
  43032. if (audioGroup) {
  43033. const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;
  43034. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  43035. mediaTypes.AUDIO.onGroupChanged();
  43036. mediaTypes.AUDIO.onTrackChanged();
  43037. const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  43038. // track is changed, but needs to be handled here since the track may not be considered
  43039. // changed on the first call to onTrackChanged
  43040. if (!activeAudioGroup.playlistLoader) {
  43041. // either audio is muxed with video or the stream is audio only
  43042. mainSegmentLoader.setAudio(true);
  43043. } else {
  43044. // audio is demuxed
  43045. mainSegmentLoader.setAudio(false);
  43046. audioSegmentLoader.setAudio(true);
  43047. }
  43048. }
  43049. mainPlaylistLoader.on('mediachange', () => {
  43050. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());
  43051. });
  43052. mainPlaylistLoader.on('mediachanging', () => {
  43053. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());
  43054. }); // custom audio track change event handler for usage event
  43055. const onAudioTrackChanged = () => {
  43056. mediaTypes.AUDIO.onTrackChanged();
  43057. tech.trigger({
  43058. type: 'usage',
  43059. name: 'vhs-audio-change'
  43060. });
  43061. };
  43062. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  43063. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  43064. vhs.on('dispose', () => {
  43065. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  43066. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  43067. }); // clear existing audio tracks and add the ones we just created
  43068. tech.clearTracks('audio');
  43069. for (const id in mediaTypes.AUDIO.tracks) {
  43070. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  43071. }
  43072. };
  43073. /**
  43074. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  43075. * media type
  43076. *
  43077. * @return {Object}
  43078. * Object to store the loaders, tracks, and utility methods for each media type
  43079. * @function createMediaTypes
  43080. */
  43081. const createMediaTypes = () => {
  43082. const mediaTypes = {};
  43083. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  43084. mediaTypes[type] = {
  43085. groups: {},
  43086. tracks: {},
  43087. activePlaylistLoader: null,
  43088. activeGroup: noop,
  43089. activeTrack: noop,
  43090. getActiveGroup: noop,
  43091. onGroupChanged: noop,
  43092. onTrackChanged: noop,
  43093. lastTrack_: null,
  43094. logger_: logger(`MediaGroups[${type}]`)
  43095. };
  43096. });
  43097. return mediaTypes;
  43098. };
  43099. /**
  43100. * @file playlist-controller.js
  43101. */
  43102. const ABORT_EARLY_EXCLUSION_SECONDS = 60 * 2;
  43103. let Vhs$1; // SegmentLoader stats that need to have each loader's
  43104. // values summed to calculate the final value
  43105. const loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  43106. const sumLoaderStat = function (stat) {
  43107. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  43108. };
  43109. const shouldSwitchToMedia = function ({
  43110. currentPlaylist,
  43111. buffered,
  43112. currentTime,
  43113. nextPlaylist,
  43114. bufferLowWaterLine,
  43115. bufferHighWaterLine,
  43116. duration,
  43117. bufferBasedABR,
  43118. log
  43119. }) {
  43120. // we have no other playlist to switch to
  43121. if (!nextPlaylist) {
  43122. videojs.log.warn('We received no playlist to switch to. Please check your stream.');
  43123. return false;
  43124. }
  43125. const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;
  43126. if (!currentPlaylist) {
  43127. log(`${sharedLogLine} as current playlist is not set`);
  43128. return true;
  43129. } // no need to switch if playlist is the same
  43130. if (nextPlaylist.id === currentPlaylist.id) {
  43131. return false;
  43132. } // determine if current time is in a buffered range.
  43133. const isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  43134. // This is because in LIVE, the player plays 3 segments from the end of the
  43135. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  43136. // in those segments, a viewer will never experience a rendition upswitch.
  43137. if (!currentPlaylist.endList) {
  43138. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  43139. // doubles the time to first playback.
  43140. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  43141. log(`not ${sharedLogLine} as current playlist is live llhls, but currentTime isn't in buffered.`);
  43142. return false;
  43143. }
  43144. log(`${sharedLogLine} as current playlist is live`);
  43145. return true;
  43146. }
  43147. const forwardBuffer = timeAheadOf(buffered, currentTime);
  43148. 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
  43149. // duration is below the max potential low water line
  43150. if (duration < maxBufferLowWaterLine) {
  43151. log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);
  43152. return true;
  43153. }
  43154. const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  43155. const currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  43156. // we can switch down
  43157. if (nextBandwidth < currBandwidth && (!bufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  43158. let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;
  43159. if (bufferBasedABR) {
  43160. logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;
  43161. }
  43162. log(logLine);
  43163. return true;
  43164. } // and if our buffer is higher than the low water line,
  43165. // we can switch up
  43166. if ((!bufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  43167. let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;
  43168. if (bufferBasedABR) {
  43169. logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;
  43170. }
  43171. log(logLine);
  43172. return true;
  43173. }
  43174. log(`not ${sharedLogLine} as no switching criteria met`);
  43175. return false;
  43176. };
  43177. /**
  43178. * the main playlist controller controller all interactons
  43179. * between playlists and segmentloaders. At this time this mainly
  43180. * involves a main playlist and a series of audio playlists
  43181. * if they are available
  43182. *
  43183. * @class PlaylistController
  43184. * @extends videojs.EventTarget
  43185. */
  43186. class PlaylistController extends videojs.EventTarget {
  43187. constructor(options) {
  43188. super();
  43189. const {
  43190. src,
  43191. withCredentials,
  43192. tech,
  43193. bandwidth,
  43194. externVhs,
  43195. useCueTags,
  43196. playlistExclusionDuration,
  43197. enableLowInitialPlaylist,
  43198. sourceType,
  43199. cacheEncryptionKeys,
  43200. bufferBasedABR,
  43201. leastPixelDiffSelector,
  43202. captionServices
  43203. } = options;
  43204. if (!src) {
  43205. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  43206. }
  43207. let {
  43208. maxPlaylistRetries
  43209. } = options;
  43210. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  43211. maxPlaylistRetries = Infinity;
  43212. }
  43213. Vhs$1 = externVhs;
  43214. this.bufferBasedABR = Boolean(bufferBasedABR);
  43215. this.leastPixelDiffSelector = Boolean(leastPixelDiffSelector);
  43216. this.withCredentials = withCredentials;
  43217. this.tech_ = tech;
  43218. this.vhs_ = tech.vhs;
  43219. this.sourceType_ = sourceType;
  43220. this.useCueTags_ = useCueTags;
  43221. this.playlistExclusionDuration = playlistExclusionDuration;
  43222. this.maxPlaylistRetries = maxPlaylistRetries;
  43223. this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  43224. if (this.useCueTags_) {
  43225. this.cueTagsTrack_ = this.tech_.addTextTrack('metadata', 'ad-cues');
  43226. this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  43227. }
  43228. this.requestOptions_ = {
  43229. withCredentials,
  43230. maxPlaylistRetries,
  43231. timeout: null
  43232. };
  43233. this.on('error', this.pauseLoading);
  43234. this.mediaTypes_ = createMediaTypes();
  43235. this.mediaSource = new window$1.MediaSource();
  43236. this.handleDurationChange_ = this.handleDurationChange_.bind(this);
  43237. this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);
  43238. this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);
  43239. this.mediaSource.addEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  43240. this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);
  43241. this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  43242. // everything, and the MediaSource should not be detached without a proper disposal
  43243. this.seekable_ = createTimeRanges();
  43244. this.hasPlayed_ = false;
  43245. this.syncController_ = new SyncController(options);
  43246. this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  43247. kind: 'metadata',
  43248. label: 'segment-metadata'
  43249. }, false).track;
  43250. this.decrypter_ = new Decrypter();
  43251. this.sourceUpdater_ = new SourceUpdater(this.mediaSource);
  43252. this.inbandTextTracks_ = {};
  43253. this.timelineChangeController_ = new TimelineChangeController();
  43254. const segmentLoaderSettings = {
  43255. vhs: this.vhs_,
  43256. parse708captions: options.parse708captions,
  43257. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  43258. captionServices,
  43259. mediaSource: this.mediaSource,
  43260. currentTime: this.tech_.currentTime.bind(this.tech_),
  43261. seekable: () => this.seekable(),
  43262. seeking: () => this.tech_.seeking(),
  43263. duration: () => this.duration(),
  43264. hasPlayed: () => this.hasPlayed_,
  43265. goalBufferLength: () => this.goalBufferLength(),
  43266. bandwidth,
  43267. syncController: this.syncController_,
  43268. decrypter: this.decrypter_,
  43269. sourceType: this.sourceType_,
  43270. inbandTextTracks: this.inbandTextTracks_,
  43271. cacheEncryptionKeys,
  43272. sourceUpdater: this.sourceUpdater_,
  43273. timelineChangeController: this.timelineChangeController_,
  43274. exactManifestTimings: options.exactManifestTimings
  43275. }; // The source type check not only determines whether a special DASH playlist loader
  43276. // should be used, but also covers the case where the provided src is a vhs-json
  43277. // manifest object (instead of a URL). In the case of vhs-json, the default
  43278. // PlaylistLoader should be used.
  43279. this.mainPlaylistLoader_ = this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, this.vhs_, this.requestOptions_) : new PlaylistLoader(src, this.vhs_, this.requestOptions_);
  43280. this.setupMainPlaylistLoaderListeners_(); // setup segment loaders
  43281. // combined audio/video or just video when alternate audio track is selected
  43282. this.mainSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  43283. segmentMetadataTrack: this.segmentMetadataTrack_,
  43284. loaderType: 'main'
  43285. }), options); // alternate audio track
  43286. this.audioSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  43287. loaderType: 'audio'
  43288. }), options);
  43289. this.subtitleSegmentLoader_ = new VTTSegmentLoader(merge(segmentLoaderSettings, {
  43290. loaderType: 'vtt',
  43291. featuresNativeTextTracks: this.tech_.featuresNativeTextTracks,
  43292. loadVttJs: () => new Promise((resolve, reject) => {
  43293. function onLoad() {
  43294. tech.off('vttjserror', onError);
  43295. resolve();
  43296. }
  43297. function onError() {
  43298. tech.off('vttjsloaded', onLoad);
  43299. reject();
  43300. }
  43301. tech.one('vttjsloaded', onLoad);
  43302. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  43303. tech.addWebVttScript_();
  43304. })
  43305. }), options);
  43306. this.setupSegmentLoaderListeners_();
  43307. if (this.bufferBasedABR) {
  43308. this.mainPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());
  43309. this.tech_.on('pause', () => this.stopABRTimer_());
  43310. this.tech_.on('play', () => this.startABRTimer_());
  43311. } // Create SegmentLoader stat-getters
  43312. // mediaRequests_
  43313. // mediaRequestsAborted_
  43314. // mediaRequestsTimedout_
  43315. // mediaRequestsErrored_
  43316. // mediaTransferDuration_
  43317. // mediaBytesTransferred_
  43318. // mediaAppends_
  43319. loaderStats.forEach(stat => {
  43320. this[stat + '_'] = sumLoaderStat.bind(this, stat);
  43321. });
  43322. this.logger_ = logger('pc');
  43323. this.triggeredFmp4Usage = false;
  43324. if (this.tech_.preload() === 'none') {
  43325. this.loadOnPlay_ = () => {
  43326. this.loadOnPlay_ = null;
  43327. this.mainPlaylistLoader_.load();
  43328. };
  43329. this.tech_.one('play', this.loadOnPlay_);
  43330. } else {
  43331. this.mainPlaylistLoader_.load();
  43332. }
  43333. this.timeToLoadedData__ = -1;
  43334. this.mainAppendsToLoadedData__ = -1;
  43335. this.audioAppendsToLoadedData__ = -1;
  43336. const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  43337. this.tech_.one(event, () => {
  43338. const timeToLoadedDataStart = Date.now();
  43339. this.tech_.one('loadeddata', () => {
  43340. this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  43341. this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;
  43342. this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;
  43343. });
  43344. });
  43345. }
  43346. mainAppendsToLoadedData_() {
  43347. return this.mainAppendsToLoadedData__;
  43348. }
  43349. audioAppendsToLoadedData_() {
  43350. return this.audioAppendsToLoadedData__;
  43351. }
  43352. appendsToLoadedData_() {
  43353. const main = this.mainAppendsToLoadedData_();
  43354. const audio = this.audioAppendsToLoadedData_();
  43355. if (main === -1 || audio === -1) {
  43356. return -1;
  43357. }
  43358. return main + audio;
  43359. }
  43360. timeToLoadedData_() {
  43361. return this.timeToLoadedData__;
  43362. }
  43363. /**
  43364. * Run selectPlaylist and switch to the new playlist if we should
  43365. *
  43366. * @param {string} [reason=abr] a reason for why the ABR check is made
  43367. * @private
  43368. */
  43369. checkABR_(reason = 'abr') {
  43370. const nextPlaylist = this.selectPlaylist();
  43371. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  43372. this.switchMedia_(nextPlaylist, reason);
  43373. }
  43374. }
  43375. switchMedia_(playlist, cause, delay) {
  43376. const oldMedia = this.media();
  43377. const oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  43378. const newId = playlist.id || playlist.uri;
  43379. if (oldId && oldId !== newId) {
  43380. this.logger_(`switch media ${oldId} -> ${newId} from ${cause}`);
  43381. this.tech_.trigger({
  43382. type: 'usage',
  43383. name: `vhs-rendition-change-${cause}`
  43384. });
  43385. }
  43386. this.mainPlaylistLoader_.media(playlist, delay);
  43387. }
  43388. /**
  43389. * Start a timer that periodically calls checkABR_
  43390. *
  43391. * @private
  43392. */
  43393. startABRTimer_() {
  43394. this.stopABRTimer_();
  43395. this.abrTimer_ = window$1.setInterval(() => this.checkABR_(), 250);
  43396. }
  43397. /**
  43398. * Stop the timer that periodically calls checkABR_
  43399. *
  43400. * @private
  43401. */
  43402. stopABRTimer_() {
  43403. // if we're scrubbing, we don't need to pause.
  43404. // This getter will be added to Video.js in version 7.11.
  43405. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  43406. return;
  43407. }
  43408. window$1.clearInterval(this.abrTimer_);
  43409. this.abrTimer_ = null;
  43410. }
  43411. /**
  43412. * Get a list of playlists for the currently selected audio playlist
  43413. *
  43414. * @return {Array} the array of audio playlists
  43415. */
  43416. getAudioTrackPlaylists_() {
  43417. const main = this.main();
  43418. const defaultPlaylists = main && main.playlists || []; // if we don't have any audio groups then we can only
  43419. // assume that the audio tracks are contained in main
  43420. // playlist array, use that or an empty array.
  43421. if (!main || !main.mediaGroups || !main.mediaGroups.AUDIO) {
  43422. return defaultPlaylists;
  43423. }
  43424. const AUDIO = main.mediaGroups.AUDIO;
  43425. const groupKeys = Object.keys(AUDIO);
  43426. let track; // get the current active track
  43427. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  43428. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from main if mediaTypes_ isn't setup yet
  43429. } else {
  43430. // default group is `main` or just the first group.
  43431. const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  43432. for (const label in defaultGroup) {
  43433. if (defaultGroup[label].default) {
  43434. track = {
  43435. label
  43436. };
  43437. break;
  43438. }
  43439. }
  43440. } // no active track no playlists.
  43441. if (!track) {
  43442. return defaultPlaylists;
  43443. }
  43444. const playlists = []; // get all of the playlists that are possible for the
  43445. // active track.
  43446. for (const group in AUDIO) {
  43447. if (AUDIO[group][track.label]) {
  43448. const properties = AUDIO[group][track.label];
  43449. if (properties.playlists && properties.playlists.length) {
  43450. playlists.push.apply(playlists, properties.playlists);
  43451. } else if (properties.uri) {
  43452. playlists.push(properties);
  43453. } else if (main.playlists.length) {
  43454. // if an audio group does not have a uri
  43455. // see if we have main playlists that use it as a group.
  43456. // if we do then add those to the playlists list.
  43457. for (let i = 0; i < main.playlists.length; i++) {
  43458. const playlist = main.playlists[i];
  43459. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  43460. playlists.push(playlist);
  43461. }
  43462. }
  43463. }
  43464. }
  43465. }
  43466. if (!playlists.length) {
  43467. return defaultPlaylists;
  43468. }
  43469. return playlists;
  43470. }
  43471. /**
  43472. * Register event handlers on the main playlist loader. A helper
  43473. * function for construction time.
  43474. *
  43475. * @private
  43476. */
  43477. setupMainPlaylistLoaderListeners_() {
  43478. this.mainPlaylistLoader_.on('loadedmetadata', () => {
  43479. const media = this.mainPlaylistLoader_.media();
  43480. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  43481. // timeout the request.
  43482. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  43483. this.requestOptions_.timeout = 0;
  43484. } else {
  43485. this.requestOptions_.timeout = requestTimeout;
  43486. } // if this isn't a live video and preload permits, start
  43487. // downloading segments
  43488. if (media.endList && this.tech_.preload() !== 'none') {
  43489. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  43490. this.mainSegmentLoader_.load();
  43491. }
  43492. setupMediaGroups({
  43493. sourceType: this.sourceType_,
  43494. segmentLoaders: {
  43495. AUDIO: this.audioSegmentLoader_,
  43496. SUBTITLES: this.subtitleSegmentLoader_,
  43497. main: this.mainSegmentLoader_
  43498. },
  43499. tech: this.tech_,
  43500. requestOptions: this.requestOptions_,
  43501. mainPlaylistLoader: this.mainPlaylistLoader_,
  43502. vhs: this.vhs_,
  43503. main: this.main(),
  43504. mediaTypes: this.mediaTypes_,
  43505. excludePlaylist: this.excludePlaylist.bind(this)
  43506. });
  43507. this.triggerPresenceUsage_(this.main(), media);
  43508. this.setupFirstPlay();
  43509. if (!this.mediaTypes_.AUDIO.activePlaylistLoader || this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  43510. this.trigger('selectedinitialmedia');
  43511. } else {
  43512. // We must wait for the active audio playlist loader to
  43513. // finish setting up before triggering this event so the
  43514. // representations API and EME setup is correct
  43515. this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {
  43516. this.trigger('selectedinitialmedia');
  43517. });
  43518. }
  43519. });
  43520. this.mainPlaylistLoader_.on('loadedplaylist', () => {
  43521. if (this.loadOnPlay_) {
  43522. this.tech_.off('play', this.loadOnPlay_);
  43523. }
  43524. let updatedPlaylist = this.mainPlaylistLoader_.media();
  43525. if (!updatedPlaylist) {
  43526. // exclude any variants that are not supported by the browser before selecting
  43527. // an initial media as the playlist selectors do not consider browser support
  43528. this.excludeUnsupportedVariants_();
  43529. let selectedMedia;
  43530. if (this.enableLowInitialPlaylist) {
  43531. selectedMedia = this.selectInitialPlaylist();
  43532. }
  43533. if (!selectedMedia) {
  43534. selectedMedia = this.selectPlaylist();
  43535. }
  43536. if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {
  43537. return;
  43538. }
  43539. this.initialMedia_ = selectedMedia;
  43540. this.switchMedia_(this.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  43541. // fire again since the playlist will be requested. In the case of vhs-json
  43542. // (where the manifest object is provided as the source), when the media
  43543. // playlist's `segments` list is already available, a media playlist won't be
  43544. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  43545. // called on its own here.
  43546. const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;
  43547. if (!haveJsonSource) {
  43548. return;
  43549. }
  43550. updatedPlaylist = this.initialMedia_;
  43551. }
  43552. this.handleUpdatedMediaPlaylist(updatedPlaylist);
  43553. });
  43554. this.mainPlaylistLoader_.on('error', () => {
  43555. const error = this.mainPlaylistLoader_.error;
  43556. this.excludePlaylist({
  43557. playlistToExclude: error.playlist,
  43558. error
  43559. });
  43560. });
  43561. this.mainPlaylistLoader_.on('mediachanging', () => {
  43562. this.mainSegmentLoader_.abort();
  43563. this.mainSegmentLoader_.pause();
  43564. });
  43565. this.mainPlaylistLoader_.on('mediachange', () => {
  43566. const media = this.mainPlaylistLoader_.media();
  43567. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  43568. // timeout the request.
  43569. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  43570. this.requestOptions_.timeout = 0;
  43571. } else {
  43572. this.requestOptions_.timeout = requestTimeout;
  43573. }
  43574. this.mainPlaylistLoader_.load(); // TODO: Create a new event on the PlaylistLoader that signals
  43575. // that the segments have changed in some way and use that to
  43576. // update the SegmentLoader instead of doing it twice here and
  43577. // on `loadedplaylist`
  43578. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  43579. this.mainSegmentLoader_.load();
  43580. this.tech_.trigger({
  43581. type: 'mediachange',
  43582. bubbles: true
  43583. });
  43584. });
  43585. this.mainPlaylistLoader_.on('playlistunchanged', () => {
  43586. const updatedPlaylist = this.mainPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  43587. // excluded for not-changing. We likely just have a really slowly updating
  43588. // playlist.
  43589. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  43590. return;
  43591. }
  43592. const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);
  43593. if (playlistOutdated) {
  43594. // Playlist has stopped updating and we're stuck at its end. Try to
  43595. // exclude it and switch to another playlist in the hope that that
  43596. // one is updating (and give the player a chance to re-adjust to the
  43597. // safe live point).
  43598. this.excludePlaylist({
  43599. error: {
  43600. message: 'Playlist no longer updating.',
  43601. reason: 'playlist-unchanged'
  43602. }
  43603. }); // useful for monitoring QoS
  43604. this.tech_.trigger('playliststuck');
  43605. }
  43606. });
  43607. this.mainPlaylistLoader_.on('renditiondisabled', () => {
  43608. this.tech_.trigger({
  43609. type: 'usage',
  43610. name: 'vhs-rendition-disabled'
  43611. });
  43612. });
  43613. this.mainPlaylistLoader_.on('renditionenabled', () => {
  43614. this.tech_.trigger({
  43615. type: 'usage',
  43616. name: 'vhs-rendition-enabled'
  43617. });
  43618. });
  43619. }
  43620. /**
  43621. * Given an updated media playlist (whether it was loaded for the first time, or
  43622. * refreshed for live playlists), update any relevant properties and state to reflect
  43623. * changes in the media that should be accounted for (e.g., cues and duration).
  43624. *
  43625. * @param {Object} updatedPlaylist the updated media playlist object
  43626. *
  43627. * @private
  43628. */
  43629. handleUpdatedMediaPlaylist(updatedPlaylist) {
  43630. if (this.useCueTags_) {
  43631. this.updateAdCues_(updatedPlaylist);
  43632. } // TODO: Create a new event on the PlaylistLoader that signals
  43633. // that the segments have changed in some way and use that to
  43634. // update the SegmentLoader instead of doing it twice here and
  43635. // on `mediachange`
  43636. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  43637. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  43638. // as it is possible that it was temporarily stopped while waiting for
  43639. // a playlist (e.g., in case the playlist errored and we re-requested it).
  43640. if (!this.tech_.paused()) {
  43641. this.mainSegmentLoader_.load();
  43642. if (this.audioSegmentLoader_) {
  43643. this.audioSegmentLoader_.load();
  43644. }
  43645. }
  43646. }
  43647. /**
  43648. * A helper function for triggerring presence usage events once per source
  43649. *
  43650. * @private
  43651. */
  43652. triggerPresenceUsage_(main, media) {
  43653. const mediaGroups = main.mediaGroups || {};
  43654. let defaultDemuxed = true;
  43655. const audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  43656. for (const mediaGroup in mediaGroups.AUDIO) {
  43657. for (const label in mediaGroups.AUDIO[mediaGroup]) {
  43658. const properties = mediaGroups.AUDIO[mediaGroup][label];
  43659. if (!properties.uri) {
  43660. defaultDemuxed = false;
  43661. }
  43662. }
  43663. }
  43664. if (defaultDemuxed) {
  43665. this.tech_.trigger({
  43666. type: 'usage',
  43667. name: 'vhs-demuxed'
  43668. });
  43669. }
  43670. if (Object.keys(mediaGroups.SUBTITLES).length) {
  43671. this.tech_.trigger({
  43672. type: 'usage',
  43673. name: 'vhs-webvtt'
  43674. });
  43675. }
  43676. if (Vhs$1.Playlist.isAes(media)) {
  43677. this.tech_.trigger({
  43678. type: 'usage',
  43679. name: 'vhs-aes'
  43680. });
  43681. }
  43682. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  43683. this.tech_.trigger({
  43684. type: 'usage',
  43685. name: 'vhs-alternate-audio'
  43686. });
  43687. }
  43688. if (this.useCueTags_) {
  43689. this.tech_.trigger({
  43690. type: 'usage',
  43691. name: 'vhs-playlist-cue-tags'
  43692. });
  43693. }
  43694. }
  43695. shouldSwitchToMedia_(nextPlaylist) {
  43696. const currentPlaylist = this.mainPlaylistLoader_.media() || this.mainPlaylistLoader_.pendingMedia_;
  43697. const currentTime = this.tech_.currentTime();
  43698. const bufferLowWaterLine = this.bufferLowWaterLine();
  43699. const bufferHighWaterLine = this.bufferHighWaterLine();
  43700. const buffered = this.tech_.buffered();
  43701. return shouldSwitchToMedia({
  43702. buffered,
  43703. currentTime,
  43704. currentPlaylist,
  43705. nextPlaylist,
  43706. bufferLowWaterLine,
  43707. bufferHighWaterLine,
  43708. duration: this.duration(),
  43709. bufferBasedABR: this.bufferBasedABR,
  43710. log: this.logger_
  43711. });
  43712. }
  43713. /**
  43714. * Register event handlers on the segment loaders. A helper function
  43715. * for construction time.
  43716. *
  43717. * @private
  43718. */
  43719. setupSegmentLoaderListeners_() {
  43720. this.mainSegmentLoader_.on('bandwidthupdate', () => {
  43721. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  43722. // useful to check to see if a rendition switch should be made.
  43723. this.checkABR_('bandwidthupdate');
  43724. this.tech_.trigger('bandwidthupdate');
  43725. });
  43726. this.mainSegmentLoader_.on('timeout', () => {
  43727. if (this.bufferBasedABR) {
  43728. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  43729. // Here the only consideration is that for buffer based ABR there's no guarantee
  43730. // of an immediate switch (since the bandwidth is averaged with a timeout
  43731. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  43732. this.mainSegmentLoader_.load();
  43733. }
  43734. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  43735. // based ABR.
  43736. if (!this.bufferBasedABR) {
  43737. this.mainSegmentLoader_.on('progress', () => {
  43738. this.trigger('progress');
  43739. });
  43740. }
  43741. this.mainSegmentLoader_.on('error', () => {
  43742. const error = this.mainSegmentLoader_.error();
  43743. this.excludePlaylist({
  43744. playlistToExclude: error.playlist,
  43745. error
  43746. });
  43747. });
  43748. this.mainSegmentLoader_.on('appenderror', () => {
  43749. this.error = this.mainSegmentLoader_.error_;
  43750. this.trigger('error');
  43751. });
  43752. this.mainSegmentLoader_.on('syncinfoupdate', () => {
  43753. this.onSyncInfoUpdate_();
  43754. });
  43755. this.mainSegmentLoader_.on('timestampoffset', () => {
  43756. this.tech_.trigger({
  43757. type: 'usage',
  43758. name: 'vhs-timestamp-offset'
  43759. });
  43760. });
  43761. this.audioSegmentLoader_.on('syncinfoupdate', () => {
  43762. this.onSyncInfoUpdate_();
  43763. });
  43764. this.audioSegmentLoader_.on('appenderror', () => {
  43765. this.error = this.audioSegmentLoader_.error_;
  43766. this.trigger('error');
  43767. });
  43768. this.mainSegmentLoader_.on('ended', () => {
  43769. this.logger_('main segment loader ended');
  43770. this.onEndOfStream();
  43771. });
  43772. this.mainSegmentLoader_.on('earlyabort', event => {
  43773. // never try to early abort with the new ABR algorithm
  43774. if (this.bufferBasedABR) {
  43775. return;
  43776. }
  43777. this.delegateLoaders_('all', ['abort']);
  43778. this.excludePlaylist({
  43779. error: {
  43780. message: 'Aborted early because there isn\'t enough bandwidth to complete ' + 'the request without rebuffering.'
  43781. },
  43782. playlistExclusionDuration: ABORT_EARLY_EXCLUSION_SECONDS
  43783. });
  43784. });
  43785. const updateCodecs = () => {
  43786. if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {
  43787. return this.tryToCreateSourceBuffers_();
  43788. }
  43789. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  43790. if (!codecs) {
  43791. return;
  43792. }
  43793. this.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  43794. };
  43795. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  43796. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  43797. this.mainSegmentLoader_.on('fmp4', () => {
  43798. if (!this.triggeredFmp4Usage) {
  43799. this.tech_.trigger({
  43800. type: 'usage',
  43801. name: 'vhs-fmp4'
  43802. });
  43803. this.triggeredFmp4Usage = true;
  43804. }
  43805. });
  43806. this.audioSegmentLoader_.on('fmp4', () => {
  43807. if (!this.triggeredFmp4Usage) {
  43808. this.tech_.trigger({
  43809. type: 'usage',
  43810. name: 'vhs-fmp4'
  43811. });
  43812. this.triggeredFmp4Usage = true;
  43813. }
  43814. });
  43815. this.audioSegmentLoader_.on('ended', () => {
  43816. this.logger_('audioSegmentLoader ended');
  43817. this.onEndOfStream();
  43818. });
  43819. }
  43820. mediaSecondsLoaded_() {
  43821. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  43822. }
  43823. /**
  43824. * Call load on our SegmentLoaders
  43825. */
  43826. load() {
  43827. this.mainSegmentLoader_.load();
  43828. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  43829. this.audioSegmentLoader_.load();
  43830. }
  43831. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  43832. this.subtitleSegmentLoader_.load();
  43833. }
  43834. }
  43835. /**
  43836. * Re-tune playback quality level for the current player
  43837. * conditions. This method will perform destructive actions like removing
  43838. * already buffered content in order to readjust the currently active
  43839. * playlist quickly. This is good for manual quality changes
  43840. *
  43841. * @private
  43842. */
  43843. fastQualityChange_(media = this.selectPlaylist()) {
  43844. if (media === this.mainPlaylistLoader_.media()) {
  43845. this.logger_('skipping fastQualityChange because new media is same as old');
  43846. return;
  43847. }
  43848. this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
  43849. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  43850. // ahead is roughly the minimum that will accomplish this across a variety of content
  43851. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  43852. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  43853. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  43854. this.mainSegmentLoader_.resetEverything(() => {
  43855. // Since this is not a typical seek, we avoid the seekTo method which can cause segments
  43856. // from the previously enabled rendition to load before the new playlist has finished loading
  43857. if (videojs.browser.IE_VERSION || videojs.browser.IS_EDGE) {
  43858. this.tech_.setCurrentTime(this.tech_.currentTime() + 0.04);
  43859. } else {
  43860. this.tech_.setCurrentTime(this.tech_.currentTime());
  43861. }
  43862. }); // don't need to reset audio as it is reset when media changes
  43863. }
  43864. /**
  43865. * Begin playback.
  43866. */
  43867. play() {
  43868. if (this.setupFirstPlay()) {
  43869. return;
  43870. }
  43871. if (this.tech_.ended()) {
  43872. this.tech_.setCurrentTime(0);
  43873. }
  43874. if (this.hasPlayed_) {
  43875. this.load();
  43876. }
  43877. const seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  43878. // seek forward to the live point
  43879. if (this.tech_.duration() === Infinity) {
  43880. if (this.tech_.currentTime() < seekable.start(0)) {
  43881. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  43882. }
  43883. }
  43884. }
  43885. /**
  43886. * Seek to the latest media position if this is a live video and the
  43887. * player and video are loaded and initialized.
  43888. */
  43889. setupFirstPlay() {
  43890. const media = this.mainPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  43891. // If 1) there is no active media
  43892. // 2) the player is paused
  43893. // 3) the first play has already been setup
  43894. // then exit early
  43895. if (!media || this.tech_.paused() || this.hasPlayed_) {
  43896. return false;
  43897. } // when the video is a live stream
  43898. if (!media.endList) {
  43899. const seekable = this.seekable();
  43900. if (!seekable.length) {
  43901. // without a seekable range, the player cannot seek to begin buffering at the live
  43902. // point
  43903. return false;
  43904. }
  43905. if (videojs.browser.IE_VERSION && this.tech_.readyState() === 0) {
  43906. // IE11 throws an InvalidStateError if you try to set currentTime while the
  43907. // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
  43908. this.tech_.one('loadedmetadata', () => {
  43909. this.trigger('firstplay');
  43910. this.tech_.setCurrentTime(seekable.end(0));
  43911. this.hasPlayed_ = true;
  43912. });
  43913. return false;
  43914. } // trigger firstplay to inform the source handler to ignore the next seek event
  43915. this.trigger('firstplay'); // seek to the live point
  43916. this.tech_.setCurrentTime(seekable.end(0));
  43917. }
  43918. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  43919. this.load();
  43920. return true;
  43921. }
  43922. /**
  43923. * handle the sourceopen event on the MediaSource
  43924. *
  43925. * @private
  43926. */
  43927. handleSourceOpen_() {
  43928. // Only attempt to create the source buffer if none already exist.
  43929. // handleSourceOpen is also called when we are "re-opening" a source buffer
  43930. // after `endOfStream` has been called (in response to a seek for instance)
  43931. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  43932. // code in video.js but is required because play() must be invoked
  43933. // *after* the media source has opened.
  43934. if (this.tech_.autoplay()) {
  43935. const playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  43936. // on browsers which return a promise
  43937. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  43938. playPromise.then(null, e => {});
  43939. }
  43940. }
  43941. this.trigger('sourceopen');
  43942. }
  43943. /**
  43944. * handle the sourceended event on the MediaSource
  43945. *
  43946. * @private
  43947. */
  43948. handleSourceEnded_() {
  43949. if (!this.inbandTextTracks_.metadataTrack_) {
  43950. return;
  43951. }
  43952. const cues = this.inbandTextTracks_.metadataTrack_.cues;
  43953. if (!cues || !cues.length) {
  43954. return;
  43955. }
  43956. const duration = this.duration();
  43957. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  43958. }
  43959. /**
  43960. * handle the durationchange event on the MediaSource
  43961. *
  43962. * @private
  43963. */
  43964. handleDurationChange_() {
  43965. this.tech_.trigger('durationchange');
  43966. }
  43967. /**
  43968. * Calls endOfStream on the media source when all active stream types have called
  43969. * endOfStream
  43970. *
  43971. * @param {string} streamType
  43972. * Stream type of the segment loader that called endOfStream
  43973. * @private
  43974. */
  43975. onEndOfStream() {
  43976. let isEndOfStream = this.mainSegmentLoader_.ended_;
  43977. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  43978. const mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  43979. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  43980. // if we do not know if the main segment loader contains video yet or if we
  43981. // definitively know the main segment loader contains video, then we need to wait
  43982. // for both main and audio segment loaders to call endOfStream
  43983. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  43984. } else {
  43985. // otherwise just rely on the audio loader
  43986. isEndOfStream = this.audioSegmentLoader_.ended_;
  43987. }
  43988. }
  43989. if (!isEndOfStream) {
  43990. return;
  43991. }
  43992. this.stopABRTimer_();
  43993. this.sourceUpdater_.endOfStream();
  43994. }
  43995. /**
  43996. * Check if a playlist has stopped being updated
  43997. *
  43998. * @param {Object} playlist the media playlist object
  43999. * @return {boolean} whether the playlist has stopped being updated or not
  44000. */
  44001. stuckAtPlaylistEnd_(playlist) {
  44002. const seekable = this.seekable();
  44003. if (!seekable.length) {
  44004. // playlist doesn't have enough information to determine whether we are stuck
  44005. return false;
  44006. }
  44007. const expired = this.syncController_.getExpiredTime(playlist, this.duration());
  44008. if (expired === null) {
  44009. return false;
  44010. } // does not use the safe live end to calculate playlist end, since we
  44011. // don't want to say we are stuck while there is still content
  44012. const absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  44013. const currentTime = this.tech_.currentTime();
  44014. const buffered = this.tech_.buffered();
  44015. if (!buffered.length) {
  44016. // return true if the playhead reached the absolute end of the playlist
  44017. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  44018. }
  44019. const bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  44020. // end of playlist
  44021. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  44022. }
  44023. /**
  44024. * Exclude a playlist for a set amount of time, making it unavailable for selection by
  44025. * the rendition selection algorithm, then force a new playlist (rendition) selection.
  44026. *
  44027. * @param {Object=} playlistToExclude
  44028. * the playlist to exclude, defaults to the currently selected playlist
  44029. * @param {Object=} error
  44030. * an optional error
  44031. * @param {number=} playlistExclusionDuration
  44032. * an optional number of seconds to exclude the playlist
  44033. */
  44034. excludePlaylist({
  44035. playlistToExclude = this.mainPlaylistLoader_.media(),
  44036. error = {},
  44037. playlistExclusionDuration
  44038. }) {
  44039. // If the `error` was generated by the playlist loader, it will contain
  44040. // the playlist we were trying to load (but failed) and that should be
  44041. // excluded instead of the currently selected playlist which is likely
  44042. // out-of-date in this scenario
  44043. playlistToExclude = playlistToExclude || this.mainPlaylistLoader_.media();
  44044. playlistExclusionDuration = playlistExclusionDuration || error.playlistExclusionDuration || this.playlistExclusionDuration; // If there is no current playlist, then an error occurred while we were
  44045. // trying to load the main OR while we were disposing of the tech
  44046. if (!playlistToExclude) {
  44047. this.error = error;
  44048. if (this.mediaSource.readyState !== 'open') {
  44049. this.trigger('error');
  44050. } else {
  44051. this.sourceUpdater_.endOfStream('network');
  44052. }
  44053. return;
  44054. }
  44055. playlistToExclude.playlistErrors_++;
  44056. const playlists = this.mainPlaylistLoader_.main.playlists;
  44057. const enabledPlaylists = playlists.filter(isEnabled);
  44058. const isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === playlistToExclude; // Don't exclude the only playlist unless it was excluded
  44059. // forever
  44060. if (playlists.length === 1 && playlistExclusionDuration !== Infinity) {
  44061. videojs.log.warn(`Problem encountered with playlist ${playlistToExclude.id}. ` + 'Trying again since it is the only playlist.');
  44062. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  44063. return this.mainPlaylistLoader_.load(isFinalRendition);
  44064. }
  44065. if (isFinalRendition) {
  44066. // Since we're on the final non-excluded playlist, and we're about to exclude
  44067. // it, instead of erring the player or retrying this playlist, clear out the current
  44068. // exclusion list. This allows other playlists to be attempted in case any have been
  44069. // fixed.
  44070. let reincluded = false;
  44071. playlists.forEach(playlist => {
  44072. // skip current playlist which is about to be excluded
  44073. if (playlist === playlistToExclude) {
  44074. return;
  44075. }
  44076. const excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  44077. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  44078. reincluded = true;
  44079. delete playlist.excludeUntil;
  44080. }
  44081. });
  44082. if (reincluded) {
  44083. 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
  44084. // playlist. This is needed for users relying on the retryplaylist event to catch a
  44085. // case where the player might be stuck and looping through "dead" playlists.
  44086. this.tech_.trigger('retryplaylist');
  44087. }
  44088. } // Exclude this playlist
  44089. let excludeUntil;
  44090. if (playlistToExclude.playlistErrors_ > this.maxPlaylistRetries) {
  44091. excludeUntil = Infinity;
  44092. } else {
  44093. excludeUntil = Date.now() + playlistExclusionDuration * 1000;
  44094. }
  44095. playlistToExclude.excludeUntil = excludeUntil;
  44096. if (error.reason) {
  44097. playlistToExclude.lastExcludeReason_ = error.reason;
  44098. }
  44099. this.tech_.trigger('excludeplaylist');
  44100. this.tech_.trigger({
  44101. type: 'usage',
  44102. name: 'vhs-rendition-excluded'
  44103. }); // TODO: only load a new playlist if we're excluding the current playlist
  44104. // If this function was called with a playlist that's not the current active playlist
  44105. // (e.g., media().id !== playlistToExclude.id),
  44106. // then a new playlist should not be selected and loaded, as there's nothing wrong with the current playlist.
  44107. const nextPlaylist = this.selectPlaylist();
  44108. if (!nextPlaylist) {
  44109. this.error = 'Playback cannot continue. No available working or supported playlists.';
  44110. this.trigger('error');
  44111. return;
  44112. }
  44113. const logFn = error.internal ? this.logger_ : videojs.log.warn;
  44114. const errorMessage = error.message ? ' ' + error.message : '';
  44115. logFn(`${error.internal ? 'Internal problem' : 'Problem'} encountered with playlist ${playlistToExclude.id}.` + `${errorMessage} Switching to playlist ${nextPlaylist.id}.`); // if audio group changed reset audio loaders
  44116. if (nextPlaylist.attributes.AUDIO !== playlistToExclude.attributes.AUDIO) {
  44117. this.delegateLoaders_('audio', ['abort', 'pause']);
  44118. } // if subtitle group changed reset subtitle loaders
  44119. if (nextPlaylist.attributes.SUBTITLES !== playlistToExclude.attributes.SUBTITLES) {
  44120. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  44121. }
  44122. this.delegateLoaders_('main', ['abort', 'pause']);
  44123. const delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  44124. 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
  44125. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  44126. }
  44127. /**
  44128. * Pause all segment/playlist loaders
  44129. */
  44130. pauseLoading() {
  44131. this.delegateLoaders_('all', ['abort', 'pause']);
  44132. this.stopABRTimer_();
  44133. }
  44134. /**
  44135. * Call a set of functions in order on playlist loaders, segment loaders,
  44136. * or both types of loaders.
  44137. *
  44138. * @param {string} filter
  44139. * Filter loaders that should call fnNames using a string. Can be:
  44140. * * all - run on all loaders
  44141. * * audio - run on all audio loaders
  44142. * * subtitle - run on all subtitle loaders
  44143. * * main - run on the main loaders
  44144. *
  44145. * @param {Array|string} fnNames
  44146. * A string or array of function names to call.
  44147. */
  44148. delegateLoaders_(filter, fnNames) {
  44149. const loaders = [];
  44150. const dontFilterPlaylist = filter === 'all';
  44151. if (dontFilterPlaylist || filter === 'main') {
  44152. loaders.push(this.mainPlaylistLoader_);
  44153. }
  44154. const mediaTypes = [];
  44155. if (dontFilterPlaylist || filter === 'audio') {
  44156. mediaTypes.push('AUDIO');
  44157. }
  44158. if (dontFilterPlaylist || filter === 'subtitle') {
  44159. mediaTypes.push('CLOSED-CAPTIONS');
  44160. mediaTypes.push('SUBTITLES');
  44161. }
  44162. mediaTypes.forEach(mediaType => {
  44163. const loader = this.mediaTypes_[mediaType] && this.mediaTypes_[mediaType].activePlaylistLoader;
  44164. if (loader) {
  44165. loaders.push(loader);
  44166. }
  44167. });
  44168. ['main', 'audio', 'subtitle'].forEach(name => {
  44169. const loader = this[`${name}SegmentLoader_`];
  44170. if (loader && (filter === name || filter === 'all')) {
  44171. loaders.push(loader);
  44172. }
  44173. });
  44174. loaders.forEach(loader => fnNames.forEach(fnName => {
  44175. if (typeof loader[fnName] === 'function') {
  44176. loader[fnName]();
  44177. }
  44178. }));
  44179. }
  44180. /**
  44181. * set the current time on all segment loaders
  44182. *
  44183. * @param {TimeRange} currentTime the current time to set
  44184. * @return {TimeRange} the current time
  44185. */
  44186. setCurrentTime(currentTime) {
  44187. const buffered = findRange(this.tech_.buffered(), currentTime);
  44188. if (!(this.mainPlaylistLoader_ && this.mainPlaylistLoader_.media())) {
  44189. // return immediately if the metadata is not ready yet
  44190. return 0;
  44191. } // it's clearly an edge-case but don't thrown an error if asked to
  44192. // seek within an empty playlist
  44193. if (!this.mainPlaylistLoader_.media().segments) {
  44194. return 0;
  44195. } // if the seek location is already buffered, continue buffering as usual
  44196. if (buffered && buffered.length) {
  44197. return currentTime;
  44198. } // cancel outstanding requests so we begin buffering at the new
  44199. // location
  44200. this.mainSegmentLoader_.resetEverything();
  44201. this.mainSegmentLoader_.abort();
  44202. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  44203. this.audioSegmentLoader_.resetEverything();
  44204. this.audioSegmentLoader_.abort();
  44205. }
  44206. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  44207. this.subtitleSegmentLoader_.resetEverything();
  44208. this.subtitleSegmentLoader_.abort();
  44209. } // start segment loader loading in case they are paused
  44210. this.load();
  44211. }
  44212. /**
  44213. * get the current duration
  44214. *
  44215. * @return {TimeRange} the duration
  44216. */
  44217. duration() {
  44218. if (!this.mainPlaylistLoader_) {
  44219. return 0;
  44220. }
  44221. const media = this.mainPlaylistLoader_.media();
  44222. if (!media) {
  44223. // no playlists loaded yet, so can't determine a duration
  44224. return 0;
  44225. } // Don't rely on the media source for duration in the case of a live playlist since
  44226. // setting the native MediaSource's duration to infinity ends up with consequences to
  44227. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  44228. //
  44229. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  44230. // however, few browsers have support for setLiveSeekableRange()
  44231. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  44232. //
  44233. // Until a time when the duration of the media source can be set to infinity, and a
  44234. // seekable range specified across browsers, just return Infinity.
  44235. if (!media.endList) {
  44236. return Infinity;
  44237. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  44238. // available). If it's not available, fall back to a playlist-calculated estimate.
  44239. if (this.mediaSource) {
  44240. return this.mediaSource.duration;
  44241. }
  44242. return Vhs$1.Playlist.duration(media);
  44243. }
  44244. /**
  44245. * check the seekable range
  44246. *
  44247. * @return {TimeRange} the seekable range
  44248. */
  44249. seekable() {
  44250. return this.seekable_;
  44251. }
  44252. onSyncInfoUpdate_() {
  44253. let audioSeekable; // TODO check for creation of both source buffers before updating seekable
  44254. //
  44255. // A fix was made to this function where a check for
  44256. // this.sourceUpdater_.hasCreatedSourceBuffers
  44257. // was added to ensure that both source buffers were created before seekable was
  44258. // updated. However, it originally had a bug where it was checking for a true and
  44259. // returning early instead of checking for false. Setting it to check for false to
  44260. // return early though created other issues. A call to play() would check for seekable
  44261. // end without verifying that a seekable range was present. In addition, even checking
  44262. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  44263. // due to a media update calling load on the segment loaders, skipping a seek to live,
  44264. // thereby starting live streams at the beginning of the stream rather than at the end.
  44265. //
  44266. // This conditional should be fixed to wait for the creation of two source buffers at
  44267. // the same time as the other sections of code are fixed to properly seek to live and
  44268. // not throw an error due to checking for a seekable end when no seekable range exists.
  44269. //
  44270. // For now, fall back to the older behavior, with the understanding that the seekable
  44271. // range may not be completely correct, leading to a suboptimal initial live point.
  44272. if (!this.mainPlaylistLoader_) {
  44273. return;
  44274. }
  44275. let media = this.mainPlaylistLoader_.media();
  44276. if (!media) {
  44277. return;
  44278. }
  44279. let expired = this.syncController_.getExpiredTime(media, this.duration());
  44280. if (expired === null) {
  44281. // not enough information to update seekable
  44282. return;
  44283. }
  44284. const main = this.mainPlaylistLoader_.main;
  44285. const mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  44286. if (mainSeekable.length === 0) {
  44287. return;
  44288. }
  44289. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  44290. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  44291. expired = this.syncController_.getExpiredTime(media, this.duration());
  44292. if (expired === null) {
  44293. return;
  44294. }
  44295. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  44296. if (audioSeekable.length === 0) {
  44297. return;
  44298. }
  44299. }
  44300. let oldEnd;
  44301. let oldStart;
  44302. if (this.seekable_ && this.seekable_.length) {
  44303. oldEnd = this.seekable_.end(0);
  44304. oldStart = this.seekable_.start(0);
  44305. }
  44306. if (!audioSeekable) {
  44307. // seekable has been calculated based on buffering video data so it
  44308. // can be returned directly
  44309. this.seekable_ = mainSeekable;
  44310. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  44311. // seekables are pretty far off, rely on main
  44312. this.seekable_ = mainSeekable;
  44313. } else {
  44314. 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)]]);
  44315. } // seekable is the same as last time
  44316. if (this.seekable_ && this.seekable_.length) {
  44317. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  44318. return;
  44319. }
  44320. }
  44321. this.logger_(`seekable updated [${printableRange(this.seekable_)}]`);
  44322. this.tech_.trigger('seekablechanged');
  44323. }
  44324. /**
  44325. * Update the player duration
  44326. */
  44327. updateDuration(isLive) {
  44328. if (this.updateDuration_) {
  44329. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  44330. this.updateDuration_ = null;
  44331. }
  44332. if (this.mediaSource.readyState !== 'open') {
  44333. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  44334. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  44335. return;
  44336. }
  44337. if (isLive) {
  44338. const seekable = this.seekable();
  44339. if (!seekable.length) {
  44340. return;
  44341. } // Even in the case of a live playlist, the native MediaSource's duration should not
  44342. // be set to Infinity (even though this would be expected for a live playlist), since
  44343. // setting the native MediaSource's duration to infinity ends up with consequences to
  44344. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  44345. //
  44346. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  44347. // however, few browsers have support for setLiveSeekableRange()
  44348. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  44349. //
  44350. // Until a time when the duration of the media source can be set to infinity, and a
  44351. // seekable range specified across browsers, the duration should be greater than or
  44352. // equal to the last possible seekable value.
  44353. // MediaSource duration starts as NaN
  44354. // It is possible (and probable) that this case will never be reached for many
  44355. // sources, since the MediaSource reports duration as the highest value without
  44356. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  44357. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  44358. // time will be between 0 and 100, the native media source may report the duration
  44359. // as 200. However, since we report duration separate from the media source (as
  44360. // Infinity), and as long as the native media source duration value is greater than
  44361. // our reported seekable range, seeks will work as expected. The large number as
  44362. // duration for live is actually a strategy used by some players to work around the
  44363. // issue of live seekable ranges cited above.
  44364. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  44365. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  44366. }
  44367. return;
  44368. }
  44369. const buffered = this.tech_.buffered();
  44370. let duration = Vhs$1.Playlist.duration(this.mainPlaylistLoader_.media());
  44371. if (buffered.length > 0) {
  44372. duration = Math.max(duration, buffered.end(buffered.length - 1));
  44373. }
  44374. if (this.mediaSource.duration !== duration) {
  44375. this.sourceUpdater_.setDuration(duration);
  44376. }
  44377. }
  44378. /**
  44379. * dispose of the PlaylistController and everything
  44380. * that it controls
  44381. */
  44382. dispose() {
  44383. this.trigger('dispose');
  44384. this.decrypter_.terminate();
  44385. this.mainPlaylistLoader_.dispose();
  44386. this.mainSegmentLoader_.dispose();
  44387. if (this.loadOnPlay_) {
  44388. this.tech_.off('play', this.loadOnPlay_);
  44389. }
  44390. ['AUDIO', 'SUBTITLES'].forEach(type => {
  44391. const groups = this.mediaTypes_[type].groups;
  44392. for (const id in groups) {
  44393. groups[id].forEach(group => {
  44394. if (group.playlistLoader) {
  44395. group.playlistLoader.dispose();
  44396. }
  44397. });
  44398. }
  44399. });
  44400. this.audioSegmentLoader_.dispose();
  44401. this.subtitleSegmentLoader_.dispose();
  44402. this.sourceUpdater_.dispose();
  44403. this.timelineChangeController_.dispose();
  44404. this.stopABRTimer_();
  44405. if (this.updateDuration_) {
  44406. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  44407. }
  44408. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  44409. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  44410. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  44411. this.off();
  44412. }
  44413. /**
  44414. * return the main playlist object if we have one
  44415. *
  44416. * @return {Object} the main playlist object that we parsed
  44417. */
  44418. main() {
  44419. return this.mainPlaylistLoader_.main;
  44420. }
  44421. /**
  44422. * return the currently selected playlist
  44423. *
  44424. * @return {Object} the currently selected playlist object that we parsed
  44425. */
  44426. media() {
  44427. // playlist loader will not return media if it has not been fully loaded
  44428. return this.mainPlaylistLoader_.media() || this.initialMedia_;
  44429. }
  44430. areMediaTypesKnown_() {
  44431. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  44432. const hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  44433. // otherwise check on the segment loader.
  44434. const hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  44435. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  44436. return false;
  44437. }
  44438. return true;
  44439. }
  44440. getCodecsOrExclude_() {
  44441. const media = {
  44442. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  44443. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  44444. };
  44445. const playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  44446. media.video = media.main;
  44447. const playlistCodecs = codecsForPlaylist(this.main(), playlist);
  44448. const codecs = {};
  44449. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  44450. if (media.main.hasVideo) {
  44451. codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
  44452. }
  44453. if (media.main.isMuxed) {
  44454. codecs.video += `,${playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC}`;
  44455. }
  44456. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  44457. codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
  44458. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  44459. } // no codecs, no playback.
  44460. if (!codecs.audio && !codecs.video) {
  44461. this.excludePlaylist({
  44462. playlistToExclude: playlist,
  44463. error: {
  44464. message: 'Could not determine codecs for playlist.'
  44465. },
  44466. playlistExclusionDuration: Infinity
  44467. });
  44468. return;
  44469. } // fmp4 relies on browser support, while ts relies on muxer support
  44470. const supportFunction = (isFmp4, codec) => isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
  44471. const unsupportedCodecs = {};
  44472. let unsupportedAudio;
  44473. ['video', 'audio'].forEach(function (type) {
  44474. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  44475. const supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  44476. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  44477. unsupportedCodecs[supporter].push(codecs[type]);
  44478. if (type === 'audio') {
  44479. unsupportedAudio = supporter;
  44480. }
  44481. }
  44482. });
  44483. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  44484. const audioGroup = playlist.attributes.AUDIO;
  44485. this.main().playlists.forEach(variant => {
  44486. const variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  44487. if (variantAudioGroup === audioGroup && variant !== playlist) {
  44488. variant.excludeUntil = Infinity;
  44489. }
  44490. });
  44491. this.logger_(`excluding audio group ${audioGroup} as ${unsupportedAudio} does not support codec(s): "${codecs.audio}"`);
  44492. } // if we have any unsupported codecs exclude this playlist.
  44493. if (Object.keys(unsupportedCodecs).length) {
  44494. const message = Object.keys(unsupportedCodecs).reduce((acc, supporter) => {
  44495. if (acc) {
  44496. acc += ', ';
  44497. }
  44498. acc += `${supporter} does not support codec(s): "${unsupportedCodecs[supporter].join(',')}"`;
  44499. return acc;
  44500. }, '') + '.';
  44501. this.excludePlaylist({
  44502. playlistToExclude: playlist,
  44503. error: {
  44504. internal: true,
  44505. message
  44506. },
  44507. playlistExclusionDuration: Infinity
  44508. });
  44509. return;
  44510. } // check if codec switching is happening
  44511. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  44512. const switchMessages = [];
  44513. ['video', 'audio'].forEach(type => {
  44514. const newCodec = (parseCodecs(this.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  44515. const oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
  44516. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  44517. switchMessages.push(`"${this.sourceUpdater_.codecs[type]}" -> "${codecs[type]}"`);
  44518. }
  44519. });
  44520. if (switchMessages.length) {
  44521. this.excludePlaylist({
  44522. playlistToExclude: playlist,
  44523. error: {
  44524. message: `Codec switching not supported: ${switchMessages.join(', ')}.`,
  44525. internal: true
  44526. },
  44527. playlistExclusionDuration: Infinity
  44528. });
  44529. return;
  44530. }
  44531. } // TODO: when using the muxer shouldn't we just return
  44532. // the codecs that the muxer outputs?
  44533. return codecs;
  44534. }
  44535. /**
  44536. * Create source buffers and exlude any incompatible renditions.
  44537. *
  44538. * @private
  44539. */
  44540. tryToCreateSourceBuffers_() {
  44541. // media source is not ready yet or sourceBuffers are already
  44542. // created.
  44543. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  44544. return;
  44545. }
  44546. if (!this.areMediaTypesKnown_()) {
  44547. return;
  44548. }
  44549. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  44550. if (!codecs) {
  44551. return;
  44552. }
  44553. this.sourceUpdater_.createSourceBuffers(codecs);
  44554. const codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  44555. this.excludeIncompatibleVariants_(codecString);
  44556. }
  44557. /**
  44558. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  44559. */
  44560. excludeUnsupportedVariants_() {
  44561. const playlists = this.main().playlists;
  44562. const ids = []; // TODO: why don't we have a property to loop through all
  44563. // playlist? Why did we ever mix indexes and keys?
  44564. Object.keys(playlists).forEach(key => {
  44565. const variant = playlists[key]; // check if we already processed this playlist.
  44566. if (ids.indexOf(variant.id) !== -1) {
  44567. return;
  44568. }
  44569. ids.push(variant.id);
  44570. const codecs = codecsForPlaylist(this.main, variant);
  44571. const unsupported = [];
  44572. if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
  44573. unsupported.push(`audio codec ${codecs.audio}`);
  44574. }
  44575. if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
  44576. unsupported.push(`video codec ${codecs.video}`);
  44577. }
  44578. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  44579. unsupported.push(`text codec ${codecs.text}`);
  44580. }
  44581. if (unsupported.length) {
  44582. variant.excludeUntil = Infinity;
  44583. this.logger_(`excluding ${variant.id} for unsupported: ${unsupported.join(', ')}`);
  44584. }
  44585. });
  44586. }
  44587. /**
  44588. * Exclude playlists that are known to be codec or
  44589. * stream-incompatible with the SourceBuffer configuration. For
  44590. * instance, Media Source Extensions would cause the video element to
  44591. * stall waiting for video data if you switched from a variant with
  44592. * video and audio to an audio-only one.
  44593. *
  44594. * @param {Object} media a media playlist compatible with the current
  44595. * set of SourceBuffers. Variants in the current main playlist that
  44596. * do not appear to have compatible codec or stream configurations
  44597. * will be excluded from the default playlist selection algorithm
  44598. * indefinitely.
  44599. * @private
  44600. */
  44601. excludeIncompatibleVariants_(codecString) {
  44602. const ids = [];
  44603. const playlists = this.main().playlists;
  44604. const codecs = unwrapCodecList(parseCodecs(codecString));
  44605. const codecCount_ = codecCount(codecs);
  44606. const videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
  44607. const audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
  44608. Object.keys(playlists).forEach(key => {
  44609. const variant = playlists[key]; // check if we already processed this playlist.
  44610. // or it if it is already excluded forever.
  44611. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  44612. return;
  44613. }
  44614. ids.push(variant.id);
  44615. const exclusionReasons = []; // get codecs from the playlist for this variant
  44616. const variantCodecs = codecsForPlaylist(this.mainPlaylistLoader_.main, variant);
  44617. const variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  44618. // variant is incompatible. Wait for mux.js to probe
  44619. if (!variantCodecs.audio && !variantCodecs.video) {
  44620. return;
  44621. } // TODO: we can support this by removing the
  44622. // old media source and creating a new one, but it will take some work.
  44623. // The number of streams cannot change
  44624. if (variantCodecCount !== codecCount_) {
  44625. exclusionReasons.push(`codec count "${variantCodecCount}" !== "${codecCount_}"`);
  44626. } // only exclude playlists by codec change, if codecs cannot switch
  44627. // during playback.
  44628. if (!this.sourceUpdater_.canChangeType()) {
  44629. const variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
  44630. const variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  44631. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  44632. exclusionReasons.push(`video codec "${variantVideoDetails.type}" !== "${videoDetails.type}"`);
  44633. } // the audio codec cannot change
  44634. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  44635. exclusionReasons.push(`audio codec "${variantAudioDetails.type}" !== "${audioDetails.type}"`);
  44636. }
  44637. }
  44638. if (exclusionReasons.length) {
  44639. variant.excludeUntil = Infinity;
  44640. this.logger_(`excluding ${variant.id}: ${exclusionReasons.join(' && ')}`);
  44641. }
  44642. });
  44643. }
  44644. updateAdCues_(media) {
  44645. let offset = 0;
  44646. const seekable = this.seekable();
  44647. if (seekable.length) {
  44648. offset = seekable.start(0);
  44649. }
  44650. updateAdCues(media, this.cueTagsTrack_, offset);
  44651. }
  44652. /**
  44653. * Calculates the desired forward buffer length based on current time
  44654. *
  44655. * @return {number} Desired forward buffer length in seconds
  44656. */
  44657. goalBufferLength() {
  44658. const currentTime = this.tech_.currentTime();
  44659. const initial = Config.GOAL_BUFFER_LENGTH;
  44660. const rate = Config.GOAL_BUFFER_LENGTH_RATE;
  44661. const max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  44662. return Math.min(initial + currentTime * rate, max);
  44663. }
  44664. /**
  44665. * Calculates the desired buffer low water line based on current time
  44666. *
  44667. * @return {number} Desired buffer low water line in seconds
  44668. */
  44669. bufferLowWaterLine() {
  44670. const currentTime = this.tech_.currentTime();
  44671. const initial = Config.BUFFER_LOW_WATER_LINE;
  44672. const rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  44673. const max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  44674. const newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  44675. return Math.min(initial + currentTime * rate, this.bufferBasedABR ? newMax : max);
  44676. }
  44677. bufferHighWaterLine() {
  44678. return Config.BUFFER_HIGH_WATER_LINE;
  44679. }
  44680. }
  44681. /**
  44682. * Returns a function that acts as the Enable/disable playlist function.
  44683. *
  44684. * @param {PlaylistLoader} loader - The main playlist loader
  44685. * @param {string} playlistID - id of the playlist
  44686. * @param {Function} changePlaylistFn - A function to be called after a
  44687. * playlist's enabled-state has been changed. Will NOT be called if a
  44688. * playlist's enabled-state is unchanged
  44689. * @param {boolean=} enable - Value to set the playlist enabled-state to
  44690. * or if undefined returns the current enabled-state for the playlist
  44691. * @return {Function} Function for setting/getting enabled
  44692. */
  44693. const enableFunction = (loader, playlistID, changePlaylistFn) => enable => {
  44694. const playlist = loader.main.playlists[playlistID];
  44695. const incompatible = isIncompatible(playlist);
  44696. const currentlyEnabled = isEnabled(playlist);
  44697. if (typeof enable === 'undefined') {
  44698. return currentlyEnabled;
  44699. }
  44700. if (enable) {
  44701. delete playlist.disabled;
  44702. } else {
  44703. playlist.disabled = true;
  44704. }
  44705. if (enable !== currentlyEnabled && !incompatible) {
  44706. // Ensure the outside world knows about our changes
  44707. changePlaylistFn();
  44708. if (enable) {
  44709. loader.trigger('renditionenabled');
  44710. } else {
  44711. loader.trigger('renditiondisabled');
  44712. }
  44713. }
  44714. return enable;
  44715. };
  44716. /**
  44717. * The representation object encapsulates the publicly visible information
  44718. * in a media playlist along with a setter/getter-type function (enabled)
  44719. * for changing the enabled-state of a particular playlist entry
  44720. *
  44721. * @class Representation
  44722. */
  44723. class Representation {
  44724. constructor(vhsHandler, playlist, id) {
  44725. const {
  44726. playlistController_: pc
  44727. } = vhsHandler;
  44728. const qualityChangeFunction = pc.fastQualityChange_.bind(pc); // some playlist attributes are optional
  44729. if (playlist.attributes) {
  44730. const resolution = playlist.attributes.RESOLUTION;
  44731. this.width = resolution && resolution.width;
  44732. this.height = resolution && resolution.height;
  44733. this.bandwidth = playlist.attributes.BANDWIDTH;
  44734. this.frameRate = playlist.attributes['FRAME-RATE'];
  44735. }
  44736. this.codecs = codecsForPlaylist(pc.main(), playlist);
  44737. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  44738. // within the main playlist
  44739. this.id = id; // Partially-apply the enableFunction to create a playlist-
  44740. // specific variant
  44741. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  44742. }
  44743. }
  44744. /**
  44745. * A mixin function that adds the `representations` api to an instance
  44746. * of the VhsHandler class
  44747. *
  44748. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  44749. * representation API into
  44750. */
  44751. const renditionSelectionMixin = function (vhsHandler) {
  44752. // Add a single API-specific function to the VhsHandler instance
  44753. vhsHandler.representations = () => {
  44754. const main = vhsHandler.playlistController_.main();
  44755. const playlists = isAudioOnly(main) ? vhsHandler.playlistController_.getAudioTrackPlaylists_() : main.playlists;
  44756. if (!playlists) {
  44757. return [];
  44758. }
  44759. return playlists.filter(media => !isIncompatible(media)).map((e, i) => new Representation(vhsHandler, e, e.id));
  44760. };
  44761. };
  44762. /**
  44763. * @file playback-watcher.js
  44764. *
  44765. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  44766. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  44767. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  44768. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  44769. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  44770. */
  44771. const timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  44772. /**
  44773. * @class PlaybackWatcher
  44774. */
  44775. class PlaybackWatcher {
  44776. /**
  44777. * Represents an PlaybackWatcher object.
  44778. *
  44779. * @class
  44780. * @param {Object} options an object that includes the tech and settings
  44781. */
  44782. constructor(options) {
  44783. this.playlistController_ = options.playlistController;
  44784. this.tech_ = options.tech;
  44785. this.seekable = options.seekable;
  44786. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  44787. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  44788. this.media = options.media;
  44789. this.consecutiveUpdates = 0;
  44790. this.lastRecordedTime = null;
  44791. this.checkCurrentTimeTimeout_ = null;
  44792. this.logger_ = logger('PlaybackWatcher');
  44793. this.logger_('initialize');
  44794. const playHandler = () => this.monitorCurrentTime_();
  44795. const canPlayHandler = () => this.monitorCurrentTime_();
  44796. const waitingHandler = () => this.techWaiting_();
  44797. const cancelTimerHandler = () => this.resetTimeUpdate_();
  44798. const pc = this.playlistController_;
  44799. const loaderTypes = ['main', 'subtitle', 'audio'];
  44800. const loaderChecks = {};
  44801. loaderTypes.forEach(type => {
  44802. loaderChecks[type] = {
  44803. reset: () => this.resetSegmentDownloads_(type),
  44804. updateend: () => this.checkSegmentDownloads_(type)
  44805. };
  44806. pc[`${type}SegmentLoader_`].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  44807. // isn't changing we want to reset. We cannot assume that the new rendition
  44808. // will also be stalled, until after new appends.
  44809. pc[`${type}SegmentLoader_`].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  44810. // This prevents one segment playlists (single vtt or single segment content)
  44811. // from being detected as stalling. As the buffer will not change in those cases, since
  44812. // the buffer is the entire video duration.
  44813. this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  44814. });
  44815. /**
  44816. * We check if a seek was into a gap through the following steps:
  44817. * 1. We get a seeking event and we do not get a seeked event. This means that
  44818. * a seek was attempted but not completed.
  44819. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  44820. * removed everything from our buffer and appended a segment, and should be ready
  44821. * to check for gaps.
  44822. */
  44823. const setSeekingHandlers = fn => {
  44824. ['main', 'audio'].forEach(type => {
  44825. pc[`${type}SegmentLoader_`][fn]('appended', this.seekingAppendCheck_);
  44826. });
  44827. };
  44828. this.seekingAppendCheck_ = () => {
  44829. if (this.fixesBadSeeks_()) {
  44830. this.consecutiveUpdates = 0;
  44831. this.lastRecordedTime = this.tech_.currentTime();
  44832. setSeekingHandlers('off');
  44833. }
  44834. };
  44835. this.clearSeekingAppendCheck_ = () => setSeekingHandlers('off');
  44836. this.watchForBadSeeking_ = () => {
  44837. this.clearSeekingAppendCheck_();
  44838. setSeekingHandlers('on');
  44839. };
  44840. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  44841. this.tech_.on('seeking', this.watchForBadSeeking_);
  44842. this.tech_.on('waiting', waitingHandler);
  44843. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  44844. this.tech_.on('canplay', canPlayHandler);
  44845. /*
  44846. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  44847. is surfaced in one of two ways:
  44848. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  44849. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  44850. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  44851. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  44852. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  44853. even if the player is in a playing state
  44854. */
  44855. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  44856. this.dispose = () => {
  44857. this.clearSeekingAppendCheck_();
  44858. this.logger_('dispose');
  44859. this.tech_.off('waiting', waitingHandler);
  44860. this.tech_.off(timerCancelEvents, cancelTimerHandler);
  44861. this.tech_.off('canplay', canPlayHandler);
  44862. this.tech_.off('play', playHandler);
  44863. this.tech_.off('seeking', this.watchForBadSeeking_);
  44864. this.tech_.off('seeked', this.clearSeekingAppendCheck_);
  44865. loaderTypes.forEach(type => {
  44866. pc[`${type}SegmentLoader_`].off('appendsdone', loaderChecks[type].updateend);
  44867. pc[`${type}SegmentLoader_`].off('playlistupdate', loaderChecks[type].reset);
  44868. this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  44869. });
  44870. if (this.checkCurrentTimeTimeout_) {
  44871. window$1.clearTimeout(this.checkCurrentTimeTimeout_);
  44872. }
  44873. this.resetTimeUpdate_();
  44874. };
  44875. }
  44876. /**
  44877. * Periodically check current time to see if playback stopped
  44878. *
  44879. * @private
  44880. */
  44881. monitorCurrentTime_() {
  44882. this.checkCurrentTime_();
  44883. if (this.checkCurrentTimeTimeout_) {
  44884. window$1.clearTimeout(this.checkCurrentTimeTimeout_);
  44885. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  44886. this.checkCurrentTimeTimeout_ = window$1.setTimeout(this.monitorCurrentTime_.bind(this), 250);
  44887. }
  44888. /**
  44889. * Reset stalled download stats for a specific type of loader
  44890. *
  44891. * @param {string} type
  44892. * The segment loader type to check.
  44893. *
  44894. * @listens SegmentLoader#playlistupdate
  44895. * @listens Tech#seeking
  44896. * @listens Tech#seeked
  44897. */
  44898. resetSegmentDownloads_(type) {
  44899. const loader = this.playlistController_[`${type}SegmentLoader_`];
  44900. if (this[`${type}StalledDownloads_`] > 0) {
  44901. this.logger_(`resetting possible stalled download count for ${type} loader`);
  44902. }
  44903. this[`${type}StalledDownloads_`] = 0;
  44904. this[`${type}Buffered_`] = loader.buffered_();
  44905. }
  44906. /**
  44907. * Checks on every segment `appendsdone` to see
  44908. * if segment appends are making progress. If they are not
  44909. * and we are still downloading bytes. We exclude the playlist.
  44910. *
  44911. * @param {string} type
  44912. * The segment loader type to check.
  44913. *
  44914. * @listens SegmentLoader#appendsdone
  44915. */
  44916. checkSegmentDownloads_(type) {
  44917. const pc = this.playlistController_;
  44918. const loader = pc[`${type}SegmentLoader_`];
  44919. const buffered = loader.buffered_();
  44920. const isBufferedDifferent = isRangeDifferent(this[`${type}Buffered_`], buffered);
  44921. this[`${type}Buffered_`] = buffered; // if another watcher is going to fix the issue or
  44922. // the buffered value for this loader changed
  44923. // appends are working
  44924. if (isBufferedDifferent) {
  44925. this.resetSegmentDownloads_(type);
  44926. return;
  44927. }
  44928. this[`${type}StalledDownloads_`]++;
  44929. this.logger_(`found #${this[`${type}StalledDownloads_`]} ${type} appends that did not increase buffer (possible stalled download)`, {
  44930. playlistId: loader.playlist_ && loader.playlist_.id,
  44931. buffered: timeRangesToArray(buffered)
  44932. }); // after 10 possibly stalled appends with no reset, exclude
  44933. if (this[`${type}StalledDownloads_`] < 10) {
  44934. return;
  44935. }
  44936. this.logger_(`${type} loader stalled download exclusion`);
  44937. this.resetSegmentDownloads_(type);
  44938. this.tech_.trigger({
  44939. type: 'usage',
  44940. name: `vhs-${type}-download-exclusion`
  44941. });
  44942. if (type === 'subtitle') {
  44943. return;
  44944. } // TODO: should we exclude audio tracks rather than main tracks
  44945. // when type is audio?
  44946. pc.excludePlaylist({
  44947. error: {
  44948. message: `Excessive ${type} segment downloading detected.`
  44949. },
  44950. playlistExclusionDuration: Infinity
  44951. });
  44952. }
  44953. /**
  44954. * The purpose of this function is to emulate the "waiting" event on
  44955. * browsers that do not emit it when they are waiting for more
  44956. * data to continue playback
  44957. *
  44958. * @private
  44959. */
  44960. checkCurrentTime_() {
  44961. if (this.tech_.paused() || this.tech_.seeking()) {
  44962. return;
  44963. }
  44964. const currentTime = this.tech_.currentTime();
  44965. const buffered = this.tech_.buffered();
  44966. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  44967. // If current time is at the end of the final buffered region, then any playback
  44968. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  44969. // should fire a `waiting` event in this scenario, but due to browser and tech
  44970. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  44971. // responding to a native `waiting` event when the tech fails to emit one.
  44972. return this.techWaiting_();
  44973. }
  44974. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  44975. this.consecutiveUpdates++;
  44976. this.waiting_();
  44977. } else if (currentTime === this.lastRecordedTime) {
  44978. this.consecutiveUpdates++;
  44979. } else {
  44980. this.consecutiveUpdates = 0;
  44981. this.lastRecordedTime = currentTime;
  44982. }
  44983. }
  44984. /**
  44985. * Resets the 'timeupdate' mechanism designed to detect that we are stalled
  44986. *
  44987. * @private
  44988. */
  44989. resetTimeUpdate_() {
  44990. this.consecutiveUpdates = 0;
  44991. }
  44992. /**
  44993. * Fixes situations where there's a bad seek
  44994. *
  44995. * @return {boolean} whether an action was taken to fix the seek
  44996. * @private
  44997. */
  44998. fixesBadSeeks_() {
  44999. const seeking = this.tech_.seeking();
  45000. if (!seeking) {
  45001. return false;
  45002. } // TODO: It's possible that these seekable checks should be moved out of this function
  45003. // and into a function that runs on seekablechange. It's also possible that we only need
  45004. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  45005. // seekable range.
  45006. const seekable = this.seekable();
  45007. const currentTime = this.tech_.currentTime();
  45008. const isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  45009. let seekTo;
  45010. if (isAfterSeekableRange) {
  45011. const seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  45012. seekTo = seekableEnd;
  45013. }
  45014. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  45015. const seekableStart = seekable.start(0); // sync to the beginning of the live window
  45016. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  45017. seekTo = seekableStart + (
  45018. // if the playlist is too short and the seekable range is an exact time (can
  45019. // happen in live with a 3 segment playlist), then don't use a time delta
  45020. seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
  45021. }
  45022. if (typeof seekTo !== 'undefined') {
  45023. this.logger_(`Trying to seek outside of seekable at time ${currentTime} with ` + `seekable range ${printableRange(seekable)}. Seeking to ` + `${seekTo}.`);
  45024. this.tech_.setCurrentTime(seekTo);
  45025. return true;
  45026. }
  45027. const sourceUpdater = this.playlistController_.sourceUpdater_;
  45028. const buffered = this.tech_.buffered();
  45029. const audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  45030. const videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  45031. const media = this.media(); // verify that at least two segment durations or one part duration have been
  45032. // appended before checking for a gap.
  45033. const minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been
  45034. // appended before checking for a gap.
  45035. const bufferedToCheck = [audioBuffered, videoBuffered];
  45036. for (let i = 0; i < bufferedToCheck.length; i++) {
  45037. // skip null buffered
  45038. if (!bufferedToCheck[i]) {
  45039. continue;
  45040. }
  45041. const timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part
  45042. // duration behind we haven't appended enough to call this a bad seek.
  45043. if (timeAhead < minAppendedDuration) {
  45044. return false;
  45045. }
  45046. }
  45047. const nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered
  45048. // to seek over the gap
  45049. if (nextRange.length === 0) {
  45050. return false;
  45051. }
  45052. seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
  45053. this.logger_(`Buffered region starts (${nextRange.start(0)}) ` + ` just beyond seek point (${currentTime}). Seeking to ${seekTo}.`);
  45054. this.tech_.setCurrentTime(seekTo);
  45055. return true;
  45056. }
  45057. /**
  45058. * Handler for situations when we determine the player is waiting.
  45059. *
  45060. * @private
  45061. */
  45062. waiting_() {
  45063. if (this.techWaiting_()) {
  45064. return;
  45065. } // All tech waiting checks failed. Use last resort correction
  45066. const currentTime = this.tech_.currentTime();
  45067. const buffered = this.tech_.buffered();
  45068. const currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  45069. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  45070. // currentTime is usually enough to kickstart the player. This checks that the player
  45071. // is currently within a buffered region before attempting a corrective seek.
  45072. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  45073. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  45074. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  45075. // to avoid triggering an `unknownwaiting` event when the network is slow.
  45076. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  45077. this.resetTimeUpdate_();
  45078. this.tech_.setCurrentTime(currentTime);
  45079. 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
  45080. this.tech_.trigger({
  45081. type: 'usage',
  45082. name: 'vhs-unknown-waiting'
  45083. });
  45084. return;
  45085. }
  45086. }
  45087. /**
  45088. * Handler for situations when the tech fires a `waiting` event
  45089. *
  45090. * @return {boolean}
  45091. * True if an action (or none) was needed to correct the waiting. False if no
  45092. * checks passed
  45093. * @private
  45094. */
  45095. techWaiting_() {
  45096. const seekable = this.seekable();
  45097. const currentTime = this.tech_.currentTime();
  45098. if (this.tech_.seeking()) {
  45099. // Tech is seeking or already waiting on another action, no action needed
  45100. return true;
  45101. }
  45102. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  45103. const livePoint = seekable.end(seekable.length - 1);
  45104. this.logger_(`Fell out of live window at time ${currentTime}. Seeking to ` + `live point (seekable end) ${livePoint}`);
  45105. this.resetTimeUpdate_();
  45106. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  45107. this.tech_.trigger({
  45108. type: 'usage',
  45109. name: 'vhs-live-resync'
  45110. });
  45111. return true;
  45112. }
  45113. const sourceUpdater = this.tech_.vhs.playlistController_.sourceUpdater_;
  45114. const buffered = this.tech_.buffered();
  45115. const videoUnderflow = this.videoUnderflow_({
  45116. audioBuffered: sourceUpdater.audioBuffered(),
  45117. videoBuffered: sourceUpdater.videoBuffered(),
  45118. currentTime
  45119. });
  45120. if (videoUnderflow) {
  45121. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  45122. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  45123. // allows the video to catch up to the audio position without losing any audio
  45124. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  45125. this.resetTimeUpdate_();
  45126. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  45127. this.tech_.trigger({
  45128. type: 'usage',
  45129. name: 'vhs-video-underflow'
  45130. });
  45131. return true;
  45132. }
  45133. const nextRange = findNextRange(buffered, currentTime); // check for gap
  45134. if (nextRange.length > 0) {
  45135. this.logger_(`Stopped at ${currentTime} and seeking to ${nextRange.start(0)}`);
  45136. this.resetTimeUpdate_();
  45137. this.skipTheGap_(currentTime);
  45138. return true;
  45139. } // All checks failed. Returning false to indicate failure to correct waiting
  45140. return false;
  45141. }
  45142. afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow = false) {
  45143. if (!seekable.length) {
  45144. // we can't make a solid case if there's no seekable, default to false
  45145. return false;
  45146. }
  45147. let allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  45148. const isLive = !playlist.endList;
  45149. if (isLive && allowSeeksWithinUnsafeLiveWindow) {
  45150. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  45151. }
  45152. if (currentTime > allowedEnd) {
  45153. return true;
  45154. }
  45155. return false;
  45156. }
  45157. beforeSeekableWindow_(seekable, currentTime) {
  45158. if (seekable.length &&
  45159. // can't fall before 0 and 0 seekable start identifies VOD stream
  45160. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  45161. return true;
  45162. }
  45163. return false;
  45164. }
  45165. videoUnderflow_({
  45166. videoBuffered,
  45167. audioBuffered,
  45168. currentTime
  45169. }) {
  45170. // audio only content will not have video underflow :)
  45171. if (!videoBuffered) {
  45172. return;
  45173. }
  45174. let gap; // find a gap in demuxed content.
  45175. if (videoBuffered.length && audioBuffered.length) {
  45176. // in Chrome audio will continue to play for ~3s when we run out of video
  45177. // so we have to check that the video buffer did have some buffer in the
  45178. // past.
  45179. const lastVideoRange = findRange(videoBuffered, currentTime - 3);
  45180. const videoRange = findRange(videoBuffered, currentTime);
  45181. const audioRange = findRange(audioBuffered, currentTime);
  45182. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  45183. gap = {
  45184. start: lastVideoRange.end(0),
  45185. end: audioRange.end(0)
  45186. };
  45187. } // find a gap in muxed content.
  45188. } else {
  45189. const nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  45190. // stuck in a gap due to video underflow.
  45191. if (!nextRange.length) {
  45192. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  45193. }
  45194. }
  45195. if (gap) {
  45196. this.logger_(`Encountered a gap in video from ${gap.start} to ${gap.end}. ` + `Seeking to current time ${currentTime}`);
  45197. return true;
  45198. }
  45199. return false;
  45200. }
  45201. /**
  45202. * Timer callback. If playback still has not proceeded, then we seek
  45203. * to the start of the next buffered region.
  45204. *
  45205. * @private
  45206. */
  45207. skipTheGap_(scheduledCurrentTime) {
  45208. const buffered = this.tech_.buffered();
  45209. const currentTime = this.tech_.currentTime();
  45210. const nextRange = findNextRange(buffered, currentTime);
  45211. this.resetTimeUpdate_();
  45212. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  45213. return;
  45214. }
  45215. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  45216. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  45217. this.tech_.trigger({
  45218. type: 'usage',
  45219. name: 'vhs-gap-skip'
  45220. });
  45221. }
  45222. gapFromVideoUnderflow_(buffered, currentTime) {
  45223. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  45224. // playing for ~3 seconds after the video gap starts. This is done to account for
  45225. // video buffer underflow/underrun (note that this is not done when there is audio
  45226. // buffer underflow/underrun -- in that case the video will stop as soon as it
  45227. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  45228. // video stalls). The player's time will reflect the playthrough of audio, so the
  45229. // time will appear as if we are in a buffered region, even if we are stuck in a
  45230. // "gap."
  45231. //
  45232. // Example:
  45233. // video buffer: 0 => 10.1, 10.2 => 20
  45234. // audio buffer: 0 => 20
  45235. // overall buffer: 0 => 10.1, 10.2 => 20
  45236. // current time: 13
  45237. //
  45238. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  45239. // however, the audio continued playing until it reached ~3 seconds past the gap
  45240. // (13 seconds), at which point it stops as well. Since current time is past the
  45241. // gap, findNextRange will return no ranges.
  45242. //
  45243. // To check for this issue, we see if there is a gap that starts somewhere within
  45244. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  45245. const gaps = findGaps(buffered);
  45246. for (let i = 0; i < gaps.length; i++) {
  45247. const start = gaps.start(i);
  45248. const end = gaps.end(i); // gap is starts no more than 4 seconds back
  45249. if (currentTime - start < 4 && currentTime - start > 2) {
  45250. return {
  45251. start,
  45252. end
  45253. };
  45254. }
  45255. }
  45256. return null;
  45257. }
  45258. }
  45259. const defaultOptions = {
  45260. errorInterval: 30,
  45261. getSource(next) {
  45262. const tech = this.tech({
  45263. IWillNotUseThisInPlugins: true
  45264. });
  45265. const sourceObj = tech.currentSource_ || this.currentSource();
  45266. return next(sourceObj);
  45267. }
  45268. };
  45269. /**
  45270. * Main entry point for the plugin
  45271. *
  45272. * @param {Player} player a reference to a videojs Player instance
  45273. * @param {Object} [options] an object with plugin options
  45274. * @private
  45275. */
  45276. const initPlugin = function (player, options) {
  45277. let lastCalled = 0;
  45278. let seekTo = 0;
  45279. const localOptions = merge(defaultOptions, options);
  45280. player.ready(() => {
  45281. player.trigger({
  45282. type: 'usage',
  45283. name: 'vhs-error-reload-initialized'
  45284. });
  45285. });
  45286. /**
  45287. * Player modifications to perform that must wait until `loadedmetadata`
  45288. * has been triggered
  45289. *
  45290. * @private
  45291. */
  45292. const loadedMetadataHandler = function () {
  45293. if (seekTo) {
  45294. player.currentTime(seekTo);
  45295. }
  45296. };
  45297. /**
  45298. * Set the source on the player element, play, and seek if necessary
  45299. *
  45300. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  45301. * @private
  45302. */
  45303. const setSource = function (sourceObj) {
  45304. if (sourceObj === null || sourceObj === undefined) {
  45305. return;
  45306. }
  45307. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  45308. player.one('loadedmetadata', loadedMetadataHandler);
  45309. player.src(sourceObj);
  45310. player.trigger({
  45311. type: 'usage',
  45312. name: 'vhs-error-reload'
  45313. });
  45314. player.play();
  45315. };
  45316. /**
  45317. * Attempt to get a source from either the built-in getSource function
  45318. * or a custom function provided via the options
  45319. *
  45320. * @private
  45321. */
  45322. const errorHandler = function () {
  45323. // Do not attempt to reload the source if a source-reload occurred before
  45324. // 'errorInterval' time has elapsed since the last source-reload
  45325. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  45326. player.trigger({
  45327. type: 'usage',
  45328. name: 'vhs-error-reload-canceled'
  45329. });
  45330. return;
  45331. }
  45332. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  45333. videojs.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  45334. return;
  45335. }
  45336. lastCalled = Date.now();
  45337. return localOptions.getSource.call(player, setSource);
  45338. };
  45339. /**
  45340. * Unbind any event handlers that were bound by the plugin
  45341. *
  45342. * @private
  45343. */
  45344. const cleanupEvents = function () {
  45345. player.off('loadedmetadata', loadedMetadataHandler);
  45346. player.off('error', errorHandler);
  45347. player.off('dispose', cleanupEvents);
  45348. };
  45349. /**
  45350. * Cleanup before re-initializing the plugin
  45351. *
  45352. * @param {Object} [newOptions] an object with plugin options
  45353. * @private
  45354. */
  45355. const reinitPlugin = function (newOptions) {
  45356. cleanupEvents();
  45357. initPlugin(player, newOptions);
  45358. };
  45359. player.on('error', errorHandler);
  45360. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  45361. // initializing the plugin
  45362. player.reloadSourceOnError = reinitPlugin;
  45363. };
  45364. /**
  45365. * Reload the source when an error is detected as long as there
  45366. * wasn't an error previously within the last 30 seconds
  45367. *
  45368. * @param {Object} [options] an object with plugin options
  45369. */
  45370. const reloadSourceOnError = function (options) {
  45371. initPlugin(this, options);
  45372. };
  45373. var version$4 = "3.0.2";
  45374. var version$3 = "6.3.0";
  45375. var version$2 = "1.0.1";
  45376. var version$1 = "6.0.0";
  45377. var version = "4.0.1";
  45378. /**
  45379. * @file videojs-http-streaming.js
  45380. *
  45381. * The main file for the VHS project.
  45382. * License: https://github.com/videojs/videojs-http-streaming/blob/main/LICENSE
  45383. */
  45384. const Vhs = {
  45385. PlaylistLoader,
  45386. Playlist,
  45387. utils,
  45388. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  45389. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  45390. lastBandwidthSelector,
  45391. movingAverageBandwidthSelector,
  45392. comparePlaylistBandwidth,
  45393. comparePlaylistResolution,
  45394. xhr: xhrFactory()
  45395. }; // Define getter/setters for config properties
  45396. Object.keys(Config).forEach(prop => {
  45397. Object.defineProperty(Vhs, prop, {
  45398. get() {
  45399. videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  45400. return Config[prop];
  45401. },
  45402. set(value) {
  45403. videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  45404. if (typeof value !== 'number' || value < 0) {
  45405. videojs.log.warn(`value of Vhs.${prop} must be greater than or equal to 0`);
  45406. return;
  45407. }
  45408. Config[prop] = value;
  45409. }
  45410. });
  45411. });
  45412. const LOCAL_STORAGE_KEY = 'videojs-vhs';
  45413. /**
  45414. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  45415. *
  45416. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  45417. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  45418. * @function handleVhsMediaChange
  45419. */
  45420. const handleVhsMediaChange = function (qualityLevels, playlistLoader) {
  45421. const newPlaylist = playlistLoader.media();
  45422. let selectedIndex = -1;
  45423. for (let i = 0; i < qualityLevels.length; i++) {
  45424. if (qualityLevels[i].id === newPlaylist.id) {
  45425. selectedIndex = i;
  45426. break;
  45427. }
  45428. }
  45429. qualityLevels.selectedIndex_ = selectedIndex;
  45430. qualityLevels.trigger({
  45431. selectedIndex,
  45432. type: 'change'
  45433. });
  45434. };
  45435. /**
  45436. * Adds quality levels to list once playlist metadata is available
  45437. *
  45438. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  45439. * @param {Object} vhs Vhs object to listen to for media events.
  45440. * @function handleVhsLoadedMetadata
  45441. */
  45442. const handleVhsLoadedMetadata = function (qualityLevels, vhs) {
  45443. vhs.representations().forEach(rep => {
  45444. qualityLevels.addQualityLevel(rep);
  45445. });
  45446. handleVhsMediaChange(qualityLevels, vhs.playlists);
  45447. }; // VHS is a source handler, not a tech. Make sure attempts to use it
  45448. // as one do not cause exceptions.
  45449. Vhs.canPlaySource = function () {
  45450. return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  45451. };
  45452. const emeKeySystems = (keySystemOptions, mainPlaylist, audioPlaylist) => {
  45453. if (!keySystemOptions) {
  45454. return keySystemOptions;
  45455. }
  45456. let codecs = {};
  45457. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  45458. codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
  45459. }
  45460. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  45461. codecs.audio = audioPlaylist.attributes.CODECS;
  45462. }
  45463. const videoContentType = getMimeForCodec(codecs.video);
  45464. const audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  45465. const keySystemContentTypes = {};
  45466. for (const keySystem in keySystemOptions) {
  45467. keySystemContentTypes[keySystem] = {};
  45468. if (audioContentType) {
  45469. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  45470. }
  45471. if (videoContentType) {
  45472. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  45473. } // Default to using the video playlist's PSSH even though they may be different, as
  45474. // videojs-contrib-eme will only accept one in the options.
  45475. //
  45476. // This shouldn't be an issue for most cases as early intialization will handle all
  45477. // unique PSSH values, and if they aren't, then encrypted events should have the
  45478. // specific information needed for the unique license.
  45479. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  45480. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  45481. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  45482. // so we need to prevent overwriting the URL entirely
  45483. if (typeof keySystemOptions[keySystem] === 'string') {
  45484. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  45485. }
  45486. }
  45487. return merge(keySystemOptions, keySystemContentTypes);
  45488. };
  45489. /**
  45490. * @typedef {Object} KeySystems
  45491. *
  45492. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  45493. * Note: not all options are listed here.
  45494. *
  45495. * @property {Uint8Array} [pssh]
  45496. * Protection System Specific Header
  45497. */
  45498. /**
  45499. * Goes through all the playlists and collects an array of KeySystems options objects
  45500. * containing each playlist's keySystems and their pssh values, if available.
  45501. *
  45502. * @param {Object[]} playlists
  45503. * The playlists to look through
  45504. * @param {string[]} keySystems
  45505. * The keySystems to collect pssh values for
  45506. *
  45507. * @return {KeySystems[]}
  45508. * An array of KeySystems objects containing available key systems and their
  45509. * pssh values
  45510. */
  45511. const getAllPsshKeySystemsOptions = (playlists, keySystems) => {
  45512. return playlists.reduce((keySystemsArr, playlist) => {
  45513. if (!playlist.contentProtection) {
  45514. return keySystemsArr;
  45515. }
  45516. const keySystemsOptions = keySystems.reduce((keySystemsObj, keySystem) => {
  45517. const keySystemOptions = playlist.contentProtection[keySystem];
  45518. if (keySystemOptions && keySystemOptions.pssh) {
  45519. keySystemsObj[keySystem] = {
  45520. pssh: keySystemOptions.pssh
  45521. };
  45522. }
  45523. return keySystemsObj;
  45524. }, {});
  45525. if (Object.keys(keySystemsOptions).length) {
  45526. keySystemsArr.push(keySystemsOptions);
  45527. }
  45528. return keySystemsArr;
  45529. }, []);
  45530. };
  45531. /**
  45532. * Returns a promise that waits for the
  45533. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  45534. *
  45535. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  45536. * browsers.
  45537. *
  45538. * As per the above ticket, this is particularly important for Chrome, where, if
  45539. * unencrypted content is appended before encrypted content and the key session has not
  45540. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  45541. * during playback.
  45542. *
  45543. * @param {Object} player
  45544. * The player instance
  45545. * @param {Object[]} sourceKeySystems
  45546. * The key systems options from the player source
  45547. * @param {Object} [audioMedia]
  45548. * The active audio media playlist (optional)
  45549. * @param {Object[]} mainPlaylists
  45550. * The playlists found on the main playlist object
  45551. *
  45552. * @return {Object}
  45553. * Promise that resolves when the key session has been created
  45554. */
  45555. const waitForKeySessionCreation = ({
  45556. player,
  45557. sourceKeySystems,
  45558. audioMedia,
  45559. mainPlaylists
  45560. }) => {
  45561. if (!player.eme.initializeMediaKeys) {
  45562. return Promise.resolve();
  45563. } // TODO should all audio PSSH values be initialized for DRM?
  45564. //
  45565. // All unique video rendition pssh values are initialized for DRM, but here only
  45566. // the initial audio playlist license is initialized. In theory, an encrypted
  45567. // event should be fired if the user switches to an alternative audio playlist
  45568. // where a license is required, but this case hasn't yet been tested. In addition, there
  45569. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  45570. // languages).
  45571. const playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  45572. const keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  45573. const initializationFinishedPromises = [];
  45574. const keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  45575. // only place where it should not be deduped is for ms-prefixed APIs, but the early
  45576. // return for IE11 above, and the existence of modern EME APIs in addition to
  45577. // ms-prefixed APIs on Edge should prevent this from being a concern.
  45578. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  45579. keySystemsOptionsArr.forEach(keySystemsOptions => {
  45580. keySessionCreatedPromises.push(new Promise((resolve, reject) => {
  45581. player.tech_.one('keysessioncreated', resolve);
  45582. }));
  45583. initializationFinishedPromises.push(new Promise((resolve, reject) => {
  45584. player.eme.initializeMediaKeys({
  45585. keySystems: keySystemsOptions
  45586. }, err => {
  45587. if (err) {
  45588. reject(err);
  45589. return;
  45590. }
  45591. resolve();
  45592. });
  45593. }));
  45594. }); // The reasons Promise.race is chosen over Promise.any:
  45595. //
  45596. // * Promise.any is only available in Safari 14+.
  45597. // * None of these promises are expected to reject. If they do reject, it might be
  45598. // better here for the race to surface the rejection, rather than mask it by using
  45599. // Promise.any.
  45600. return Promise.race([
  45601. // If a session was previously created, these will all finish resolving without
  45602. // creating a new session, otherwise it will take until the end of all license
  45603. // requests, which is why the key session check is used (to make setup much faster).
  45604. Promise.all(initializationFinishedPromises),
  45605. // Once a single session is created, the browser knows DRM will be used.
  45606. Promise.race(keySessionCreatedPromises)]);
  45607. };
  45608. /**
  45609. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  45610. * there are keySystems on the source, sets up source options to prepare the source for
  45611. * eme.
  45612. *
  45613. * @param {Object} player
  45614. * The player instance
  45615. * @param {Object[]} sourceKeySystems
  45616. * The key systems options from the player source
  45617. * @param {Object} media
  45618. * The active media playlist
  45619. * @param {Object} [audioMedia]
  45620. * The active audio media playlist (optional)
  45621. *
  45622. * @return {boolean}
  45623. * Whether or not options were configured and EME is available
  45624. */
  45625. const setupEmeOptions = ({
  45626. player,
  45627. sourceKeySystems,
  45628. media,
  45629. audioMedia
  45630. }) => {
  45631. const sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  45632. if (!sourceOptions) {
  45633. return false;
  45634. }
  45635. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  45636. // do nothing.
  45637. if (sourceOptions && !player.eme) {
  45638. videojs.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  45639. return false;
  45640. }
  45641. return true;
  45642. };
  45643. const getVhsLocalStorage = () => {
  45644. if (!window$1.localStorage) {
  45645. return null;
  45646. }
  45647. const storedObject = window$1.localStorage.getItem(LOCAL_STORAGE_KEY);
  45648. if (!storedObject) {
  45649. return null;
  45650. }
  45651. try {
  45652. return JSON.parse(storedObject);
  45653. } catch (e) {
  45654. // someone may have tampered with the value
  45655. return null;
  45656. }
  45657. };
  45658. const updateVhsLocalStorage = options => {
  45659. if (!window$1.localStorage) {
  45660. return false;
  45661. }
  45662. let objectToStore = getVhsLocalStorage();
  45663. objectToStore = objectToStore ? merge(objectToStore, options) : options;
  45664. try {
  45665. window$1.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  45666. } catch (e) {
  45667. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  45668. // storage is set to 0).
  45669. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  45670. // No need to perform any operation.
  45671. return false;
  45672. }
  45673. return objectToStore;
  45674. };
  45675. /**
  45676. * Parses VHS-supported media types from data URIs. See
  45677. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  45678. * for information on data URIs.
  45679. *
  45680. * @param {string} dataUri
  45681. * The data URI
  45682. *
  45683. * @return {string|Object}
  45684. * The parsed object/string, or the original string if no supported media type
  45685. * was found
  45686. */
  45687. const expandDataUri = dataUri => {
  45688. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  45689. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  45690. } // no known case for this data URI, return the string as-is
  45691. return dataUri;
  45692. };
  45693. /**
  45694. * Whether the browser has built-in HLS support.
  45695. */
  45696. Vhs.supportsNativeHls = function () {
  45697. if (!document || !document.createElement) {
  45698. return false;
  45699. }
  45700. const video = document.createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  45701. if (!videojs.getTech('Html5').isSupported()) {
  45702. return false;
  45703. } // HLS manifests can go by many mime-types
  45704. const canPlay = [
  45705. // Apple santioned
  45706. 'application/vnd.apple.mpegurl',
  45707. // Apple sanctioned for backwards compatibility
  45708. 'audio/mpegurl',
  45709. // Very common
  45710. 'audio/x-mpegurl',
  45711. // Very common
  45712. 'application/x-mpegurl',
  45713. // Included for completeness
  45714. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  45715. return canPlay.some(function (canItPlay) {
  45716. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  45717. });
  45718. }();
  45719. Vhs.supportsNativeDash = function () {
  45720. if (!document || !document.createElement || !videojs.getTech('Html5').isSupported()) {
  45721. return false;
  45722. }
  45723. return /maybe|probably/i.test(document.createElement('video').canPlayType('application/dash+xml'));
  45724. }();
  45725. Vhs.supportsTypeNatively = type => {
  45726. if (type === 'hls') {
  45727. return Vhs.supportsNativeHls;
  45728. }
  45729. if (type === 'dash') {
  45730. return Vhs.supportsNativeDash;
  45731. }
  45732. return false;
  45733. };
  45734. /**
  45735. * VHS is a source handler, not a tech. Make sure attempts to use it
  45736. * as one do not cause exceptions.
  45737. */
  45738. Vhs.isSupported = function () {
  45739. return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  45740. };
  45741. const Component = videojs.getComponent('Component');
  45742. /**
  45743. * The Vhs Handler object, where we orchestrate all of the parts
  45744. * of VHS to interact with video.js
  45745. *
  45746. * @class VhsHandler
  45747. * @extends videojs.Component
  45748. * @param {Object} source the soruce object
  45749. * @param {Tech} tech the parent tech object
  45750. * @param {Object} options optional and required options
  45751. */
  45752. class VhsHandler extends Component {
  45753. constructor(source, tech, options) {
  45754. super(tech, options.vhs); // if a tech level `initialBandwidth` option was passed
  45755. // use that over the VHS level `bandwidth` option
  45756. if (typeof options.initialBandwidth === 'number') {
  45757. this.options_.bandwidth = options.initialBandwidth;
  45758. }
  45759. this.logger_ = logger('VhsHandler'); // we need access to the player in some cases,
  45760. // so, get it from Video.js via the `playerId`
  45761. if (tech.options_ && tech.options_.playerId) {
  45762. const _player = videojs.getPlayer(tech.options_.playerId);
  45763. this.player_ = _player;
  45764. }
  45765. this.tech_ = tech;
  45766. this.source_ = source;
  45767. this.stats = {};
  45768. this.ignoreNextSeekingEvent_ = false;
  45769. this.setOptions_();
  45770. if (this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  45771. tech.overrideNativeAudioTracks(true);
  45772. tech.overrideNativeVideoTracks(true);
  45773. } else if (this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  45774. // overriding native VHS only works if audio tracks have been emulated
  45775. // error early if we're misconfigured
  45776. throw new Error('Overriding native VHS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  45777. } // listen for fullscreenchange events for this player so that we
  45778. // can adjust our quality selection quickly
  45779. this.on(document, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], event => {
  45780. const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  45781. if (fullscreenElement && fullscreenElement.contains(this.tech_.el())) {
  45782. this.playlistController_.fastQualityChange_();
  45783. } else {
  45784. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  45785. // than full screen, see if there should be a rendition switch down to preserve
  45786. // bandwidth.
  45787. this.playlistController_.checkABR_();
  45788. }
  45789. });
  45790. this.on(this.tech_, 'seeking', function () {
  45791. if (this.ignoreNextSeekingEvent_) {
  45792. this.ignoreNextSeekingEvent_ = false;
  45793. return;
  45794. }
  45795. this.setCurrentTime(this.tech_.currentTime());
  45796. });
  45797. this.on(this.tech_, 'error', function () {
  45798. // verify that the error was real and we are loaded
  45799. // enough to have pc loaded.
  45800. if (this.tech_.error() && this.playlistController_) {
  45801. this.playlistController_.pauseLoading();
  45802. }
  45803. });
  45804. this.on(this.tech_, 'play', this.play);
  45805. }
  45806. setOptions_() {
  45807. // defaults
  45808. this.options_.withCredentials = this.options_.withCredentials || false;
  45809. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  45810. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  45811. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  45812. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  45813. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  45814. this.options_.customTagParsers = this.options_.customTagParsers || [];
  45815. this.options_.customTagMappers = this.options_.customTagMappers || [];
  45816. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  45817. this.options_.llhls = this.options_.llhls === false ? false : true;
  45818. this.options_.bufferBasedABR = this.options_.bufferBasedABR || false;
  45819. if (typeof this.options_.playlistExclusionDuration !== 'number') {
  45820. this.options_.playlistExclusionDuration = 5 * 60;
  45821. }
  45822. if (typeof this.options_.bandwidth !== 'number') {
  45823. if (this.options_.useBandwidthFromLocalStorage) {
  45824. const storedObject = getVhsLocalStorage();
  45825. if (storedObject && storedObject.bandwidth) {
  45826. this.options_.bandwidth = storedObject.bandwidth;
  45827. this.tech_.trigger({
  45828. type: 'usage',
  45829. name: 'vhs-bandwidth-from-local-storage'
  45830. });
  45831. }
  45832. if (storedObject && storedObject.throughput) {
  45833. this.options_.throughput = storedObject.throughput;
  45834. this.tech_.trigger({
  45835. type: 'usage',
  45836. name: 'vhs-throughput-from-local-storage'
  45837. });
  45838. }
  45839. }
  45840. } // if bandwidth was not set by options or pulled from local storage, start playlist
  45841. // selection at a reasonable bandwidth
  45842. if (typeof this.options_.bandwidth !== 'number') {
  45843. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  45844. } // If the bandwidth number is unchanged from the initial setting
  45845. // then this takes precedence over the enableLowInitialPlaylist option
  45846. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  45847. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'customTagParsers', 'customTagMappers', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'bufferBasedABR', 'liveRangeSafeTimeDelta', 'llhls', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'exactManifestTimings', 'leastPixelDiffSelector'].forEach(option => {
  45848. if (typeof this.source_[option] !== 'undefined') {
  45849. this.options_[option] = this.source_[option];
  45850. }
  45851. });
  45852. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  45853. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  45854. }
  45855. /**
  45856. * called when player.src gets called, handle a new source
  45857. *
  45858. * @param {Object} src the source object to handle
  45859. */
  45860. src(src, type) {
  45861. // do nothing if the src is falsey
  45862. if (!src) {
  45863. return;
  45864. }
  45865. this.setOptions_(); // add main playlist controller options
  45866. this.options_.src = expandDataUri(this.source_.src);
  45867. this.options_.tech = this.tech_;
  45868. this.options_.externVhs = Vhs;
  45869. this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  45870. this.options_.seekTo = time => {
  45871. this.tech_.setCurrentTime(time);
  45872. };
  45873. this.playlistController_ = new PlaylistController(this.options_);
  45874. const playbackWatcherOptions = merge({
  45875. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  45876. }, this.options_, {
  45877. seekable: () => this.seekable(),
  45878. media: () => this.playlistController_.media(),
  45879. playlistController: this.playlistController_
  45880. });
  45881. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  45882. this.playlistController_.on('error', () => {
  45883. const player = videojs.players[this.tech_.options_.playerId];
  45884. let error = this.playlistController_.error;
  45885. if (typeof error === 'object' && !error.code) {
  45886. error.code = 3;
  45887. } else if (typeof error === 'string') {
  45888. error = {
  45889. message: error,
  45890. code: 3
  45891. };
  45892. }
  45893. player.error(error);
  45894. });
  45895. const defaultSelector = this.options_.bufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  45896. // compatibility with < v2
  45897. this.playlistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  45898. this.playlistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  45899. this.playlists = this.playlistController_.mainPlaylistLoader_;
  45900. this.mediaSource = this.playlistController_.mediaSource; // Proxy assignment of some properties to the main playlist
  45901. // controller. Using a custom property for backwards compatibility
  45902. // with < v2
  45903. Object.defineProperties(this, {
  45904. selectPlaylist: {
  45905. get() {
  45906. return this.playlistController_.selectPlaylist;
  45907. },
  45908. set(selectPlaylist) {
  45909. this.playlistController_.selectPlaylist = selectPlaylist.bind(this);
  45910. }
  45911. },
  45912. throughput: {
  45913. get() {
  45914. return this.playlistController_.mainSegmentLoader_.throughput.rate;
  45915. },
  45916. set(throughput) {
  45917. this.playlistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  45918. // for the cumulative average
  45919. this.playlistController_.mainSegmentLoader_.throughput.count = 1;
  45920. }
  45921. },
  45922. bandwidth: {
  45923. get() {
  45924. let playerBandwidthEst = this.playlistController_.mainSegmentLoader_.bandwidth;
  45925. const networkInformation = window$1.navigator.connection || window$1.navigator.mozConnection || window$1.navigator.webkitConnection;
  45926. const tenMbpsAsBitsPerSecond = 10e6;
  45927. if (this.options_.useNetworkInformationApi && networkInformation) {
  45928. // downlink returns Mbps
  45929. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  45930. const networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  45931. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  45932. // high quality streams are not filtered out.
  45933. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  45934. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  45935. } else {
  45936. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  45937. }
  45938. }
  45939. return playerBandwidthEst;
  45940. },
  45941. set(bandwidth) {
  45942. this.playlistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  45943. // `count` is set to zero that current value of `rate` isn't included
  45944. // in the cumulative average
  45945. this.playlistController_.mainSegmentLoader_.throughput = {
  45946. rate: 0,
  45947. count: 0
  45948. };
  45949. }
  45950. },
  45951. /**
  45952. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  45953. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  45954. * the entire process after that - decryption, transmuxing, and appending - provided
  45955. * by `throughput`.
  45956. *
  45957. * Since the two process are serial, the overall system bandwidth is given by:
  45958. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  45959. */
  45960. systemBandwidth: {
  45961. get() {
  45962. const invBandwidth = 1 / (this.bandwidth || 1);
  45963. let invThroughput;
  45964. if (this.throughput > 0) {
  45965. invThroughput = 1 / this.throughput;
  45966. } else {
  45967. invThroughput = 0;
  45968. }
  45969. const systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  45970. return systemBitrate;
  45971. },
  45972. set() {
  45973. videojs.log.error('The "systemBandwidth" property is read-only');
  45974. }
  45975. }
  45976. });
  45977. if (this.options_.bandwidth) {
  45978. this.bandwidth = this.options_.bandwidth;
  45979. }
  45980. if (this.options_.throughput) {
  45981. this.throughput = this.options_.throughput;
  45982. }
  45983. Object.defineProperties(this.stats, {
  45984. bandwidth: {
  45985. get: () => this.bandwidth || 0,
  45986. enumerable: true
  45987. },
  45988. mediaRequests: {
  45989. get: () => this.playlistController_.mediaRequests_() || 0,
  45990. enumerable: true
  45991. },
  45992. mediaRequestsAborted: {
  45993. get: () => this.playlistController_.mediaRequestsAborted_() || 0,
  45994. enumerable: true
  45995. },
  45996. mediaRequestsTimedout: {
  45997. get: () => this.playlistController_.mediaRequestsTimedout_() || 0,
  45998. enumerable: true
  45999. },
  46000. mediaRequestsErrored: {
  46001. get: () => this.playlistController_.mediaRequestsErrored_() || 0,
  46002. enumerable: true
  46003. },
  46004. mediaTransferDuration: {
  46005. get: () => this.playlistController_.mediaTransferDuration_() || 0,
  46006. enumerable: true
  46007. },
  46008. mediaBytesTransferred: {
  46009. get: () => this.playlistController_.mediaBytesTransferred_() || 0,
  46010. enumerable: true
  46011. },
  46012. mediaSecondsLoaded: {
  46013. get: () => this.playlistController_.mediaSecondsLoaded_() || 0,
  46014. enumerable: true
  46015. },
  46016. mediaAppends: {
  46017. get: () => this.playlistController_.mediaAppends_() || 0,
  46018. enumerable: true
  46019. },
  46020. mainAppendsToLoadedData: {
  46021. get: () => this.playlistController_.mainAppendsToLoadedData_() || 0,
  46022. enumerable: true
  46023. },
  46024. audioAppendsToLoadedData: {
  46025. get: () => this.playlistController_.audioAppendsToLoadedData_() || 0,
  46026. enumerable: true
  46027. },
  46028. appendsToLoadedData: {
  46029. get: () => this.playlistController_.appendsToLoadedData_() || 0,
  46030. enumerable: true
  46031. },
  46032. timeToLoadedData: {
  46033. get: () => this.playlistController_.timeToLoadedData_() || 0,
  46034. enumerable: true
  46035. },
  46036. buffered: {
  46037. get: () => timeRangesToArray(this.tech_.buffered()),
  46038. enumerable: true
  46039. },
  46040. currentTime: {
  46041. get: () => this.tech_.currentTime(),
  46042. enumerable: true
  46043. },
  46044. currentSource: {
  46045. get: () => this.tech_.currentSource_,
  46046. enumerable: true
  46047. },
  46048. currentTech: {
  46049. get: () => this.tech_.name_,
  46050. enumerable: true
  46051. },
  46052. duration: {
  46053. get: () => this.tech_.duration(),
  46054. enumerable: true
  46055. },
  46056. main: {
  46057. get: () => this.playlists.main,
  46058. enumerable: true
  46059. },
  46060. playerDimensions: {
  46061. get: () => this.tech_.currentDimensions(),
  46062. enumerable: true
  46063. },
  46064. seekable: {
  46065. get: () => timeRangesToArray(this.tech_.seekable()),
  46066. enumerable: true
  46067. },
  46068. timestamp: {
  46069. get: () => Date.now(),
  46070. enumerable: true
  46071. },
  46072. videoPlaybackQuality: {
  46073. get: () => this.tech_.getVideoPlaybackQuality(),
  46074. enumerable: true
  46075. }
  46076. });
  46077. this.tech_.one('canplay', this.playlistController_.setupFirstPlay.bind(this.playlistController_));
  46078. this.tech_.on('bandwidthupdate', () => {
  46079. if (this.options_.useBandwidthFromLocalStorage) {
  46080. updateVhsLocalStorage({
  46081. bandwidth: this.bandwidth,
  46082. throughput: Math.round(this.throughput)
  46083. });
  46084. }
  46085. });
  46086. this.playlistController_.on('selectedinitialmedia', () => {
  46087. // Add the manual rendition mix-in to VhsHandler
  46088. renditionSelectionMixin(this);
  46089. });
  46090. this.playlistController_.sourceUpdater_.on('createdsourcebuffers', () => {
  46091. this.setupEme_();
  46092. }); // the bandwidth of the primary segment loader is our best
  46093. // estimate of overall bandwidth
  46094. this.on(this.playlistController_, 'progress', function () {
  46095. this.tech_.trigger('progress');
  46096. }); // In the live case, we need to ignore the very first `seeking` event since
  46097. // that will be the result of the seek-to-live behavior
  46098. this.on(this.playlistController_, 'firstplay', function () {
  46099. this.ignoreNextSeekingEvent_ = true;
  46100. });
  46101. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  46102. // this can occur if someone sets the src in player.ready(), for instance
  46103. if (!this.tech_.el()) {
  46104. return;
  46105. }
  46106. this.mediaSourceUrl_ = window$1.URL.createObjectURL(this.playlistController_.mediaSource);
  46107. this.tech_.src(this.mediaSourceUrl_);
  46108. }
  46109. createKeySessions_() {
  46110. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  46111. this.logger_('waiting for EME key session creation');
  46112. waitForKeySessionCreation({
  46113. player: this.player_,
  46114. sourceKeySystems: this.source_.keySystems,
  46115. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  46116. mainPlaylists: this.playlists.main.playlists
  46117. }).then(() => {
  46118. this.logger_('created EME key session');
  46119. this.playlistController_.sourceUpdater_.initializedEme();
  46120. }).catch(err => {
  46121. this.logger_('error while creating EME key session', err);
  46122. this.player_.error({
  46123. message: 'Failed to initialize media keys for EME',
  46124. code: 3
  46125. });
  46126. });
  46127. }
  46128. handleWaitingForKey_() {
  46129. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  46130. // the key is in the manifest. While this should've happened on initial source load, it
  46131. // may happen again in live streams where the keys change, and the manifest info
  46132. // reflects the update.
  46133. //
  46134. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  46135. // already requested keys for, we don't have to worry about this generating extraneous
  46136. // requests.
  46137. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  46138. this.createKeySessions_();
  46139. }
  46140. /**
  46141. * If necessary and EME is available, sets up EME options and waits for key session
  46142. * creation.
  46143. *
  46144. * This function also updates the source updater so taht it can be used, as for some
  46145. * browsers, EME must be configured before content is appended (if appending unencrypted
  46146. * content before encrypted content).
  46147. */
  46148. setupEme_() {
  46149. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  46150. const didSetupEmeOptions = setupEmeOptions({
  46151. player: this.player_,
  46152. sourceKeySystems: this.source_.keySystems,
  46153. media: this.playlists.media(),
  46154. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  46155. });
  46156. this.player_.tech_.on('keystatuschange', e => {
  46157. if (e.status !== 'output-restricted') {
  46158. return;
  46159. }
  46160. const mainPlaylist = this.playlistController_.main();
  46161. if (!mainPlaylist || !mainPlaylist.playlists) {
  46162. return;
  46163. }
  46164. const excludedHDPlaylists = []; // Assume all HD streams are unplayable and exclude them from ABR selection
  46165. mainPlaylist.playlists.forEach(playlist => {
  46166. if (playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height >= 720) {
  46167. if (!playlist.excludeUntil || playlist.excludeUntil < Infinity) {
  46168. playlist.excludeUntil = Infinity;
  46169. excludedHDPlaylists.push(playlist);
  46170. }
  46171. }
  46172. });
  46173. if (excludedHDPlaylists.length) {
  46174. 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
  46175. this.playlistController_.fastQualityChange_();
  46176. }
  46177. });
  46178. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  46179. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_); // In IE11 this is too early to initialize media keys, and IE11 does not support
  46180. // promises.
  46181. if (videojs.browser.IE_VERSION === 11 || !didSetupEmeOptions) {
  46182. // If EME options were not set up, we've done all we could to initialize EME.
  46183. this.playlistController_.sourceUpdater_.initializedEme();
  46184. return;
  46185. }
  46186. this.createKeySessions_();
  46187. }
  46188. /**
  46189. * Initializes the quality levels and sets listeners to update them.
  46190. *
  46191. * @method setupQualityLevels_
  46192. * @private
  46193. */
  46194. setupQualityLevels_() {
  46195. const player = videojs.players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  46196. // or qualityLevels_ listeners have already been setup, do nothing.
  46197. if (!player || !player.qualityLevels || this.qualityLevels_) {
  46198. return;
  46199. }
  46200. this.qualityLevels_ = player.qualityLevels();
  46201. this.playlistController_.on('selectedinitialmedia', () => {
  46202. handleVhsLoadedMetadata(this.qualityLevels_, this);
  46203. });
  46204. this.playlists.on('mediachange', () => {
  46205. handleVhsMediaChange(this.qualityLevels_, this.playlists);
  46206. });
  46207. }
  46208. /**
  46209. * return the version
  46210. */
  46211. static version() {
  46212. return {
  46213. '@videojs/http-streaming': version$4,
  46214. 'mux.js': version$3,
  46215. 'mpd-parser': version$2,
  46216. 'm3u8-parser': version$1,
  46217. 'aes-decrypter': version
  46218. };
  46219. }
  46220. /**
  46221. * return the version
  46222. */
  46223. version() {
  46224. return this.constructor.version();
  46225. }
  46226. canChangeType() {
  46227. return SourceUpdater.canChangeType();
  46228. }
  46229. /**
  46230. * Begin playing the video.
  46231. */
  46232. play() {
  46233. this.playlistController_.play();
  46234. }
  46235. /**
  46236. * a wrapper around the function in PlaylistController
  46237. */
  46238. setCurrentTime(currentTime) {
  46239. this.playlistController_.setCurrentTime(currentTime);
  46240. }
  46241. /**
  46242. * a wrapper around the function in PlaylistController
  46243. */
  46244. duration() {
  46245. return this.playlistController_.duration();
  46246. }
  46247. /**
  46248. * a wrapper around the function in PlaylistController
  46249. */
  46250. seekable() {
  46251. return this.playlistController_.seekable();
  46252. }
  46253. /**
  46254. * Abort all outstanding work and cleanup.
  46255. */
  46256. dispose() {
  46257. if (this.playbackWatcher_) {
  46258. this.playbackWatcher_.dispose();
  46259. }
  46260. if (this.playlistController_) {
  46261. this.playlistController_.dispose();
  46262. }
  46263. if (this.qualityLevels_) {
  46264. this.qualityLevels_.dispose();
  46265. }
  46266. if (this.tech_ && this.tech_.vhs) {
  46267. delete this.tech_.vhs;
  46268. }
  46269. if (this.mediaSourceUrl_ && window$1.URL.revokeObjectURL) {
  46270. window$1.URL.revokeObjectURL(this.mediaSourceUrl_);
  46271. this.mediaSourceUrl_ = null;
  46272. }
  46273. if (this.tech_) {
  46274. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  46275. }
  46276. super.dispose();
  46277. }
  46278. convertToProgramTime(time, callback) {
  46279. return getProgramTime({
  46280. playlist: this.playlistController_.media(),
  46281. time,
  46282. callback
  46283. });
  46284. } // the player must be playing before calling this
  46285. seekToProgramTime(programTime, callback, pauseAfterSeek = true, retryCount = 2) {
  46286. return seekToProgramTime({
  46287. programTime,
  46288. playlist: this.playlistController_.media(),
  46289. retryCount,
  46290. pauseAfterSeek,
  46291. seekTo: this.options_.seekTo,
  46292. tech: this.options_.tech,
  46293. callback
  46294. });
  46295. }
  46296. }
  46297. /**
  46298. * The Source Handler object, which informs video.js what additional
  46299. * MIME types are supported and sets up playback. It is registered
  46300. * automatically to the appropriate tech based on the capabilities of
  46301. * the browser it is running in. It is not necessary to use or modify
  46302. * this object in normal usage.
  46303. */
  46304. const VhsSourceHandler = {
  46305. name: 'videojs-http-streaming',
  46306. VERSION: version$4,
  46307. canHandleSource(srcObj, options = {}) {
  46308. const localOptions = merge(videojs.options, options);
  46309. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  46310. },
  46311. handleSource(source, tech, options = {}) {
  46312. const localOptions = merge(videojs.options, options);
  46313. tech.vhs = new VhsHandler(source, tech, localOptions);
  46314. tech.vhs.xhr = xhrFactory();
  46315. tech.vhs.src(source.src, source.type);
  46316. return tech.vhs;
  46317. },
  46318. canPlayType(type, options) {
  46319. const simpleType = simpleTypeFromSourceType(type);
  46320. if (!simpleType) {
  46321. return '';
  46322. }
  46323. const overrideNative = VhsSourceHandler.getOverrideNative(options);
  46324. const supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  46325. const canUseMsePlayback = !supportsTypeNatively || overrideNative;
  46326. return canUseMsePlayback ? 'maybe' : '';
  46327. },
  46328. getOverrideNative(options = {}) {
  46329. const {
  46330. vhs = {}
  46331. } = options;
  46332. const defaultOverrideNative = !(videojs.browser.IS_ANY_SAFARI || videojs.browser.IS_IOS);
  46333. const {
  46334. overrideNative = defaultOverrideNative
  46335. } = vhs;
  46336. return overrideNative;
  46337. }
  46338. };
  46339. /**
  46340. * Check to see if the native MediaSource object exists and supports
  46341. * an MP4 container with both H.264 video and AAC-LC audio.
  46342. *
  46343. * @return {boolean} if native media sources are supported
  46344. */
  46345. const supportsNativeMediaSources = () => {
  46346. return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  46347. }; // register source handlers with the appropriate techs
  46348. if (supportsNativeMediaSources()) {
  46349. videojs.getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  46350. }
  46351. videojs.VhsHandler = VhsHandler;
  46352. videojs.VhsSourceHandler = VhsSourceHandler;
  46353. videojs.Vhs = Vhs;
  46354. if (!videojs.use) {
  46355. videojs.registerComponent('Vhs', Vhs);
  46356. }
  46357. videojs.options.vhs = videojs.options.vhs || {};
  46358. if (!videojs.getPlugin || !videojs.getPlugin('reloadSourceOnError')) {
  46359. videojs.registerPlugin('reloadSourceOnError', reloadSourceOnError);
  46360. }
  46361. export { videojs as default };