video.js 2.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343
  1. /**
  2. * @license
  3. * Video.js 8.3.0 <http://videojs.com/>
  4. * Copyright Brightcove, Inc. <https://www.brightcove.com/>
  5. * Available under Apache License Version 2.0
  6. * <https://github.com/videojs/video.js/blob/main/LICENSE>
  7. *
  8. * Includes vtt.js <https://github.com/mozilla/vtt.js>
  9. * Available under Apache License Version 2.0
  10. * <https://github.com/mozilla/vtt.js/blob/main/LICENSE>
  11. */
  12. (function (global, factory) {
  13. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  14. typeof define === 'function' && define.amd ? define(factory) :
  15. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.videojs = factory());
  16. })(this, (function () { 'use strict';
  17. var version$5 = "8.3.0";
  18. /**
  19. * An Object that contains lifecycle hooks as keys which point to an array
  20. * of functions that are run when a lifecycle is triggered
  21. *
  22. * @private
  23. */
  24. const hooks_ = {};
  25. /**
  26. * Get a list of hooks for a specific lifecycle
  27. *
  28. * @param {string} type
  29. * the lifecycle to get hooks from
  30. *
  31. * @param {Function|Function[]} [fn]
  32. * Optionally add a hook (or hooks) to the lifecycle that your are getting.
  33. *
  34. * @return {Array}
  35. * an array of hooks, or an empty array if there are none.
  36. */
  37. const hooks = function (type, fn) {
  38. hooks_[type] = hooks_[type] || [];
  39. if (fn) {
  40. hooks_[type] = hooks_[type].concat(fn);
  41. }
  42. return hooks_[type];
  43. };
  44. /**
  45. * Add a function hook to a specific videojs lifecycle.
  46. *
  47. * @param {string} type
  48. * the lifecycle to hook the function to.
  49. *
  50. * @param {Function|Function[]}
  51. * The function or array of functions to attach.
  52. */
  53. const hook = function (type, fn) {
  54. hooks(type, fn);
  55. };
  56. /**
  57. * Remove a hook from a specific videojs lifecycle.
  58. *
  59. * @param {string} type
  60. * the lifecycle that the function hooked to
  61. *
  62. * @param {Function} fn
  63. * The hooked function to remove
  64. *
  65. * @return {boolean}
  66. * The function that was removed or undef
  67. */
  68. const removeHook = function (type, fn) {
  69. const index = hooks(type).indexOf(fn);
  70. if (index <= -1) {
  71. return false;
  72. }
  73. hooks_[type] = hooks_[type].slice();
  74. hooks_[type].splice(index, 1);
  75. return true;
  76. };
  77. /**
  78. * Add a function hook that will only run once to a specific videojs lifecycle.
  79. *
  80. * @param {string} type
  81. * the lifecycle to hook the function to.
  82. *
  83. * @param {Function|Function[]}
  84. * The function or array of functions to attach.
  85. */
  86. const hookOnce = function (type, fn) {
  87. hooks(type, [].concat(fn).map(original => {
  88. const wrapper = (...args) => {
  89. removeHook(type, wrapper);
  90. return original(...args);
  91. };
  92. return wrapper;
  93. }));
  94. };
  95. /**
  96. * @file fullscreen-api.js
  97. * @module fullscreen-api
  98. */
  99. /**
  100. * Store the browser-specific methods for the fullscreen API.
  101. *
  102. * @type {Object}
  103. * @see [Specification]{@link https://fullscreen.spec.whatwg.org}
  104. * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}
  105. */
  106. const FullscreenApi = {
  107. prefixed: true
  108. };
  109. // browser API methods
  110. const apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror', 'fullscreen'],
  111. // WebKit
  112. ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror', '-webkit-full-screen'],
  113. // Mozilla
  114. ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror', '-moz-full-screen'],
  115. // Microsoft
  116. ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError', '-ms-fullscreen']];
  117. const specApi = apiMap[0];
  118. let browserApi;
  119. // determine the supported set of functions
  120. for (let i = 0; i < apiMap.length; i++) {
  121. // check for exitFullscreen function
  122. if (apiMap[i][1] in document) {
  123. browserApi = apiMap[i];
  124. break;
  125. }
  126. }
  127. // map the browser API names to the spec API names
  128. if (browserApi) {
  129. for (let i = 0; i < browserApi.length; i++) {
  130. FullscreenApi[specApi[i]] = browserApi[i];
  131. }
  132. FullscreenApi.prefixed = browserApi[0] !== specApi[0];
  133. }
  134. /**
  135. * @file create-logger.js
  136. * @module create-logger
  137. */
  138. // This is the private tracking variable for the logging history.
  139. let history = [];
  140. /**
  141. * Log messages to the console and history based on the type of message
  142. *
  143. * @private
  144. * @param {string} type
  145. * The name of the console method to use.
  146. *
  147. * @param {Array} args
  148. * The arguments to be passed to the matching console method.
  149. */
  150. const LogByTypeFactory = (name, log) => (type, level, args) => {
  151. const lvl = log.levels[level];
  152. const lvlRegExp = new RegExp(`^(${lvl})$`);
  153. if (type !== 'log') {
  154. // Add the type to the front of the message when it's not "log".
  155. args.unshift(type.toUpperCase() + ':');
  156. }
  157. // Add console prefix after adding to history.
  158. args.unshift(name + ':');
  159. // Add a clone of the args at this point to history.
  160. if (history) {
  161. history.push([].concat(args));
  162. // only store 1000 history entries
  163. const splice = history.length - 1000;
  164. history.splice(0, splice > 0 ? splice : 0);
  165. }
  166. // If there's no console then don't try to output messages, but they will
  167. // still be stored in history.
  168. if (!window.console) {
  169. return;
  170. }
  171. // Was setting these once outside of this function, but containing them
  172. // in the function makes it easier to test cases where console doesn't exist
  173. // when the module is executed.
  174. let fn = window.console[type];
  175. if (!fn && type === 'debug') {
  176. // Certain browsers don't have support for console.debug. For those, we
  177. // should default to the closest comparable log.
  178. fn = window.console.info || window.console.log;
  179. }
  180. // Bail out if there's no console or if this type is not allowed by the
  181. // current logging level.
  182. if (!fn || !lvl || !lvlRegExp.test(type)) {
  183. return;
  184. }
  185. fn[Array.isArray(args) ? 'apply' : 'call'](window.console, args);
  186. };
  187. function createLogger$1(name) {
  188. // This is the private tracking variable for logging level.
  189. let level = 'info';
  190. // the curried logByType bound to the specific log and history
  191. let logByType;
  192. /**
  193. * Logs plain debug messages. Similar to `console.log`.
  194. *
  195. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  196. * of our JSDoc template, we cannot properly document this as both a function
  197. * and a namespace, so its function signature is documented here.
  198. *
  199. * #### Arguments
  200. * ##### *args
  201. * *[]
  202. *
  203. * Any combination of values that could be passed to `console.log()`.
  204. *
  205. * #### Return Value
  206. *
  207. * `undefined`
  208. *
  209. * @namespace
  210. * @param {...*} args
  211. * One or more messages or objects that should be logged.
  212. */
  213. const log = function (...args) {
  214. logByType('log', level, args);
  215. };
  216. // This is the logByType helper that the logging methods below use
  217. logByType = LogByTypeFactory(name, log);
  218. /**
  219. * Create a new sublogger which chains the old name to the new name.
  220. *
  221. * For example, doing `videojs.log.createLogger('player')` and then using that logger will log the following:
  222. * ```js
  223. * mylogger('foo');
  224. * // > VIDEOJS: player: foo
  225. * ```
  226. *
  227. * @param {string} name
  228. * The name to add call the new logger
  229. * @return {Object}
  230. */
  231. log.createLogger = subname => createLogger$1(name + ': ' + subname);
  232. /**
  233. * Enumeration of available logging levels, where the keys are the level names
  234. * and the values are `|`-separated strings containing logging methods allowed
  235. * in that logging level. These strings are used to create a regular expression
  236. * matching the function name being called.
  237. *
  238. * Levels provided by Video.js are:
  239. *
  240. * - `off`: Matches no calls. Any value that can be cast to `false` will have
  241. * this effect. The most restrictive.
  242. * - `all`: Matches only Video.js-provided functions (`debug`, `log`,
  243. * `log.warn`, and `log.error`).
  244. * - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls.
  245. * - `info` (default): Matches `log`, `log.warn`, and `log.error` calls.
  246. * - `warn`: Matches `log.warn` and `log.error` calls.
  247. * - `error`: Matches only `log.error` calls.
  248. *
  249. * @type {Object}
  250. */
  251. log.levels = {
  252. all: 'debug|log|warn|error',
  253. off: '',
  254. debug: 'debug|log|warn|error',
  255. info: 'log|warn|error',
  256. warn: 'warn|error',
  257. error: 'error',
  258. DEFAULT: level
  259. };
  260. /**
  261. * Get or set the current logging level.
  262. *
  263. * If a string matching a key from {@link module:log.levels} is provided, acts
  264. * as a setter.
  265. *
  266. * @param {string} [lvl]
  267. * Pass a valid level to set a new logging level.
  268. *
  269. * @return {string}
  270. * The current logging level.
  271. */
  272. log.level = lvl => {
  273. if (typeof lvl === 'string') {
  274. if (!log.levels.hasOwnProperty(lvl)) {
  275. throw new Error(`"${lvl}" in not a valid log level`);
  276. }
  277. level = lvl;
  278. }
  279. return level;
  280. };
  281. /**
  282. * Returns an array containing everything that has been logged to the history.
  283. *
  284. * This array is a shallow clone of the internal history record. However, its
  285. * contents are _not_ cloned; so, mutating objects inside this array will
  286. * mutate them in history.
  287. *
  288. * @return {Array}
  289. */
  290. log.history = () => history ? [].concat(history) : [];
  291. /**
  292. * Allows you to filter the history by the given logger name
  293. *
  294. * @param {string} fname
  295. * The name to filter by
  296. *
  297. * @return {Array}
  298. * The filtered list to return
  299. */
  300. log.history.filter = fname => {
  301. return (history || []).filter(historyItem => {
  302. // if the first item in each historyItem includes `fname`, then it's a match
  303. return new RegExp(`.*${fname}.*`).test(historyItem[0]);
  304. });
  305. };
  306. /**
  307. * Clears the internal history tracking, but does not prevent further history
  308. * tracking.
  309. */
  310. log.history.clear = () => {
  311. if (history) {
  312. history.length = 0;
  313. }
  314. };
  315. /**
  316. * Disable history tracking if it is currently enabled.
  317. */
  318. log.history.disable = () => {
  319. if (history !== null) {
  320. history.length = 0;
  321. history = null;
  322. }
  323. };
  324. /**
  325. * Enable history tracking if it is currently disabled.
  326. */
  327. log.history.enable = () => {
  328. if (history === null) {
  329. history = [];
  330. }
  331. };
  332. /**
  333. * Logs error messages. Similar to `console.error`.
  334. *
  335. * @param {...*} args
  336. * One or more messages or objects that should be logged as an error
  337. */
  338. log.error = (...args) => logByType('error', level, args);
  339. /**
  340. * Logs warning messages. Similar to `console.warn`.
  341. *
  342. * @param {...*} args
  343. * One or more messages or objects that should be logged as a warning.
  344. */
  345. log.warn = (...args) => logByType('warn', level, args);
  346. /**
  347. * Logs debug messages. Similar to `console.debug`, but may also act as a comparable
  348. * log if `console.debug` is not available
  349. *
  350. * @param {...*} args
  351. * One or more messages or objects that should be logged as debug.
  352. */
  353. log.debug = (...args) => logByType('debug', level, args);
  354. return log;
  355. }
  356. /**
  357. * @file log.js
  358. * @module log
  359. */
  360. const log$1 = createLogger$1('VIDEOJS');
  361. const createLogger = log$1.createLogger;
  362. /**
  363. * @file obj.js
  364. * @module obj
  365. */
  366. /**
  367. * @callback obj:EachCallback
  368. *
  369. * @param {*} value
  370. * The current key for the object that is being iterated over.
  371. *
  372. * @param {string} key
  373. * The current key-value for object that is being iterated over
  374. */
  375. /**
  376. * @callback obj:ReduceCallback
  377. *
  378. * @param {*} accum
  379. * The value that is accumulating over the reduce loop.
  380. *
  381. * @param {*} value
  382. * The current key for the object that is being iterated over.
  383. *
  384. * @param {string} key
  385. * The current key-value for object that is being iterated over
  386. *
  387. * @return {*}
  388. * The new accumulated value.
  389. */
  390. const toString$1 = Object.prototype.toString;
  391. /**
  392. * Get the keys of an Object
  393. *
  394. * @param {Object}
  395. * The Object to get the keys from
  396. *
  397. * @return {string[]}
  398. * An array of the keys from the object. Returns an empty array if the
  399. * object passed in was invalid or had no keys.
  400. *
  401. * @private
  402. */
  403. const keys = function (object) {
  404. return isObject$1(object) ? Object.keys(object) : [];
  405. };
  406. /**
  407. * Array-like iteration for objects.
  408. *
  409. * @param {Object} object
  410. * The object to iterate over
  411. *
  412. * @param {obj:EachCallback} fn
  413. * The callback function which is called for each key in the object.
  414. */
  415. function each(object, fn) {
  416. keys(object).forEach(key => fn(object[key], key));
  417. }
  418. /**
  419. * Array-like reduce for objects.
  420. *
  421. * @param {Object} object
  422. * The Object that you want to reduce.
  423. *
  424. * @param {Function} fn
  425. * A callback function which is called for each key in the object. It
  426. * receives the accumulated value and the per-iteration value and key
  427. * as arguments.
  428. *
  429. * @param {*} [initial = 0]
  430. * Starting value
  431. *
  432. * @return {*}
  433. * The final accumulated value.
  434. */
  435. function reduce(object, fn, initial = 0) {
  436. return keys(object).reduce((accum, key) => fn(accum, object[key], key), initial);
  437. }
  438. /**
  439. * Returns whether a value is an object of any kind - including DOM nodes,
  440. * arrays, regular expressions, etc. Not functions, though.
  441. *
  442. * This avoids the gotcha where using `typeof` on a `null` value
  443. * results in `'object'`.
  444. *
  445. * @param {Object} value
  446. * @return {boolean}
  447. */
  448. function isObject$1(value) {
  449. return !!value && typeof value === 'object';
  450. }
  451. /**
  452. * Returns whether an object appears to be a "plain" object - that is, a
  453. * direct instance of `Object`.
  454. *
  455. * @param {Object} value
  456. * @return {boolean}
  457. */
  458. function isPlain(value) {
  459. return isObject$1(value) && toString$1.call(value) === '[object Object]' && value.constructor === Object;
  460. }
  461. /**
  462. * Merge two objects recursively.
  463. *
  464. * Performs a deep merge like
  465. * {@link https://lodash.com/docs/4.17.10#merge|lodash.merge}, but only merges
  466. * plain objects (not arrays, elements, or anything else).
  467. *
  468. * Non-plain object values will be copied directly from the right-most
  469. * argument.
  470. *
  471. * @param {Object[]} sources
  472. * One or more objects to merge into a new object.
  473. *
  474. * @return {Object}
  475. * A new object that is the merged result of all sources.
  476. */
  477. function merge$2(...sources) {
  478. const result = {};
  479. sources.forEach(source => {
  480. if (!source) {
  481. return;
  482. }
  483. each(source, (value, key) => {
  484. if (!isPlain(value)) {
  485. result[key] = value;
  486. return;
  487. }
  488. if (!isPlain(result[key])) {
  489. result[key] = {};
  490. }
  491. result[key] = merge$2(result[key], value);
  492. });
  493. });
  494. return result;
  495. }
  496. /**
  497. * Object.defineProperty but "lazy", which means that the value is only set after
  498. * it is retrieved the first time, rather than being set right away.
  499. *
  500. * @param {Object} obj the object to set the property on
  501. * @param {string} key the key for the property to set
  502. * @param {Function} getValue the function used to get the value when it is needed.
  503. * @param {boolean} setter whether a setter should be allowed or not
  504. */
  505. function defineLazyProperty(obj, key, getValue, setter = true) {
  506. const set = value => Object.defineProperty(obj, key, {
  507. value,
  508. enumerable: true,
  509. writable: true
  510. });
  511. const options = {
  512. configurable: true,
  513. enumerable: true,
  514. get() {
  515. const value = getValue();
  516. set(value);
  517. return value;
  518. }
  519. };
  520. if (setter) {
  521. options.set = set;
  522. }
  523. return Object.defineProperty(obj, key, options);
  524. }
  525. var Obj = /*#__PURE__*/Object.freeze({
  526. __proto__: null,
  527. each: each,
  528. reduce: reduce,
  529. isObject: isObject$1,
  530. isPlain: isPlain,
  531. merge: merge$2,
  532. defineLazyProperty: defineLazyProperty
  533. });
  534. /**
  535. * @file browser.js
  536. * @module browser
  537. */
  538. /**
  539. * Whether or not this device is an iPod.
  540. *
  541. * @static
  542. * @type {Boolean}
  543. */
  544. let IS_IPOD = false;
  545. /**
  546. * The detected iOS version - or `null`.
  547. *
  548. * @static
  549. * @type {string|null}
  550. */
  551. let IOS_VERSION = null;
  552. /**
  553. * Whether or not this is an Android device.
  554. *
  555. * @static
  556. * @type {Boolean}
  557. */
  558. let IS_ANDROID = false;
  559. /**
  560. * The detected Android version - or `null` if not Android or indeterminable.
  561. *
  562. * @static
  563. * @type {number|string|null}
  564. */
  565. let ANDROID_VERSION;
  566. /**
  567. * Whether or not this is Mozilla Firefox.
  568. *
  569. * @static
  570. * @type {Boolean}
  571. */
  572. let IS_FIREFOX = false;
  573. /**
  574. * Whether or not this is Microsoft Edge.
  575. *
  576. * @static
  577. * @type {Boolean}
  578. */
  579. let IS_EDGE = false;
  580. /**
  581. * Whether or not this is any Chromium Browser
  582. *
  583. * @static
  584. * @type {Boolean}
  585. */
  586. let IS_CHROMIUM = false;
  587. /**
  588. * Whether or not this is any Chromium browser that is not Edge.
  589. *
  590. * This will also be `true` for Chrome on iOS, which will have different support
  591. * as it is actually Safari under the hood.
  592. *
  593. * Deprecated, as the behaviour to not match Edge was to prevent Legacy Edge's UA matching.
  594. * IS_CHROMIUM should be used instead.
  595. * "Chromium but not Edge" could be explicitly tested with IS_CHROMIUM && !IS_EDGE
  596. *
  597. * @static
  598. * @deprecated
  599. * @type {Boolean}
  600. */
  601. let IS_CHROME = false;
  602. /**
  603. * The detected Chromium version - or `null`.
  604. *
  605. * @static
  606. * @type {number|null}
  607. */
  608. let CHROMIUM_VERSION = null;
  609. /**
  610. * The detected Google Chrome version - or `null`.
  611. * This has always been the _Chromium_ version, i.e. would return on Chromium Edge.
  612. * Deprecated, use CHROMIUM_VERSION instead.
  613. *
  614. * @static
  615. * @deprecated
  616. * @type {number|null}
  617. */
  618. let CHROME_VERSION = null;
  619. /**
  620. * The detected Internet Explorer version - or `null`.
  621. *
  622. * @static
  623. * @deprecated
  624. * @type {number|null}
  625. */
  626. let IE_VERSION = null;
  627. /**
  628. * Whether or not this is desktop Safari.
  629. *
  630. * @static
  631. * @type {Boolean}
  632. */
  633. let IS_SAFARI = false;
  634. /**
  635. * Whether or not this is a Windows machine.
  636. *
  637. * @static
  638. * @type {Boolean}
  639. */
  640. let IS_WINDOWS = false;
  641. /**
  642. * Whether or not this device is an iPad.
  643. *
  644. * @static
  645. * @type {Boolean}
  646. */
  647. let IS_IPAD = false;
  648. /**
  649. * Whether or not this device is an iPhone.
  650. *
  651. * @static
  652. * @type {Boolean}
  653. */
  654. // The Facebook app's UIWebView identifies as both an iPhone and iPad, so
  655. // to identify iPhones, we need to exclude iPads.
  656. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
  657. let IS_IPHONE = false;
  658. /**
  659. * Whether or not this device is touch-enabled.
  660. *
  661. * @static
  662. * @const
  663. * @type {Boolean}
  664. */
  665. const TOUCH_ENABLED = Boolean(isReal() && ('ontouchstart' in window || window.navigator.maxTouchPoints || window.DocumentTouch && window.document instanceof window.DocumentTouch));
  666. const UAD = window.navigator && window.navigator.userAgentData;
  667. if (UAD) {
  668. // If userAgentData is present, use it instead of userAgent to avoid warnings
  669. // Currently only implemented on Chromium
  670. // userAgentData does not expose Android version, so ANDROID_VERSION remains `null`
  671. IS_ANDROID = UAD.platform === 'Android';
  672. IS_EDGE = Boolean(UAD.brands.find(b => b.brand === 'Microsoft Edge'));
  673. IS_CHROMIUM = Boolean(UAD.brands.find(b => b.brand === 'Chromium'));
  674. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  675. CHROMIUM_VERSION = CHROME_VERSION = (UAD.brands.find(b => b.brand === 'Chromium') || {}).version || null;
  676. IS_WINDOWS = UAD.platform === 'Windows';
  677. }
  678. // If the browser is not Chromium, either userAgentData is not present which could be an old Chromium browser,
  679. // or it's a browser that has added userAgentData since that we don't have tests for yet. In either case,
  680. // the checks need to be made agiainst the regular userAgent string.
  681. if (!IS_CHROMIUM) {
  682. const USER_AGENT = window.navigator && window.navigator.userAgent || '';
  683. IS_IPOD = /iPod/i.test(USER_AGENT);
  684. IOS_VERSION = function () {
  685. const match = USER_AGENT.match(/OS (\d+)_/i);
  686. if (match && match[1]) {
  687. return match[1];
  688. }
  689. return null;
  690. }();
  691. IS_ANDROID = /Android/i.test(USER_AGENT);
  692. ANDROID_VERSION = function () {
  693. // This matches Android Major.Minor.Patch versions
  694. // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
  695. const match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
  696. if (!match) {
  697. return null;
  698. }
  699. const major = match[1] && parseFloat(match[1]);
  700. const minor = match[2] && parseFloat(match[2]);
  701. if (major && minor) {
  702. return parseFloat(match[1] + '.' + match[2]);
  703. } else if (major) {
  704. return major;
  705. }
  706. return null;
  707. }();
  708. IS_FIREFOX = /Firefox/i.test(USER_AGENT);
  709. IS_EDGE = /Edg/i.test(USER_AGENT);
  710. IS_CHROMIUM = /Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT);
  711. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  712. CHROMIUM_VERSION = CHROME_VERSION = function () {
  713. const match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
  714. if (match && match[2]) {
  715. return parseFloat(match[2]);
  716. }
  717. return null;
  718. }();
  719. IE_VERSION = function () {
  720. const result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT);
  721. let version = result && parseFloat(result[1]);
  722. if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) {
  723. // IE 11 has a different user agent string than other IE versions
  724. version = 11.0;
  725. }
  726. return version;
  727. }();
  728. IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE;
  729. IS_WINDOWS = /Windows/i.test(USER_AGENT);
  730. IS_IPAD = /iPad/i.test(USER_AGENT) || IS_SAFARI && TOUCH_ENABLED && !/iPhone/i.test(USER_AGENT);
  731. IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD;
  732. }
  733. /**
  734. * Whether or not this is an iOS device.
  735. *
  736. * @static
  737. * @const
  738. * @type {Boolean}
  739. */
  740. const IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
  741. /**
  742. * Whether or not this is any flavor of Safari - including iOS.
  743. *
  744. * @static
  745. * @const
  746. * @type {Boolean}
  747. */
  748. const IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;
  749. var browser = /*#__PURE__*/Object.freeze({
  750. __proto__: null,
  751. get IS_IPOD () { return IS_IPOD; },
  752. get IOS_VERSION () { return IOS_VERSION; },
  753. get IS_ANDROID () { return IS_ANDROID; },
  754. get ANDROID_VERSION () { return ANDROID_VERSION; },
  755. get IS_FIREFOX () { return IS_FIREFOX; },
  756. get IS_EDGE () { return IS_EDGE; },
  757. get IS_CHROMIUM () { return IS_CHROMIUM; },
  758. get IS_CHROME () { return IS_CHROME; },
  759. get CHROMIUM_VERSION () { return CHROMIUM_VERSION; },
  760. get CHROME_VERSION () { return CHROME_VERSION; },
  761. get IE_VERSION () { return IE_VERSION; },
  762. get IS_SAFARI () { return IS_SAFARI; },
  763. get IS_WINDOWS () { return IS_WINDOWS; },
  764. get IS_IPAD () { return IS_IPAD; },
  765. get IS_IPHONE () { return IS_IPHONE; },
  766. TOUCH_ENABLED: TOUCH_ENABLED,
  767. IS_IOS: IS_IOS,
  768. IS_ANY_SAFARI: IS_ANY_SAFARI
  769. });
  770. /**
  771. * @file dom.js
  772. * @module dom
  773. */
  774. /**
  775. * Detect if a value is a string with any non-whitespace characters.
  776. *
  777. * @private
  778. * @param {string} str
  779. * The string to check
  780. *
  781. * @return {boolean}
  782. * Will be `true` if the string is non-blank, `false` otherwise.
  783. *
  784. */
  785. function isNonBlankString(str) {
  786. // we use str.trim as it will trim any whitespace characters
  787. // from the front or back of non-whitespace characters. aka
  788. // Any string that contains non-whitespace characters will
  789. // still contain them after `trim` but whitespace only strings
  790. // will have a length of 0, failing this check.
  791. return typeof str === 'string' && Boolean(str.trim());
  792. }
  793. /**
  794. * Throws an error if the passed string has whitespace. This is used by
  795. * class methods to be relatively consistent with the classList API.
  796. *
  797. * @private
  798. * @param {string} str
  799. * The string to check for whitespace.
  800. *
  801. * @throws {Error}
  802. * Throws an error if there is whitespace in the string.
  803. */
  804. function throwIfWhitespace(str) {
  805. // str.indexOf instead of regex because str.indexOf is faster performance wise.
  806. if (str.indexOf(' ') >= 0) {
  807. throw new Error('class has illegal whitespace characters');
  808. }
  809. }
  810. /**
  811. * Whether the current DOM interface appears to be real (i.e. not simulated).
  812. *
  813. * @return {boolean}
  814. * Will be `true` if the DOM appears to be real, `false` otherwise.
  815. */
  816. function isReal() {
  817. // Both document and window will never be undefined thanks to `global`.
  818. return document === window.document;
  819. }
  820. /**
  821. * Determines, via duck typing, whether or not a value is a DOM element.
  822. *
  823. * @param {*} value
  824. * The value to check.
  825. *
  826. * @return {boolean}
  827. * Will be `true` if the value is a DOM element, `false` otherwise.
  828. */
  829. function isEl(value) {
  830. return isObject$1(value) && value.nodeType === 1;
  831. }
  832. /**
  833. * Determines if the current DOM is embedded in an iframe.
  834. *
  835. * @return {boolean}
  836. * Will be `true` if the DOM is embedded in an iframe, `false`
  837. * otherwise.
  838. */
  839. function isInFrame() {
  840. // We need a try/catch here because Safari will throw errors when attempting
  841. // to get either `parent` or `self`
  842. try {
  843. return window.parent !== window.self;
  844. } catch (x) {
  845. return true;
  846. }
  847. }
  848. /**
  849. * Creates functions to query the DOM using a given method.
  850. *
  851. * @private
  852. * @param {string} method
  853. * The method to create the query with.
  854. *
  855. * @return {Function}
  856. * The query method
  857. */
  858. function createQuerier(method) {
  859. return function (selector, context) {
  860. if (!isNonBlankString(selector)) {
  861. return document[method](null);
  862. }
  863. if (isNonBlankString(context)) {
  864. context = document.querySelector(context);
  865. }
  866. const ctx = isEl(context) ? context : document;
  867. return ctx[method] && ctx[method](selector);
  868. };
  869. }
  870. /**
  871. * Creates an element and applies properties, attributes, and inserts content.
  872. *
  873. * @param {string} [tagName='div']
  874. * Name of tag to be created.
  875. *
  876. * @param {Object} [properties={}]
  877. * Element properties to be applied.
  878. *
  879. * @param {Object} [attributes={}]
  880. * Element attributes to be applied.
  881. *
  882. * @param {ContentDescriptor} [content]
  883. * A content descriptor object.
  884. *
  885. * @return {Element}
  886. * The element that was created.
  887. */
  888. function createEl(tagName = 'div', properties = {}, attributes = {}, content) {
  889. const el = document.createElement(tagName);
  890. Object.getOwnPropertyNames(properties).forEach(function (propName) {
  891. const val = properties[propName];
  892. // Handle textContent since it's not supported everywhere and we have a
  893. // method for it.
  894. if (propName === 'textContent') {
  895. textContent(el, val);
  896. } else if (el[propName] !== val || propName === 'tabIndex') {
  897. el[propName] = val;
  898. }
  899. });
  900. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  901. el.setAttribute(attrName, attributes[attrName]);
  902. });
  903. if (content) {
  904. appendContent(el, content);
  905. }
  906. return el;
  907. }
  908. /**
  909. * Injects text into an element, replacing any existing contents entirely.
  910. *
  911. * @param {Element} el
  912. * The element to add text content into
  913. *
  914. * @param {string} text
  915. * The text content to add.
  916. *
  917. * @return {Element}
  918. * The element with added text content.
  919. */
  920. function textContent(el, text) {
  921. if (typeof el.textContent === 'undefined') {
  922. el.innerText = text;
  923. } else {
  924. el.textContent = text;
  925. }
  926. return el;
  927. }
  928. /**
  929. * Insert an element as the first child node of another
  930. *
  931. * @param {Element} child
  932. * Element to insert
  933. *
  934. * @param {Element} parent
  935. * Element to insert child into
  936. */
  937. function prependTo(child, parent) {
  938. if (parent.firstChild) {
  939. parent.insertBefore(child, parent.firstChild);
  940. } else {
  941. parent.appendChild(child);
  942. }
  943. }
  944. /**
  945. * Check if an element has a class name.
  946. *
  947. * @param {Element} element
  948. * Element to check
  949. *
  950. * @param {string} classToCheck
  951. * Class name to check for
  952. *
  953. * @return {boolean}
  954. * Will be `true` if the element has a class, `false` otherwise.
  955. *
  956. * @throws {Error}
  957. * Throws an error if `classToCheck` has white space.
  958. */
  959. function hasClass(element, classToCheck) {
  960. throwIfWhitespace(classToCheck);
  961. return element.classList.contains(classToCheck);
  962. }
  963. /**
  964. * Add a class name to an element.
  965. *
  966. * @param {Element} element
  967. * Element to add class name to.
  968. *
  969. * @param {...string} classesToAdd
  970. * One or more class name to add.
  971. *
  972. * @return {Element}
  973. * The DOM element with the added class name.
  974. */
  975. function addClass(element, ...classesToAdd) {
  976. element.classList.add(...classesToAdd.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  977. return element;
  978. }
  979. /**
  980. * Remove a class name from an element.
  981. *
  982. * @param {Element} element
  983. * Element to remove a class name from.
  984. *
  985. * @param {...string} classesToRemove
  986. * One or more class name to remove.
  987. *
  988. * @return {Element}
  989. * The DOM element with class name removed.
  990. */
  991. function removeClass(element, ...classesToRemove) {
  992. // Protect in case the player gets disposed
  993. if (!element) {
  994. log$1.warn("removeClass was called with an element that doesn't exist");
  995. return null;
  996. }
  997. element.classList.remove(...classesToRemove.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  998. return element;
  999. }
  1000. /**
  1001. * The callback definition for toggleClass.
  1002. *
  1003. * @callback module:dom~PredicateCallback
  1004. * @param {Element} element
  1005. * The DOM element of the Component.
  1006. *
  1007. * @param {string} classToToggle
  1008. * The `className` that wants to be toggled
  1009. *
  1010. * @return {boolean|undefined}
  1011. * If `true` is returned, the `classToToggle` will be added to the
  1012. * `element`. If `false`, the `classToToggle` will be removed from
  1013. * the `element`. If `undefined`, the callback will be ignored.
  1014. */
  1015. /**
  1016. * Adds or removes a class name to/from an element depending on an optional
  1017. * condition or the presence/absence of the class name.
  1018. *
  1019. * @param {Element} element
  1020. * The element to toggle a class name on.
  1021. *
  1022. * @param {string} classToToggle
  1023. * The class that should be toggled.
  1024. *
  1025. * @param {boolean|module:dom~PredicateCallback} [predicate]
  1026. * See the return value for {@link module:dom~PredicateCallback}
  1027. *
  1028. * @return {Element}
  1029. * The element with a class that has been toggled.
  1030. */
  1031. function toggleClass(element, classToToggle, predicate) {
  1032. if (typeof predicate === 'function') {
  1033. predicate = predicate(element, classToToggle);
  1034. }
  1035. if (typeof predicate !== 'boolean') {
  1036. predicate = undefined;
  1037. }
  1038. classToToggle.split(/\s+/).forEach(className => element.classList.toggle(className, predicate));
  1039. return element;
  1040. }
  1041. /**
  1042. * Apply attributes to an HTML element.
  1043. *
  1044. * @param {Element} el
  1045. * Element to add attributes to.
  1046. *
  1047. * @param {Object} [attributes]
  1048. * Attributes to be applied.
  1049. */
  1050. function setAttributes(el, attributes) {
  1051. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  1052. const attrValue = attributes[attrName];
  1053. if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
  1054. el.removeAttribute(attrName);
  1055. } else {
  1056. el.setAttribute(attrName, attrValue === true ? '' : attrValue);
  1057. }
  1058. });
  1059. }
  1060. /**
  1061. * Get an element's attribute values, as defined on the HTML tag.
  1062. *
  1063. * Attributes are not the same as properties. They're defined on the tag
  1064. * or with setAttribute.
  1065. *
  1066. * @param {Element} tag
  1067. * Element from which to get tag attributes.
  1068. *
  1069. * @return {Object}
  1070. * All attributes of the element. Boolean attributes will be `true` or
  1071. * `false`, others will be strings.
  1072. */
  1073. function getAttributes(tag) {
  1074. const obj = {};
  1075. // known boolean attributes
  1076. // we can check for matching boolean properties, but not all browsers
  1077. // and not all tags know about these attributes, so, we still want to check them manually
  1078. const knownBooleans = ',' + 'autoplay,controls,playsinline,loop,muted,default,defaultMuted' + ',';
  1079. if (tag && tag.attributes && tag.attributes.length > 0) {
  1080. const attrs = tag.attributes;
  1081. for (let i = attrs.length - 1; i >= 0; i--) {
  1082. const attrName = attrs[i].name;
  1083. let attrVal = attrs[i].value;
  1084. // check for known booleans
  1085. // the matching element property will return a value for typeof
  1086. if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) {
  1087. // the value of an included boolean attribute is typically an empty
  1088. // string ('') which would equal false if we just check for a false value.
  1089. // we also don't want support bad code like autoplay='false'
  1090. attrVal = attrVal !== null ? true : false;
  1091. }
  1092. obj[attrName] = attrVal;
  1093. }
  1094. }
  1095. return obj;
  1096. }
  1097. /**
  1098. * Get the value of an element's attribute.
  1099. *
  1100. * @param {Element} el
  1101. * A DOM element.
  1102. *
  1103. * @param {string} attribute
  1104. * Attribute to get the value of.
  1105. *
  1106. * @return {string}
  1107. * The value of the attribute.
  1108. */
  1109. function getAttribute(el, attribute) {
  1110. return el.getAttribute(attribute);
  1111. }
  1112. /**
  1113. * Set the value of an element's attribute.
  1114. *
  1115. * @param {Element} el
  1116. * A DOM element.
  1117. *
  1118. * @param {string} attribute
  1119. * Attribute to set.
  1120. *
  1121. * @param {string} value
  1122. * Value to set the attribute to.
  1123. */
  1124. function setAttribute(el, attribute, value) {
  1125. el.setAttribute(attribute, value);
  1126. }
  1127. /**
  1128. * Remove an element's attribute.
  1129. *
  1130. * @param {Element} el
  1131. * A DOM element.
  1132. *
  1133. * @param {string} attribute
  1134. * Attribute to remove.
  1135. */
  1136. function removeAttribute(el, attribute) {
  1137. el.removeAttribute(attribute);
  1138. }
  1139. /**
  1140. * Attempt to block the ability to select text.
  1141. */
  1142. function blockTextSelection() {
  1143. document.body.focus();
  1144. document.onselectstart = function () {
  1145. return false;
  1146. };
  1147. }
  1148. /**
  1149. * Turn off text selection blocking.
  1150. */
  1151. function unblockTextSelection() {
  1152. document.onselectstart = function () {
  1153. return true;
  1154. };
  1155. }
  1156. /**
  1157. * Identical to the native `getBoundingClientRect` function, but ensures that
  1158. * the method is supported at all (it is in all browsers we claim to support)
  1159. * and that the element is in the DOM before continuing.
  1160. *
  1161. * This wrapper function also shims properties which are not provided by some
  1162. * older browsers (namely, IE8).
  1163. *
  1164. * Additionally, some browsers do not support adding properties to a
  1165. * `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard
  1166. * properties (except `x` and `y` which are not widely supported). This helps
  1167. * avoid implementations where keys are non-enumerable.
  1168. *
  1169. * @param {Element} el
  1170. * Element whose `ClientRect` we want to calculate.
  1171. *
  1172. * @return {Object|undefined}
  1173. * Always returns a plain object - or `undefined` if it cannot.
  1174. */
  1175. function getBoundingClientRect(el) {
  1176. if (el && el.getBoundingClientRect && el.parentNode) {
  1177. const rect = el.getBoundingClientRect();
  1178. const result = {};
  1179. ['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(k => {
  1180. if (rect[k] !== undefined) {
  1181. result[k] = rect[k];
  1182. }
  1183. });
  1184. if (!result.height) {
  1185. result.height = parseFloat(computedStyle(el, 'height'));
  1186. }
  1187. if (!result.width) {
  1188. result.width = parseFloat(computedStyle(el, 'width'));
  1189. }
  1190. return result;
  1191. }
  1192. }
  1193. /**
  1194. * Represents the position of a DOM element on the page.
  1195. *
  1196. * @typedef {Object} module:dom~Position
  1197. *
  1198. * @property {number} left
  1199. * Pixels to the left.
  1200. *
  1201. * @property {number} top
  1202. * Pixels from the top.
  1203. */
  1204. /**
  1205. * Get the position of an element in the DOM.
  1206. *
  1207. * Uses `getBoundingClientRect` technique from John Resig.
  1208. *
  1209. * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/
  1210. *
  1211. * @param {Element} el
  1212. * Element from which to get offset.
  1213. *
  1214. * @return {module:dom~Position}
  1215. * The position of the element that was passed in.
  1216. */
  1217. function findPosition(el) {
  1218. if (!el || el && !el.offsetParent) {
  1219. return {
  1220. left: 0,
  1221. top: 0,
  1222. width: 0,
  1223. height: 0
  1224. };
  1225. }
  1226. const width = el.offsetWidth;
  1227. const height = el.offsetHeight;
  1228. let left = 0;
  1229. let top = 0;
  1230. while (el.offsetParent && el !== document[FullscreenApi.fullscreenElement]) {
  1231. left += el.offsetLeft;
  1232. top += el.offsetTop;
  1233. el = el.offsetParent;
  1234. }
  1235. return {
  1236. left,
  1237. top,
  1238. width,
  1239. height
  1240. };
  1241. }
  1242. /**
  1243. * Represents x and y coordinates for a DOM element or mouse pointer.
  1244. *
  1245. * @typedef {Object} module:dom~Coordinates
  1246. *
  1247. * @property {number} x
  1248. * x coordinate in pixels
  1249. *
  1250. * @property {number} y
  1251. * y coordinate in pixels
  1252. */
  1253. /**
  1254. * Get the pointer position within an element.
  1255. *
  1256. * The base on the coordinates are the bottom left of the element.
  1257. *
  1258. * @param {Element} el
  1259. * Element on which to get the pointer position on.
  1260. *
  1261. * @param {Event} event
  1262. * Event object.
  1263. *
  1264. * @return {module:dom~Coordinates}
  1265. * A coordinates object corresponding to the mouse position.
  1266. *
  1267. */
  1268. function getPointerPosition(el, event) {
  1269. const translated = {
  1270. x: 0,
  1271. y: 0
  1272. };
  1273. if (IS_IOS) {
  1274. let item = el;
  1275. while (item && item.nodeName.toLowerCase() !== 'html') {
  1276. const transform = computedStyle(item, 'transform');
  1277. if (/^matrix/.test(transform)) {
  1278. const values = transform.slice(7, -1).split(/,\s/).map(Number);
  1279. translated.x += values[4];
  1280. translated.y += values[5];
  1281. } else if (/^matrix3d/.test(transform)) {
  1282. const values = transform.slice(9, -1).split(/,\s/).map(Number);
  1283. translated.x += values[12];
  1284. translated.y += values[13];
  1285. }
  1286. item = item.parentNode;
  1287. }
  1288. }
  1289. const position = {};
  1290. const boxTarget = findPosition(event.target);
  1291. const box = findPosition(el);
  1292. const boxW = box.width;
  1293. const boxH = box.height;
  1294. let offsetY = event.offsetY - (box.top - boxTarget.top);
  1295. let offsetX = event.offsetX - (box.left - boxTarget.left);
  1296. if (event.changedTouches) {
  1297. offsetX = event.changedTouches[0].pageX - box.left;
  1298. offsetY = event.changedTouches[0].pageY + box.top;
  1299. if (IS_IOS) {
  1300. offsetX -= translated.x;
  1301. offsetY -= translated.y;
  1302. }
  1303. }
  1304. position.y = 1 - Math.max(0, Math.min(1, offsetY / boxH));
  1305. position.x = Math.max(0, Math.min(1, offsetX / boxW));
  1306. return position;
  1307. }
  1308. /**
  1309. * Determines, via duck typing, whether or not a value is a text node.
  1310. *
  1311. * @param {*} value
  1312. * Check if this value is a text node.
  1313. *
  1314. * @return {boolean}
  1315. * Will be `true` if the value is a text node, `false` otherwise.
  1316. */
  1317. function isTextNode$1(value) {
  1318. return isObject$1(value) && value.nodeType === 3;
  1319. }
  1320. /**
  1321. * Empties the contents of an element.
  1322. *
  1323. * @param {Element} el
  1324. * The element to empty children from
  1325. *
  1326. * @return {Element}
  1327. * The element with no children
  1328. */
  1329. function emptyEl(el) {
  1330. while (el.firstChild) {
  1331. el.removeChild(el.firstChild);
  1332. }
  1333. return el;
  1334. }
  1335. /**
  1336. * This is a mixed value that describes content to be injected into the DOM
  1337. * via some method. It can be of the following types:
  1338. *
  1339. * Type | Description
  1340. * -----------|-------------
  1341. * `string` | The value will be normalized into a text node.
  1342. * `Element` | The value will be accepted as-is.
  1343. * `Text` | A TextNode. The value will be accepted as-is.
  1344. * `Array` | A one-dimensional array of strings, elements, text nodes, or functions. These functions should return a string, element, or text node (any other return value, like an array, will be ignored).
  1345. * `Function` | A function, which is expected to return a string, element, text node, or array - any of the other possible values described above. This means that a content descriptor could be a function that returns an array of functions, but those second-level functions must return strings, elements, or text nodes.
  1346. *
  1347. * @typedef {string|Element|Text|Array|Function} ContentDescriptor
  1348. */
  1349. /**
  1350. * Normalizes content for eventual insertion into the DOM.
  1351. *
  1352. * This allows a wide range of content definition methods, but helps protect
  1353. * from falling into the trap of simply writing to `innerHTML`, which could
  1354. * be an XSS concern.
  1355. *
  1356. * The content for an element can be passed in multiple types and
  1357. * combinations, whose behavior is as follows:
  1358. *
  1359. * @param {ContentDescriptor} content
  1360. * A content descriptor value.
  1361. *
  1362. * @return {Array}
  1363. * All of the content that was passed in, normalized to an array of
  1364. * elements or text nodes.
  1365. */
  1366. function normalizeContent(content) {
  1367. // First, invoke content if it is a function. If it produces an array,
  1368. // that needs to happen before normalization.
  1369. if (typeof content === 'function') {
  1370. content = content();
  1371. }
  1372. // Next up, normalize to an array, so one or many items can be normalized,
  1373. // filtered, and returned.
  1374. return (Array.isArray(content) ? content : [content]).map(value => {
  1375. // First, invoke value if it is a function to produce a new value,
  1376. // which will be subsequently normalized to a Node of some kind.
  1377. if (typeof value === 'function') {
  1378. value = value();
  1379. }
  1380. if (isEl(value) || isTextNode$1(value)) {
  1381. return value;
  1382. }
  1383. if (typeof value === 'string' && /\S/.test(value)) {
  1384. return document.createTextNode(value);
  1385. }
  1386. }).filter(value => value);
  1387. }
  1388. /**
  1389. * Normalizes and appends content to an element.
  1390. *
  1391. * @param {Element} el
  1392. * Element to append normalized content to.
  1393. *
  1394. * @param {ContentDescriptor} content
  1395. * A content descriptor value.
  1396. *
  1397. * @return {Element}
  1398. * The element with appended normalized content.
  1399. */
  1400. function appendContent(el, content) {
  1401. normalizeContent(content).forEach(node => el.appendChild(node));
  1402. return el;
  1403. }
  1404. /**
  1405. * Normalizes and inserts content into an element; this is identical to
  1406. * `appendContent()`, except it empties the element first.
  1407. *
  1408. * @param {Element} el
  1409. * Element to insert normalized content into.
  1410. *
  1411. * @param {ContentDescriptor} content
  1412. * A content descriptor value.
  1413. *
  1414. * @return {Element}
  1415. * The element with inserted normalized content.
  1416. */
  1417. function insertContent(el, content) {
  1418. return appendContent(emptyEl(el), content);
  1419. }
  1420. /**
  1421. * Check if an event was a single left click.
  1422. *
  1423. * @param {Event} event
  1424. * Event object.
  1425. *
  1426. * @return {boolean}
  1427. * Will be `true` if a single left click, `false` otherwise.
  1428. */
  1429. function isSingleLeftClick(event) {
  1430. // Note: if you create something draggable, be sure to
  1431. // call it on both `mousedown` and `mousemove` event,
  1432. // otherwise `mousedown` should be enough for a button
  1433. if (event.button === undefined && event.buttons === undefined) {
  1434. // Why do we need `buttons` ?
  1435. // Because, middle mouse sometimes have this:
  1436. // e.button === 0 and e.buttons === 4
  1437. // Furthermore, we want to prevent combination click, something like
  1438. // HOLD middlemouse then left click, that would be
  1439. // e.button === 0, e.buttons === 5
  1440. // just `button` is not gonna work
  1441. // Alright, then what this block does ?
  1442. // this is for chrome `simulate mobile devices`
  1443. // I want to support this as well
  1444. return true;
  1445. }
  1446. if (event.button === 0 && event.buttons === undefined) {
  1447. // Touch screen, sometimes on some specific device, `buttons`
  1448. // doesn't have anything (safari on ios, blackberry...)
  1449. return true;
  1450. }
  1451. // `mouseup` event on a single left click has
  1452. // `button` and `buttons` equal to 0
  1453. if (event.type === 'mouseup' && event.button === 0 && event.buttons === 0) {
  1454. return true;
  1455. }
  1456. if (event.button !== 0 || event.buttons !== 1) {
  1457. // This is the reason we have those if else block above
  1458. // if any special case we can catch and let it slide
  1459. // we do it above, when get to here, this definitely
  1460. // is-not-left-click
  1461. return false;
  1462. }
  1463. return true;
  1464. }
  1465. /**
  1466. * Finds a single DOM element matching `selector` within the optional
  1467. * `context` of another DOM element (defaulting to `document`).
  1468. *
  1469. * @param {string} selector
  1470. * A valid CSS selector, which will be passed to `querySelector`.
  1471. *
  1472. * @param {Element|String} [context=document]
  1473. * A DOM element within which to query. Can also be a selector
  1474. * string in which case the first matching element will be used
  1475. * as context. If missing (or no element matches selector), falls
  1476. * back to `document`.
  1477. *
  1478. * @return {Element|null}
  1479. * The element that was found or null.
  1480. */
  1481. const $ = createQuerier('querySelector');
  1482. /**
  1483. * Finds a all DOM elements matching `selector` within the optional
  1484. * `context` of another DOM element (defaulting to `document`).
  1485. *
  1486. * @param {string} selector
  1487. * A valid CSS selector, which will be passed to `querySelectorAll`.
  1488. *
  1489. * @param {Element|String} [context=document]
  1490. * A DOM element within which to query. Can also be a selector
  1491. * string in which case the first matching element will be used
  1492. * as context. If missing (or no element matches selector), falls
  1493. * back to `document`.
  1494. *
  1495. * @return {NodeList}
  1496. * A element list of elements that were found. Will be empty if none
  1497. * were found.
  1498. *
  1499. */
  1500. const $$ = createQuerier('querySelectorAll');
  1501. /**
  1502. * A safe getComputedStyle.
  1503. *
  1504. * This is needed because in Firefox, if the player is loaded in an iframe with
  1505. * `display:none`, then `getComputedStyle` returns `null`, so, we do a
  1506. * null-check to make sure that the player doesn't break in these cases.
  1507. *
  1508. * @param {Element} el
  1509. * The element you want the computed style of
  1510. *
  1511. * @param {string} prop
  1512. * The property name you want
  1513. *
  1514. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  1515. */
  1516. function computedStyle(el, prop) {
  1517. if (!el || !prop) {
  1518. return '';
  1519. }
  1520. if (typeof window.getComputedStyle === 'function') {
  1521. let computedStyleValue;
  1522. try {
  1523. computedStyleValue = window.getComputedStyle(el);
  1524. } catch (e) {
  1525. return '';
  1526. }
  1527. return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : '';
  1528. }
  1529. return '';
  1530. }
  1531. var Dom = /*#__PURE__*/Object.freeze({
  1532. __proto__: null,
  1533. isReal: isReal,
  1534. isEl: isEl,
  1535. isInFrame: isInFrame,
  1536. createEl: createEl,
  1537. textContent: textContent,
  1538. prependTo: prependTo,
  1539. hasClass: hasClass,
  1540. addClass: addClass,
  1541. removeClass: removeClass,
  1542. toggleClass: toggleClass,
  1543. setAttributes: setAttributes,
  1544. getAttributes: getAttributes,
  1545. getAttribute: getAttribute,
  1546. setAttribute: setAttribute,
  1547. removeAttribute: removeAttribute,
  1548. blockTextSelection: blockTextSelection,
  1549. unblockTextSelection: unblockTextSelection,
  1550. getBoundingClientRect: getBoundingClientRect,
  1551. findPosition: findPosition,
  1552. getPointerPosition: getPointerPosition,
  1553. isTextNode: isTextNode$1,
  1554. emptyEl: emptyEl,
  1555. normalizeContent: normalizeContent,
  1556. appendContent: appendContent,
  1557. insertContent: insertContent,
  1558. isSingleLeftClick: isSingleLeftClick,
  1559. $: $,
  1560. $$: $$,
  1561. computedStyle: computedStyle
  1562. });
  1563. /**
  1564. * @file setup.js - Functions for setting up a player without
  1565. * user interaction based on the data-setup `attribute` of the video tag.
  1566. *
  1567. * @module setup
  1568. */
  1569. let _windowLoaded = false;
  1570. let videojs$1;
  1571. /**
  1572. * Set up any tags that have a data-setup `attribute` when the player is started.
  1573. */
  1574. const autoSetup = function () {
  1575. if (videojs$1.options.autoSetup === false) {
  1576. return;
  1577. }
  1578. const vids = Array.prototype.slice.call(document.getElementsByTagName('video'));
  1579. const audios = Array.prototype.slice.call(document.getElementsByTagName('audio'));
  1580. const divs = Array.prototype.slice.call(document.getElementsByTagName('video-js'));
  1581. const mediaEls = vids.concat(audios, divs);
  1582. // Check if any media elements exist
  1583. if (mediaEls && mediaEls.length > 0) {
  1584. for (let i = 0, e = mediaEls.length; i < e; i++) {
  1585. const mediaEl = mediaEls[i];
  1586. // Check if element exists, has getAttribute func.
  1587. if (mediaEl && mediaEl.getAttribute) {
  1588. // Make sure this player hasn't already been set up.
  1589. if (mediaEl.player === undefined) {
  1590. const options = mediaEl.getAttribute('data-setup');
  1591. // Check if data-setup attr exists.
  1592. // We only auto-setup if they've added the data-setup attr.
  1593. if (options !== null) {
  1594. // Create new video.js instance.
  1595. videojs$1(mediaEl);
  1596. }
  1597. }
  1598. // If getAttribute isn't defined, we need to wait for the DOM.
  1599. } else {
  1600. autoSetupTimeout(1);
  1601. break;
  1602. }
  1603. }
  1604. // No videos were found, so keep looping unless page is finished loading.
  1605. } else if (!_windowLoaded) {
  1606. autoSetupTimeout(1);
  1607. }
  1608. };
  1609. /**
  1610. * Wait until the page is loaded before running autoSetup. This will be called in
  1611. * autoSetup if `hasLoaded` returns false.
  1612. *
  1613. * @param {number} wait
  1614. * How long to wait in ms
  1615. *
  1616. * @param {module:videojs} [vjs]
  1617. * The videojs library function
  1618. */
  1619. function autoSetupTimeout(wait, vjs) {
  1620. // Protect against breakage in non-browser environments
  1621. if (!isReal()) {
  1622. return;
  1623. }
  1624. if (vjs) {
  1625. videojs$1 = vjs;
  1626. }
  1627. window.setTimeout(autoSetup, wait);
  1628. }
  1629. /**
  1630. * Used to set the internal tracking of window loaded state to true.
  1631. *
  1632. * @private
  1633. */
  1634. function setWindowLoaded() {
  1635. _windowLoaded = true;
  1636. window.removeEventListener('load', setWindowLoaded);
  1637. }
  1638. if (isReal()) {
  1639. if (document.readyState === 'complete') {
  1640. setWindowLoaded();
  1641. } else {
  1642. /**
  1643. * Listen for the load event on window, and set _windowLoaded to true.
  1644. *
  1645. * We use a standard event listener here to avoid incrementing the GUID
  1646. * before any players are created.
  1647. *
  1648. * @listens load
  1649. */
  1650. window.addEventListener('load', setWindowLoaded);
  1651. }
  1652. }
  1653. /**
  1654. * @file stylesheet.js
  1655. * @module stylesheet
  1656. */
  1657. /**
  1658. * Create a DOM style element given a className for it.
  1659. *
  1660. * @param {string} className
  1661. * The className to add to the created style element.
  1662. *
  1663. * @return {Element}
  1664. * The element that was created.
  1665. */
  1666. const createStyleElement = function (className) {
  1667. const style = document.createElement('style');
  1668. style.className = className;
  1669. return style;
  1670. };
  1671. /**
  1672. * Add text to a DOM element.
  1673. *
  1674. * @param {Element} el
  1675. * The Element to add text content to.
  1676. *
  1677. * @param {string} content
  1678. * The text to add to the element.
  1679. */
  1680. const setTextContent = function (el, content) {
  1681. if (el.styleSheet) {
  1682. el.styleSheet.cssText = content;
  1683. } else {
  1684. el.textContent = content;
  1685. }
  1686. };
  1687. /**
  1688. * @file dom-data.js
  1689. * @module dom-data
  1690. */
  1691. /**
  1692. * Element Data Store.
  1693. *
  1694. * Allows for binding data to an element without putting it directly on the
  1695. * element. Ex. Event listeners are stored here.
  1696. * (also from jsninja.com, slightly modified and updated for closure compiler)
  1697. *
  1698. * @type {Object}
  1699. * @private
  1700. */
  1701. var DomData = new WeakMap();
  1702. /**
  1703. * @file guid.js
  1704. * @module guid
  1705. */
  1706. // Default value for GUIDs. This allows us to reset the GUID counter in tests.
  1707. //
  1708. // The initial GUID is 3 because some users have come to rely on the first
  1709. // default player ID ending up as `vjs_video_3`.
  1710. //
  1711. // See: https://github.com/videojs/video.js/pull/6216
  1712. const _initialGuid = 3;
  1713. /**
  1714. * Unique ID for an element or function
  1715. *
  1716. * @type {Number}
  1717. */
  1718. let _guid = _initialGuid;
  1719. /**
  1720. * Get a unique auto-incrementing ID by number that has not been returned before.
  1721. *
  1722. * @return {number}
  1723. * A new unique ID.
  1724. */
  1725. function newGUID() {
  1726. return _guid++;
  1727. }
  1728. /**
  1729. * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
  1730. * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
  1731. * This should work very similarly to jQuery's events, however it's based off the book version which isn't as
  1732. * robust as jquery's, so there's probably some differences.
  1733. *
  1734. * @file events.js
  1735. * @module events
  1736. */
  1737. /**
  1738. * Clean up the listener cache and dispatchers
  1739. *
  1740. * @param {Element|Object} elem
  1741. * Element to clean up
  1742. *
  1743. * @param {string} type
  1744. * Type of event to clean up
  1745. */
  1746. function _cleanUpEvents(elem, type) {
  1747. if (!DomData.has(elem)) {
  1748. return;
  1749. }
  1750. const data = DomData.get(elem);
  1751. // Remove the events of a particular type if there are none left
  1752. if (data.handlers[type].length === 0) {
  1753. delete data.handlers[type];
  1754. // data.handlers[type] = null;
  1755. // Setting to null was causing an error with data.handlers
  1756. // Remove the meta-handler from the element
  1757. if (elem.removeEventListener) {
  1758. elem.removeEventListener(type, data.dispatcher, false);
  1759. } else if (elem.detachEvent) {
  1760. elem.detachEvent('on' + type, data.dispatcher);
  1761. }
  1762. }
  1763. // Remove the events object if there are no types left
  1764. if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
  1765. delete data.handlers;
  1766. delete data.dispatcher;
  1767. delete data.disabled;
  1768. }
  1769. // Finally remove the element data if there is no data left
  1770. if (Object.getOwnPropertyNames(data).length === 0) {
  1771. DomData.delete(elem);
  1772. }
  1773. }
  1774. /**
  1775. * Loops through an array of event types and calls the requested method for each type.
  1776. *
  1777. * @param {Function} fn
  1778. * The event method we want to use.
  1779. *
  1780. * @param {Element|Object} elem
  1781. * Element or object to bind listeners to
  1782. *
  1783. * @param {string} type
  1784. * Type of event to bind to.
  1785. *
  1786. * @param {Function} callback
  1787. * Event listener.
  1788. */
  1789. function _handleMultipleEvents(fn, elem, types, callback) {
  1790. types.forEach(function (type) {
  1791. // Call the event method for each one of the types
  1792. fn(elem, type, callback);
  1793. });
  1794. }
  1795. /**
  1796. * Fix a native event to have standard property values
  1797. *
  1798. * @param {Object} event
  1799. * Event object to fix.
  1800. *
  1801. * @return {Object}
  1802. * Fixed event object.
  1803. */
  1804. function fixEvent(event) {
  1805. if (event.fixed_) {
  1806. return event;
  1807. }
  1808. function returnTrue() {
  1809. return true;
  1810. }
  1811. function returnFalse() {
  1812. return false;
  1813. }
  1814. // Test if fixing up is needed
  1815. // Used to check if !event.stopPropagation instead of isPropagationStopped
  1816. // But native events return true for stopPropagation, but don't have
  1817. // other expected methods like isPropagationStopped. Seems to be a problem
  1818. // with the Javascript Ninja code. So we're just overriding all events now.
  1819. if (!event || !event.isPropagationStopped || !event.isImmediatePropagationStopped) {
  1820. const old = event || window.event;
  1821. event = {};
  1822. // Clone the old object so that we can modify the values event = {};
  1823. // IE8 Doesn't like when you mess with native event properties
  1824. // Firefox returns false for event.hasOwnProperty('type') and other props
  1825. // which makes copying more difficult.
  1826. // TODO: Probably best to create a whitelist of event props
  1827. for (const key in old) {
  1828. // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
  1829. // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
  1830. // and webkitMovementX/Y
  1831. // Lighthouse complains if Event.path is copied
  1832. if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY' && key !== 'path') {
  1833. // Chrome 32+ warns if you try to copy deprecated returnValue, but
  1834. // we still want to if preventDefault isn't supported (IE8).
  1835. if (!(key === 'returnValue' && old.preventDefault)) {
  1836. event[key] = old[key];
  1837. }
  1838. }
  1839. }
  1840. // The event occurred on this element
  1841. if (!event.target) {
  1842. event.target = event.srcElement || document;
  1843. }
  1844. // Handle which other element the event is related to
  1845. if (!event.relatedTarget) {
  1846. event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
  1847. }
  1848. // Stop the default browser action
  1849. event.preventDefault = function () {
  1850. if (old.preventDefault) {
  1851. old.preventDefault();
  1852. }
  1853. event.returnValue = false;
  1854. old.returnValue = false;
  1855. event.defaultPrevented = true;
  1856. };
  1857. event.defaultPrevented = false;
  1858. // Stop the event from bubbling
  1859. event.stopPropagation = function () {
  1860. if (old.stopPropagation) {
  1861. old.stopPropagation();
  1862. }
  1863. event.cancelBubble = true;
  1864. old.cancelBubble = true;
  1865. event.isPropagationStopped = returnTrue;
  1866. };
  1867. event.isPropagationStopped = returnFalse;
  1868. // Stop the event from bubbling and executing other handlers
  1869. event.stopImmediatePropagation = function () {
  1870. if (old.stopImmediatePropagation) {
  1871. old.stopImmediatePropagation();
  1872. }
  1873. event.isImmediatePropagationStopped = returnTrue;
  1874. event.stopPropagation();
  1875. };
  1876. event.isImmediatePropagationStopped = returnFalse;
  1877. // Handle mouse position
  1878. if (event.clientX !== null && event.clientX !== undefined) {
  1879. const doc = document.documentElement;
  1880. const body = document.body;
  1881. event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  1882. event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  1883. }
  1884. // Handle key presses
  1885. event.which = event.charCode || event.keyCode;
  1886. // Fix button for mouse clicks:
  1887. // 0 == left; 1 == middle; 2 == right
  1888. if (event.button !== null && event.button !== undefined) {
  1889. // The following is disabled because it does not pass videojs-standard
  1890. // and... yikes.
  1891. /* eslint-disable */
  1892. event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
  1893. /* eslint-enable */
  1894. }
  1895. }
  1896. event.fixed_ = true;
  1897. // Returns fixed-up instance
  1898. return event;
  1899. }
  1900. /**
  1901. * Whether passive event listeners are supported
  1902. */
  1903. let _supportsPassive;
  1904. const supportsPassive = function () {
  1905. if (typeof _supportsPassive !== 'boolean') {
  1906. _supportsPassive = false;
  1907. try {
  1908. const opts = Object.defineProperty({}, 'passive', {
  1909. get() {
  1910. _supportsPassive = true;
  1911. }
  1912. });
  1913. window.addEventListener('test', null, opts);
  1914. window.removeEventListener('test', null, opts);
  1915. } catch (e) {
  1916. // disregard
  1917. }
  1918. }
  1919. return _supportsPassive;
  1920. };
  1921. /**
  1922. * Touch events Chrome expects to be passive
  1923. */
  1924. const passiveEvents = ['touchstart', 'touchmove'];
  1925. /**
  1926. * Add an event listener to element
  1927. * It stores the handler function in a separate cache object
  1928. * and adds a generic handler to the element's event,
  1929. * along with a unique id (guid) to the element.
  1930. *
  1931. * @param {Element|Object} elem
  1932. * Element or object to bind listeners to
  1933. *
  1934. * @param {string|string[]} type
  1935. * Type of event to bind to.
  1936. *
  1937. * @param {Function} fn
  1938. * Event listener.
  1939. */
  1940. function on(elem, type, fn) {
  1941. if (Array.isArray(type)) {
  1942. return _handleMultipleEvents(on, elem, type, fn);
  1943. }
  1944. if (!DomData.has(elem)) {
  1945. DomData.set(elem, {});
  1946. }
  1947. const data = DomData.get(elem);
  1948. // We need a place to store all our handler data
  1949. if (!data.handlers) {
  1950. data.handlers = {};
  1951. }
  1952. if (!data.handlers[type]) {
  1953. data.handlers[type] = [];
  1954. }
  1955. if (!fn.guid) {
  1956. fn.guid = newGUID();
  1957. }
  1958. data.handlers[type].push(fn);
  1959. if (!data.dispatcher) {
  1960. data.disabled = false;
  1961. data.dispatcher = function (event, hash) {
  1962. if (data.disabled) {
  1963. return;
  1964. }
  1965. event = fixEvent(event);
  1966. const handlers = data.handlers[event.type];
  1967. if (handlers) {
  1968. // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
  1969. const handlersCopy = handlers.slice(0);
  1970. for (let m = 0, n = handlersCopy.length; m < n; m++) {
  1971. if (event.isImmediatePropagationStopped()) {
  1972. break;
  1973. } else {
  1974. try {
  1975. handlersCopy[m].call(elem, event, hash);
  1976. } catch (e) {
  1977. log$1.error(e);
  1978. }
  1979. }
  1980. }
  1981. }
  1982. };
  1983. }
  1984. if (data.handlers[type].length === 1) {
  1985. if (elem.addEventListener) {
  1986. let options = false;
  1987. if (supportsPassive() && passiveEvents.indexOf(type) > -1) {
  1988. options = {
  1989. passive: true
  1990. };
  1991. }
  1992. elem.addEventListener(type, data.dispatcher, options);
  1993. } else if (elem.attachEvent) {
  1994. elem.attachEvent('on' + type, data.dispatcher);
  1995. }
  1996. }
  1997. }
  1998. /**
  1999. * Removes event listeners from an element
  2000. *
  2001. * @param {Element|Object} elem
  2002. * Object to remove listeners from.
  2003. *
  2004. * @param {string|string[]} [type]
  2005. * Type of listener to remove. Don't include to remove all events from element.
  2006. *
  2007. * @param {Function} [fn]
  2008. * Specific listener to remove. Don't include to remove listeners for an event
  2009. * type.
  2010. */
  2011. function off(elem, type, fn) {
  2012. // Don't want to add a cache object through getElData if not needed
  2013. if (!DomData.has(elem)) {
  2014. return;
  2015. }
  2016. const data = DomData.get(elem);
  2017. // If no events exist, nothing to unbind
  2018. if (!data.handlers) {
  2019. return;
  2020. }
  2021. if (Array.isArray(type)) {
  2022. return _handleMultipleEvents(off, elem, type, fn);
  2023. }
  2024. // Utility function
  2025. const removeType = function (el, t) {
  2026. data.handlers[t] = [];
  2027. _cleanUpEvents(el, t);
  2028. };
  2029. // Are we removing all bound events?
  2030. if (type === undefined) {
  2031. for (const t in data.handlers) {
  2032. if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t)) {
  2033. removeType(elem, t);
  2034. }
  2035. }
  2036. return;
  2037. }
  2038. const handlers = data.handlers[type];
  2039. // If no handlers exist, nothing to unbind
  2040. if (!handlers) {
  2041. return;
  2042. }
  2043. // If no listener was provided, remove all listeners for type
  2044. if (!fn) {
  2045. removeType(elem, type);
  2046. return;
  2047. }
  2048. // We're only removing a single handler
  2049. if (fn.guid) {
  2050. for (let n = 0; n < handlers.length; n++) {
  2051. if (handlers[n].guid === fn.guid) {
  2052. handlers.splice(n--, 1);
  2053. }
  2054. }
  2055. }
  2056. _cleanUpEvents(elem, type);
  2057. }
  2058. /**
  2059. * Trigger an event for an element
  2060. *
  2061. * @param {Element|Object} elem
  2062. * Element to trigger an event on
  2063. *
  2064. * @param {EventTarget~Event|string} event
  2065. * A string (the type) or an event object with a type attribute
  2066. *
  2067. * @param {Object} [hash]
  2068. * data hash to pass along with the event
  2069. *
  2070. * @return {boolean|undefined}
  2071. * Returns the opposite of `defaultPrevented` if default was
  2072. * prevented. Otherwise, returns `undefined`
  2073. */
  2074. function trigger(elem, event, hash) {
  2075. // Fetches element data and a reference to the parent (for bubbling).
  2076. // Don't want to add a data object to cache for every parent,
  2077. // so checking hasElData first.
  2078. const elemData = DomData.has(elem) ? DomData.get(elem) : {};
  2079. const parent = elem.parentNode || elem.ownerDocument;
  2080. // type = event.type || event,
  2081. // handler;
  2082. // If an event name was passed as a string, creates an event out of it
  2083. if (typeof event === 'string') {
  2084. event = {
  2085. type: event,
  2086. target: elem
  2087. };
  2088. } else if (!event.target) {
  2089. event.target = elem;
  2090. }
  2091. // Normalizes the event properties.
  2092. event = fixEvent(event);
  2093. // If the passed element has a dispatcher, executes the established handlers.
  2094. if (elemData.dispatcher) {
  2095. elemData.dispatcher.call(elem, event, hash);
  2096. }
  2097. // Unless explicitly stopped or the event does not bubble (e.g. media events)
  2098. // recursively calls this function to bubble the event up the DOM.
  2099. if (parent && !event.isPropagationStopped() && event.bubbles === true) {
  2100. trigger.call(null, parent, event, hash);
  2101. // If at the top of the DOM, triggers the default action unless disabled.
  2102. } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) {
  2103. if (!DomData.has(event.target)) {
  2104. DomData.set(event.target, {});
  2105. }
  2106. const targetData = DomData.get(event.target);
  2107. // Checks if the target has a default action for this event.
  2108. if (event.target[event.type]) {
  2109. // Temporarily disables event dispatching on the target as we have already executed the handler.
  2110. targetData.disabled = true;
  2111. // Executes the default action.
  2112. if (typeof event.target[event.type] === 'function') {
  2113. event.target[event.type]();
  2114. }
  2115. // Re-enables event dispatching.
  2116. targetData.disabled = false;
  2117. }
  2118. }
  2119. // Inform the triggerer if the default was prevented by returning false
  2120. return !event.defaultPrevented;
  2121. }
  2122. /**
  2123. * Trigger a listener only once for an event.
  2124. *
  2125. * @param {Element|Object} elem
  2126. * Element or object to bind to.
  2127. *
  2128. * @param {string|string[]} type
  2129. * Name/type of event
  2130. *
  2131. * @param {Event~EventListener} fn
  2132. * Event listener function
  2133. */
  2134. function one(elem, type, fn) {
  2135. if (Array.isArray(type)) {
  2136. return _handleMultipleEvents(one, elem, type, fn);
  2137. }
  2138. const func = function () {
  2139. off(elem, type, func);
  2140. fn.apply(this, arguments);
  2141. };
  2142. // copy the guid to the new function so it can removed using the original function's ID
  2143. func.guid = fn.guid = fn.guid || newGUID();
  2144. on(elem, type, func);
  2145. }
  2146. /**
  2147. * Trigger a listener only once and then turn if off for all
  2148. * configured events
  2149. *
  2150. * @param {Element|Object} elem
  2151. * Element or object to bind to.
  2152. *
  2153. * @param {string|string[]} type
  2154. * Name/type of event
  2155. *
  2156. * @param {Event~EventListener} fn
  2157. * Event listener function
  2158. */
  2159. function any(elem, type, fn) {
  2160. const func = function () {
  2161. off(elem, type, func);
  2162. fn.apply(this, arguments);
  2163. };
  2164. // copy the guid to the new function so it can removed using the original function's ID
  2165. func.guid = fn.guid = fn.guid || newGUID();
  2166. // multiple ons, but one off for everything
  2167. on(elem, type, func);
  2168. }
  2169. var Events = /*#__PURE__*/Object.freeze({
  2170. __proto__: null,
  2171. fixEvent: fixEvent,
  2172. on: on,
  2173. off: off,
  2174. trigger: trigger,
  2175. one: one,
  2176. any: any
  2177. });
  2178. /**
  2179. * @file fn.js
  2180. * @module fn
  2181. */
  2182. const UPDATE_REFRESH_INTERVAL = 30;
  2183. /**
  2184. * A private, internal-only function for changing the context of a function.
  2185. *
  2186. * It also stores a unique id on the function so it can be easily removed from
  2187. * events.
  2188. *
  2189. * @private
  2190. * @function
  2191. * @param {*} context
  2192. * The object to bind as scope.
  2193. *
  2194. * @param {Function} fn
  2195. * The function to be bound to a scope.
  2196. *
  2197. * @param {number} [uid]
  2198. * An optional unique ID for the function to be set
  2199. *
  2200. * @return {Function}
  2201. * The new function that will be bound into the context given
  2202. */
  2203. const bind_ = function (context, fn, uid) {
  2204. // Make sure the function has a unique ID
  2205. if (!fn.guid) {
  2206. fn.guid = newGUID();
  2207. }
  2208. // Create the new function that changes the context
  2209. const bound = fn.bind(context);
  2210. // Allow for the ability to individualize this function
  2211. // Needed in the case where multiple objects might share the same prototype
  2212. // IF both items add an event listener with the same function, then you try to remove just one
  2213. // it will remove both because they both have the same guid.
  2214. // when using this, you need to use the bind method when you remove the listener as well.
  2215. // currently used in text tracks
  2216. bound.guid = uid ? uid + '_' + fn.guid : fn.guid;
  2217. return bound;
  2218. };
  2219. /**
  2220. * Wraps the given function, `fn`, with a new function that only invokes `fn`
  2221. * at most once per every `wait` milliseconds.
  2222. *
  2223. * @function
  2224. * @param {Function} fn
  2225. * The function to be throttled.
  2226. *
  2227. * @param {number} wait
  2228. * The number of milliseconds by which to throttle.
  2229. *
  2230. * @return {Function}
  2231. */
  2232. const throttle = function (fn, wait) {
  2233. let last = window.performance.now();
  2234. const throttled = function (...args) {
  2235. const now = window.performance.now();
  2236. if (now - last >= wait) {
  2237. fn(...args);
  2238. last = now;
  2239. }
  2240. };
  2241. return throttled;
  2242. };
  2243. /**
  2244. * Creates a debounced function that delays invoking `func` until after `wait`
  2245. * milliseconds have elapsed since the last time the debounced function was
  2246. * invoked.
  2247. *
  2248. * Inspired by lodash and underscore implementations.
  2249. *
  2250. * @function
  2251. * @param {Function} func
  2252. * The function to wrap with debounce behavior.
  2253. *
  2254. * @param {number} wait
  2255. * The number of milliseconds to wait after the last invocation.
  2256. *
  2257. * @param {boolean} [immediate]
  2258. * Whether or not to invoke the function immediately upon creation.
  2259. *
  2260. * @param {Object} [context=window]
  2261. * The "context" in which the debounced function should debounce. For
  2262. * example, if this function should be tied to a Video.js player,
  2263. * the player can be passed here. Alternatively, defaults to the
  2264. * global `window` object.
  2265. *
  2266. * @return {Function}
  2267. * A debounced function.
  2268. */
  2269. const debounce = function (func, wait, immediate, context = window) {
  2270. let timeout;
  2271. const cancel = () => {
  2272. context.clearTimeout(timeout);
  2273. timeout = null;
  2274. };
  2275. /* eslint-disable consistent-this */
  2276. const debounced = function () {
  2277. const self = this;
  2278. const args = arguments;
  2279. let later = function () {
  2280. timeout = null;
  2281. later = null;
  2282. if (!immediate) {
  2283. func.apply(self, args);
  2284. }
  2285. };
  2286. if (!timeout && immediate) {
  2287. func.apply(self, args);
  2288. }
  2289. context.clearTimeout(timeout);
  2290. timeout = context.setTimeout(later, wait);
  2291. };
  2292. /* eslint-enable consistent-this */
  2293. debounced.cancel = cancel;
  2294. return debounced;
  2295. };
  2296. var Fn = /*#__PURE__*/Object.freeze({
  2297. __proto__: null,
  2298. UPDATE_REFRESH_INTERVAL: UPDATE_REFRESH_INTERVAL,
  2299. bind_: bind_,
  2300. throttle: throttle,
  2301. debounce: debounce
  2302. });
  2303. /**
  2304. * @file src/js/event-target.js
  2305. */
  2306. let EVENT_MAP;
  2307. /**
  2308. * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It
  2309. * adds shorthand functions that wrap around lengthy functions. For example:
  2310. * the `on` function is a wrapper around `addEventListener`.
  2311. *
  2312. * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget}
  2313. * @class EventTarget
  2314. */
  2315. class EventTarget$2 {
  2316. /**
  2317. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  2318. * function that will get called when an event with a certain name gets triggered.
  2319. *
  2320. * @param {string|string[]} type
  2321. * An event name or an array of event names.
  2322. *
  2323. * @param {Function} fn
  2324. * The function to call with `EventTarget`s
  2325. */
  2326. on(type, fn) {
  2327. // Remove the addEventListener alias before calling Events.on
  2328. // so we don't get into an infinite type loop
  2329. const ael = this.addEventListener;
  2330. this.addEventListener = () => {};
  2331. on(this, type, fn);
  2332. this.addEventListener = ael;
  2333. }
  2334. /**
  2335. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  2336. * This makes it so that the `event listener` will no longer get called when the
  2337. * named event happens.
  2338. *
  2339. * @param {string|string[]} type
  2340. * An event name or an array of event names.
  2341. *
  2342. * @param {Function} fn
  2343. * The function to remove.
  2344. */
  2345. off(type, fn) {
  2346. off(this, type, fn);
  2347. }
  2348. /**
  2349. * This function will add an `event listener` that gets triggered only once. After the
  2350. * first trigger it will get removed. This is like adding an `event listener`
  2351. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  2352. *
  2353. * @param {string|string[]} type
  2354. * An event name or an array of event names.
  2355. *
  2356. * @param {Function} fn
  2357. * The function to be called once for each event name.
  2358. */
  2359. one(type, fn) {
  2360. // Remove the addEventListener aliasing Events.on
  2361. // so we don't get into an infinite type loop
  2362. const ael = this.addEventListener;
  2363. this.addEventListener = () => {};
  2364. one(this, type, fn);
  2365. this.addEventListener = ael;
  2366. }
  2367. /**
  2368. * This function will add an `event listener` that gets triggered only once and is
  2369. * removed from all events. This is like adding an array of `event listener`s
  2370. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  2371. * first time it is triggered.
  2372. *
  2373. * @param {string|string[]} type
  2374. * An event name or an array of event names.
  2375. *
  2376. * @param {Function} fn
  2377. * The function to be called once for each event name.
  2378. */
  2379. any(type, fn) {
  2380. // Remove the addEventListener aliasing Events.on
  2381. // so we don't get into an infinite type loop
  2382. const ael = this.addEventListener;
  2383. this.addEventListener = () => {};
  2384. any(this, type, fn);
  2385. this.addEventListener = ael;
  2386. }
  2387. /**
  2388. * This function causes an event to happen. This will then cause any `event listeners`
  2389. * that are waiting for that event, to get called. If there are no `event listeners`
  2390. * for an event then nothing will happen.
  2391. *
  2392. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  2393. * Trigger will also call the `on` + `uppercaseEventName` function.
  2394. *
  2395. * Example:
  2396. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  2397. * `onClick` if it exists.
  2398. *
  2399. * @param {string|EventTarget~Event|Object} event
  2400. * The name of the event, an `Event`, or an object with a key of type set to
  2401. * an event name.
  2402. */
  2403. trigger(event) {
  2404. const type = event.type || event;
  2405. // deprecation
  2406. // In a future version we should default target to `this`
  2407. // similar to how we default the target to `elem` in
  2408. // `Events.trigger`. Right now the default `target` will be
  2409. // `document` due to the `Event.fixEvent` call.
  2410. if (typeof event === 'string') {
  2411. event = {
  2412. type
  2413. };
  2414. }
  2415. event = fixEvent(event);
  2416. if (this.allowedEvents_[type] && this['on' + type]) {
  2417. this['on' + type](event);
  2418. }
  2419. trigger(this, event);
  2420. }
  2421. queueTrigger(event) {
  2422. // only set up EVENT_MAP if it'll be used
  2423. if (!EVENT_MAP) {
  2424. EVENT_MAP = new Map();
  2425. }
  2426. const type = event.type || event;
  2427. let map = EVENT_MAP.get(this);
  2428. if (!map) {
  2429. map = new Map();
  2430. EVENT_MAP.set(this, map);
  2431. }
  2432. const oldTimeout = map.get(type);
  2433. map.delete(type);
  2434. window.clearTimeout(oldTimeout);
  2435. const timeout = window.setTimeout(() => {
  2436. map.delete(type);
  2437. // if we cleared out all timeouts for the current target, delete its map
  2438. if (map.size === 0) {
  2439. map = null;
  2440. EVENT_MAP.delete(this);
  2441. }
  2442. this.trigger(event);
  2443. }, 0);
  2444. map.set(type, timeout);
  2445. }
  2446. }
  2447. /**
  2448. * A Custom DOM event.
  2449. *
  2450. * @typedef {CustomEvent} Event
  2451. * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent}
  2452. */
  2453. /**
  2454. * All event listeners should follow the following format.
  2455. *
  2456. * @callback EventTarget~EventListener
  2457. * @this {EventTarget}
  2458. *
  2459. * @param {Event} event
  2460. * the event that triggered this function
  2461. *
  2462. * @param {Object} [hash]
  2463. * hash of data sent during the event
  2464. */
  2465. /**
  2466. * An object containing event names as keys and booleans as values.
  2467. *
  2468. * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger}
  2469. * will have extra functionality. See that function for more information.
  2470. *
  2471. * @property EventTarget.prototype.allowedEvents_
  2472. * @private
  2473. */
  2474. EventTarget$2.prototype.allowedEvents_ = {};
  2475. /**
  2476. * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic
  2477. * the standard DOM API.
  2478. *
  2479. * @function
  2480. * @see {@link EventTarget#on}
  2481. */
  2482. EventTarget$2.prototype.addEventListener = EventTarget$2.prototype.on;
  2483. /**
  2484. * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic
  2485. * the standard DOM API.
  2486. *
  2487. * @function
  2488. * @see {@link EventTarget#off}
  2489. */
  2490. EventTarget$2.prototype.removeEventListener = EventTarget$2.prototype.off;
  2491. /**
  2492. * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic
  2493. * the standard DOM API.
  2494. *
  2495. * @function
  2496. * @see {@link EventTarget#trigger}
  2497. */
  2498. EventTarget$2.prototype.dispatchEvent = EventTarget$2.prototype.trigger;
  2499. /**
  2500. * @file mixins/evented.js
  2501. * @module evented
  2502. */
  2503. const objName = obj => {
  2504. if (typeof obj.name === 'function') {
  2505. return obj.name();
  2506. }
  2507. if (typeof obj.name === 'string') {
  2508. return obj.name;
  2509. }
  2510. if (obj.name_) {
  2511. return obj.name_;
  2512. }
  2513. if (obj.constructor && obj.constructor.name) {
  2514. return obj.constructor.name;
  2515. }
  2516. return typeof obj;
  2517. };
  2518. /**
  2519. * Returns whether or not an object has had the evented mixin applied.
  2520. *
  2521. * @param {Object} object
  2522. * An object to test.
  2523. *
  2524. * @return {boolean}
  2525. * Whether or not the object appears to be evented.
  2526. */
  2527. const isEvented = object => object instanceof EventTarget$2 || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(k => typeof object[k] === 'function');
  2528. /**
  2529. * Adds a callback to run after the evented mixin applied.
  2530. *
  2531. * @param {Object} object
  2532. * An object to Add
  2533. * @param {Function} callback
  2534. * The callback to run.
  2535. */
  2536. const addEventedCallback = (target, callback) => {
  2537. if (isEvented(target)) {
  2538. callback();
  2539. } else {
  2540. if (!target.eventedCallbacks) {
  2541. target.eventedCallbacks = [];
  2542. }
  2543. target.eventedCallbacks.push(callback);
  2544. }
  2545. };
  2546. /**
  2547. * Whether a value is a valid event type - non-empty string or array.
  2548. *
  2549. * @private
  2550. * @param {string|Array} type
  2551. * The type value to test.
  2552. *
  2553. * @return {boolean}
  2554. * Whether or not the type is a valid event type.
  2555. */
  2556. const isValidEventType = type =>
  2557. // The regex here verifies that the `type` contains at least one non-
  2558. // whitespace character.
  2559. typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length;
  2560. /**
  2561. * Validates a value to determine if it is a valid event target. Throws if not.
  2562. *
  2563. * @private
  2564. * @throws {Error}
  2565. * If the target does not appear to be a valid event target.
  2566. *
  2567. * @param {Object} target
  2568. * The object to test.
  2569. *
  2570. * @param {Object} obj
  2571. * The evented object we are validating for
  2572. *
  2573. * @param {string} fnName
  2574. * The name of the evented mixin function that called this.
  2575. */
  2576. const validateTarget = (target, obj, fnName) => {
  2577. if (!target || !target.nodeName && !isEvented(target)) {
  2578. throw new Error(`Invalid target for ${objName(obj)}#${fnName}; must be a DOM node or evented object.`);
  2579. }
  2580. };
  2581. /**
  2582. * Validates a value to determine if it is a valid event target. Throws if not.
  2583. *
  2584. * @private
  2585. * @throws {Error}
  2586. * If the type does not appear to be a valid event type.
  2587. *
  2588. * @param {string|Array} type
  2589. * The type to test.
  2590. *
  2591. * @param {Object} obj
  2592. * The evented object we are validating for
  2593. *
  2594. * @param {string} fnName
  2595. * The name of the evented mixin function that called this.
  2596. */
  2597. const validateEventType = (type, obj, fnName) => {
  2598. if (!isValidEventType(type)) {
  2599. throw new Error(`Invalid event type for ${objName(obj)}#${fnName}; must be a non-empty string or array.`);
  2600. }
  2601. };
  2602. /**
  2603. * Validates a value to determine if it is a valid listener. Throws if not.
  2604. *
  2605. * @private
  2606. * @throws {Error}
  2607. * If the listener is not a function.
  2608. *
  2609. * @param {Function} listener
  2610. * The listener to test.
  2611. *
  2612. * @param {Object} obj
  2613. * The evented object we are validating for
  2614. *
  2615. * @param {string} fnName
  2616. * The name of the evented mixin function that called this.
  2617. */
  2618. const validateListener = (listener, obj, fnName) => {
  2619. if (typeof listener !== 'function') {
  2620. throw new Error(`Invalid listener for ${objName(obj)}#${fnName}; must be a function.`);
  2621. }
  2622. };
  2623. /**
  2624. * Takes an array of arguments given to `on()` or `one()`, validates them, and
  2625. * normalizes them into an object.
  2626. *
  2627. * @private
  2628. * @param {Object} self
  2629. * The evented object on which `on()` or `one()` was called. This
  2630. * object will be bound as the `this` value for the listener.
  2631. *
  2632. * @param {Array} args
  2633. * An array of arguments passed to `on()` or `one()`.
  2634. *
  2635. * @param {string} fnName
  2636. * The name of the evented mixin function that called this.
  2637. *
  2638. * @return {Object}
  2639. * An object containing useful values for `on()` or `one()` calls.
  2640. */
  2641. const normalizeListenArgs = (self, args, fnName) => {
  2642. // If the number of arguments is less than 3, the target is always the
  2643. // evented object itself.
  2644. const isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_;
  2645. let target;
  2646. let type;
  2647. let listener;
  2648. if (isTargetingSelf) {
  2649. target = self.eventBusEl_;
  2650. // Deal with cases where we got 3 arguments, but we are still listening to
  2651. // the evented object itself.
  2652. if (args.length >= 3) {
  2653. args.shift();
  2654. }
  2655. [type, listener] = args;
  2656. } else {
  2657. [target, type, listener] = args;
  2658. }
  2659. validateTarget(target, self, fnName);
  2660. validateEventType(type, self, fnName);
  2661. validateListener(listener, self, fnName);
  2662. listener = bind_(self, listener);
  2663. return {
  2664. isTargetingSelf,
  2665. target,
  2666. type,
  2667. listener
  2668. };
  2669. };
  2670. /**
  2671. * Adds the listener to the event type(s) on the target, normalizing for
  2672. * the type of target.
  2673. *
  2674. * @private
  2675. * @param {Element|Object} target
  2676. * A DOM node or evented object.
  2677. *
  2678. * @param {string} method
  2679. * The event binding method to use ("on" or "one").
  2680. *
  2681. * @param {string|Array} type
  2682. * One or more event type(s).
  2683. *
  2684. * @param {Function} listener
  2685. * A listener function.
  2686. */
  2687. const listen = (target, method, type, listener) => {
  2688. validateTarget(target, target, method);
  2689. if (target.nodeName) {
  2690. Events[method](target, type, listener);
  2691. } else {
  2692. target[method](type, listener);
  2693. }
  2694. };
  2695. /**
  2696. * Contains methods that provide event capabilities to an object which is passed
  2697. * to {@link module:evented|evented}.
  2698. *
  2699. * @mixin EventedMixin
  2700. */
  2701. const EventedMixin = {
  2702. /**
  2703. * Add a listener to an event (or events) on this object or another evented
  2704. * object.
  2705. *
  2706. * @param {string|Array|Element|Object} targetOrType
  2707. * If this is a string or array, it represents the event type(s)
  2708. * that will trigger the listener.
  2709. *
  2710. * Another evented object can be passed here instead, which will
  2711. * cause the listener to listen for events on _that_ object.
  2712. *
  2713. * In either case, the listener's `this` value will be bound to
  2714. * this object.
  2715. *
  2716. * @param {string|Array|Function} typeOrListener
  2717. * If the first argument was a string or array, this should be the
  2718. * listener function. Otherwise, this is a string or array of event
  2719. * type(s).
  2720. *
  2721. * @param {Function} [listener]
  2722. * If the first argument was another evented object, this will be
  2723. * the listener function.
  2724. */
  2725. on(...args) {
  2726. const {
  2727. isTargetingSelf,
  2728. target,
  2729. type,
  2730. listener
  2731. } = normalizeListenArgs(this, args, 'on');
  2732. listen(target, 'on', type, listener);
  2733. // If this object is listening to another evented object.
  2734. if (!isTargetingSelf) {
  2735. // If this object is disposed, remove the listener.
  2736. const removeListenerOnDispose = () => this.off(target, type, listener);
  2737. // Use the same function ID as the listener so we can remove it later it
  2738. // using the ID of the original listener.
  2739. removeListenerOnDispose.guid = listener.guid;
  2740. // Add a listener to the target's dispose event as well. This ensures
  2741. // that if the target is disposed BEFORE this object, we remove the
  2742. // removal listener that was just added. Otherwise, we create a memory leak.
  2743. const removeRemoverOnTargetDispose = () => this.off('dispose', removeListenerOnDispose);
  2744. // Use the same function ID as the listener so we can remove it later
  2745. // it using the ID of the original listener.
  2746. removeRemoverOnTargetDispose.guid = listener.guid;
  2747. listen(this, 'on', 'dispose', removeListenerOnDispose);
  2748. listen(target, 'on', 'dispose', removeRemoverOnTargetDispose);
  2749. }
  2750. },
  2751. /**
  2752. * Add a listener to an event (or events) on this object or another evented
  2753. * object. The listener will be called once per event and then removed.
  2754. *
  2755. * @param {string|Array|Element|Object} targetOrType
  2756. * If this is a string or array, it represents the event type(s)
  2757. * that will trigger the listener.
  2758. *
  2759. * Another evented object can be passed here instead, which will
  2760. * cause the listener to listen for events on _that_ object.
  2761. *
  2762. * In either case, the listener's `this` value will be bound to
  2763. * this object.
  2764. *
  2765. * @param {string|Array|Function} typeOrListener
  2766. * If the first argument was a string or array, this should be the
  2767. * listener function. Otherwise, this is a string or array of event
  2768. * type(s).
  2769. *
  2770. * @param {Function} [listener]
  2771. * If the first argument was another evented object, this will be
  2772. * the listener function.
  2773. */
  2774. one(...args) {
  2775. const {
  2776. isTargetingSelf,
  2777. target,
  2778. type,
  2779. listener
  2780. } = normalizeListenArgs(this, args, 'one');
  2781. // Targeting this evented object.
  2782. if (isTargetingSelf) {
  2783. listen(target, 'one', type, listener);
  2784. // Targeting another evented object.
  2785. } else {
  2786. // TODO: This wrapper is incorrect! It should only
  2787. // remove the wrapper for the event type that called it.
  2788. // Instead all listeners are removed on the first trigger!
  2789. // see https://github.com/videojs/video.js/issues/5962
  2790. const wrapper = (...largs) => {
  2791. this.off(target, type, wrapper);
  2792. listener.apply(null, largs);
  2793. };
  2794. // Use the same function ID as the listener so we can remove it later
  2795. // it using the ID of the original listener.
  2796. wrapper.guid = listener.guid;
  2797. listen(target, 'one', type, wrapper);
  2798. }
  2799. },
  2800. /**
  2801. * Add a listener to an event (or events) on this object or another evented
  2802. * object. The listener will only be called once for the first event that is triggered
  2803. * then removed.
  2804. *
  2805. * @param {string|Array|Element|Object} targetOrType
  2806. * If this is a string or array, it represents the event type(s)
  2807. * that will trigger the listener.
  2808. *
  2809. * Another evented object can be passed here instead, which will
  2810. * cause the listener to listen for events on _that_ object.
  2811. *
  2812. * In either case, the listener's `this` value will be bound to
  2813. * this object.
  2814. *
  2815. * @param {string|Array|Function} typeOrListener
  2816. * If the first argument was a string or array, this should be the
  2817. * listener function. Otherwise, this is a string or array of event
  2818. * type(s).
  2819. *
  2820. * @param {Function} [listener]
  2821. * If the first argument was another evented object, this will be
  2822. * the listener function.
  2823. */
  2824. any(...args) {
  2825. const {
  2826. isTargetingSelf,
  2827. target,
  2828. type,
  2829. listener
  2830. } = normalizeListenArgs(this, args, 'any');
  2831. // Targeting this evented object.
  2832. if (isTargetingSelf) {
  2833. listen(target, 'any', type, listener);
  2834. // Targeting another evented object.
  2835. } else {
  2836. const wrapper = (...largs) => {
  2837. this.off(target, type, wrapper);
  2838. listener.apply(null, largs);
  2839. };
  2840. // Use the same function ID as the listener so we can remove it later
  2841. // it using the ID of the original listener.
  2842. wrapper.guid = listener.guid;
  2843. listen(target, 'any', type, wrapper);
  2844. }
  2845. },
  2846. /**
  2847. * Removes listener(s) from event(s) on an evented object.
  2848. *
  2849. * @param {string|Array|Element|Object} [targetOrType]
  2850. * If this is a string or array, it represents the event type(s).
  2851. *
  2852. * Another evented object can be passed here instead, in which case
  2853. * ALL 3 arguments are _required_.
  2854. *
  2855. * @param {string|Array|Function} [typeOrListener]
  2856. * If the first argument was a string or array, this may be the
  2857. * listener function. Otherwise, this is a string or array of event
  2858. * type(s).
  2859. *
  2860. * @param {Function} [listener]
  2861. * If the first argument was another evented object, this will be
  2862. * the listener function; otherwise, _all_ listeners bound to the
  2863. * event type(s) will be removed.
  2864. */
  2865. off(targetOrType, typeOrListener, listener) {
  2866. // Targeting this evented object.
  2867. if (!targetOrType || isValidEventType(targetOrType)) {
  2868. off(this.eventBusEl_, targetOrType, typeOrListener);
  2869. // Targeting another evented object.
  2870. } else {
  2871. const target = targetOrType;
  2872. const type = typeOrListener;
  2873. // Fail fast and in a meaningful way!
  2874. validateTarget(target, this, 'off');
  2875. validateEventType(type, this, 'off');
  2876. validateListener(listener, this, 'off');
  2877. // Ensure there's at least a guid, even if the function hasn't been used
  2878. listener = bind_(this, listener);
  2879. // Remove the dispose listener on this evented object, which was given
  2880. // the same guid as the event listener in on().
  2881. this.off('dispose', listener);
  2882. if (target.nodeName) {
  2883. off(target, type, listener);
  2884. off(target, 'dispose', listener);
  2885. } else if (isEvented(target)) {
  2886. target.off(type, listener);
  2887. target.off('dispose', listener);
  2888. }
  2889. }
  2890. },
  2891. /**
  2892. * Fire an event on this evented object, causing its listeners to be called.
  2893. *
  2894. * @param {string|Object} event
  2895. * An event type or an object with a type property.
  2896. *
  2897. * @param {Object} [hash]
  2898. * An additional object to pass along to listeners.
  2899. *
  2900. * @return {boolean}
  2901. * Whether or not the default behavior was prevented.
  2902. */
  2903. trigger(event, hash) {
  2904. validateTarget(this.eventBusEl_, this, 'trigger');
  2905. const type = event && typeof event !== 'string' ? event.type : event;
  2906. if (!isValidEventType(type)) {
  2907. throw new Error(`Invalid event type for ${objName(this)}#trigger; ` + 'must be a non-empty string or object with a type key that has a non-empty value.');
  2908. }
  2909. return trigger(this.eventBusEl_, event, hash);
  2910. }
  2911. };
  2912. /**
  2913. * Applies {@link module:evented~EventedMixin|EventedMixin} to a target object.
  2914. *
  2915. * @param {Object} target
  2916. * The object to which to add event methods.
  2917. *
  2918. * @param {Object} [options={}]
  2919. * Options for customizing the mixin behavior.
  2920. *
  2921. * @param {string} [options.eventBusKey]
  2922. * By default, adds a `eventBusEl_` DOM element to the target object,
  2923. * which is used as an event bus. If the target object already has a
  2924. * DOM element that should be used, pass its key here.
  2925. *
  2926. * @return {Object}
  2927. * The target object.
  2928. */
  2929. function evented(target, options = {}) {
  2930. const {
  2931. eventBusKey
  2932. } = options;
  2933. // Set or create the eventBusEl_.
  2934. if (eventBusKey) {
  2935. if (!target[eventBusKey].nodeName) {
  2936. throw new Error(`The eventBusKey "${eventBusKey}" does not refer to an element.`);
  2937. }
  2938. target.eventBusEl_ = target[eventBusKey];
  2939. } else {
  2940. target.eventBusEl_ = createEl('span', {
  2941. className: 'vjs-event-bus'
  2942. });
  2943. }
  2944. Object.assign(target, EventedMixin);
  2945. if (target.eventedCallbacks) {
  2946. target.eventedCallbacks.forEach(callback => {
  2947. callback();
  2948. });
  2949. }
  2950. // When any evented object is disposed, it removes all its listeners.
  2951. target.on('dispose', () => {
  2952. target.off();
  2953. [target, target.el_, target.eventBusEl_].forEach(function (val) {
  2954. if (val && DomData.has(val)) {
  2955. DomData.delete(val);
  2956. }
  2957. });
  2958. window.setTimeout(() => {
  2959. target.eventBusEl_ = null;
  2960. }, 0);
  2961. });
  2962. return target;
  2963. }
  2964. /**
  2965. * @file mixins/stateful.js
  2966. * @module stateful
  2967. */
  2968. /**
  2969. * Contains methods that provide statefulness to an object which is passed
  2970. * to {@link module:stateful}.
  2971. *
  2972. * @mixin StatefulMixin
  2973. */
  2974. const StatefulMixin = {
  2975. /**
  2976. * A hash containing arbitrary keys and values representing the state of
  2977. * the object.
  2978. *
  2979. * @type {Object}
  2980. */
  2981. state: {},
  2982. /**
  2983. * Set the state of an object by mutating its
  2984. * {@link module:stateful~StatefulMixin.state|state} object in place.
  2985. *
  2986. * @fires module:stateful~StatefulMixin#statechanged
  2987. * @param {Object|Function} stateUpdates
  2988. * A new set of properties to shallow-merge into the plugin state.
  2989. * Can be a plain object or a function returning a plain object.
  2990. *
  2991. * @return {Object|undefined}
  2992. * An object containing changes that occurred. If no changes
  2993. * occurred, returns `undefined`.
  2994. */
  2995. setState(stateUpdates) {
  2996. // Support providing the `stateUpdates` state as a function.
  2997. if (typeof stateUpdates === 'function') {
  2998. stateUpdates = stateUpdates();
  2999. }
  3000. let changes;
  3001. each(stateUpdates, (value, key) => {
  3002. // Record the change if the value is different from what's in the
  3003. // current state.
  3004. if (this.state[key] !== value) {
  3005. changes = changes || {};
  3006. changes[key] = {
  3007. from: this.state[key],
  3008. to: value
  3009. };
  3010. }
  3011. this.state[key] = value;
  3012. });
  3013. // Only trigger "statechange" if there were changes AND we have a trigger
  3014. // function. This allows us to not require that the target object be an
  3015. // evented object.
  3016. if (changes && isEvented(this)) {
  3017. /**
  3018. * An event triggered on an object that is both
  3019. * {@link module:stateful|stateful} and {@link module:evented|evented}
  3020. * indicating that its state has changed.
  3021. *
  3022. * @event module:stateful~StatefulMixin#statechanged
  3023. * @type {Object}
  3024. * @property {Object} changes
  3025. * A hash containing the properties that were changed and
  3026. * the values they were changed `from` and `to`.
  3027. */
  3028. this.trigger({
  3029. changes,
  3030. type: 'statechanged'
  3031. });
  3032. }
  3033. return changes;
  3034. }
  3035. };
  3036. /**
  3037. * Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target
  3038. * object.
  3039. *
  3040. * If the target object is {@link module:evented|evented} and has a
  3041. * `handleStateChanged` method, that method will be automatically bound to the
  3042. * `statechanged` event on itself.
  3043. *
  3044. * @param {Object} target
  3045. * The object to be made stateful.
  3046. *
  3047. * @param {Object} [defaultState]
  3048. * A default set of properties to populate the newly-stateful object's
  3049. * `state` property.
  3050. *
  3051. * @return {Object}
  3052. * Returns the `target`.
  3053. */
  3054. function stateful(target, defaultState) {
  3055. Object.assign(target, StatefulMixin);
  3056. // This happens after the mixing-in because we need to replace the `state`
  3057. // added in that step.
  3058. target.state = Object.assign({}, target.state, defaultState);
  3059. // Auto-bind the `handleStateChanged` method of the target object if it exists.
  3060. if (typeof target.handleStateChanged === 'function' && isEvented(target)) {
  3061. target.on('statechanged', target.handleStateChanged);
  3062. }
  3063. return target;
  3064. }
  3065. /**
  3066. * @file str.js
  3067. * @module to-lower-case
  3068. */
  3069. /**
  3070. * Lowercase the first letter of a string.
  3071. *
  3072. * @param {string} string
  3073. * String to be lowercased
  3074. *
  3075. * @return {string}
  3076. * The string with a lowercased first letter
  3077. */
  3078. const toLowerCase = function (string) {
  3079. if (typeof string !== 'string') {
  3080. return string;
  3081. }
  3082. return string.replace(/./, w => w.toLowerCase());
  3083. };
  3084. /**
  3085. * Uppercase the first letter of a string.
  3086. *
  3087. * @param {string} string
  3088. * String to be uppercased
  3089. *
  3090. * @return {string}
  3091. * The string with an uppercased first letter
  3092. */
  3093. const toTitleCase$1 = function (string) {
  3094. if (typeof string !== 'string') {
  3095. return string;
  3096. }
  3097. return string.replace(/./, w => w.toUpperCase());
  3098. };
  3099. /**
  3100. * Compares the TitleCase versions of the two strings for equality.
  3101. *
  3102. * @param {string} str1
  3103. * The first string to compare
  3104. *
  3105. * @param {string} str2
  3106. * The second string to compare
  3107. *
  3108. * @return {boolean}
  3109. * Whether the TitleCase versions of the strings are equal
  3110. */
  3111. const titleCaseEquals = function (str1, str2) {
  3112. return toTitleCase$1(str1) === toTitleCase$1(str2);
  3113. };
  3114. var Str = /*#__PURE__*/Object.freeze({
  3115. __proto__: null,
  3116. toLowerCase: toLowerCase,
  3117. toTitleCase: toTitleCase$1,
  3118. titleCaseEquals: titleCaseEquals
  3119. });
  3120. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  3121. function unwrapExports (x) {
  3122. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  3123. }
  3124. function createCommonjsModule(fn, module) {
  3125. return module = { exports: {} }, fn(module, module.exports), module.exports;
  3126. }
  3127. var keycode = createCommonjsModule(function (module, exports) {
  3128. // Source: http://jsfiddle.net/vWx8V/
  3129. // http://stackoverflow.com/questions/5603195/full-list-of-javascript-keycodes
  3130. /**
  3131. * Conenience method returns corresponding value for given keyName or keyCode.
  3132. *
  3133. * @param {Mixed} keyCode {Number} or keyName {String}
  3134. * @return {Mixed}
  3135. * @api public
  3136. */
  3137. function keyCode(searchInput) {
  3138. // Keyboard Events
  3139. if (searchInput && 'object' === typeof searchInput) {
  3140. var hasKeyCode = searchInput.which || searchInput.keyCode || searchInput.charCode;
  3141. if (hasKeyCode) searchInput = hasKeyCode;
  3142. }
  3143. // Numbers
  3144. if ('number' === typeof searchInput) return names[searchInput];
  3145. // Everything else (cast to string)
  3146. var search = String(searchInput);
  3147. // check codes
  3148. var foundNamedKey = codes[search.toLowerCase()];
  3149. if (foundNamedKey) return foundNamedKey;
  3150. // check aliases
  3151. var foundNamedKey = aliases[search.toLowerCase()];
  3152. if (foundNamedKey) return foundNamedKey;
  3153. // weird character?
  3154. if (search.length === 1) return search.charCodeAt(0);
  3155. return undefined;
  3156. }
  3157. /**
  3158. * Compares a keyboard event with a given keyCode or keyName.
  3159. *
  3160. * @param {Event} event Keyboard event that should be tested
  3161. * @param {Mixed} keyCode {Number} or keyName {String}
  3162. * @return {Boolean}
  3163. * @api public
  3164. */
  3165. keyCode.isEventKey = function isEventKey(event, nameOrCode) {
  3166. if (event && 'object' === typeof event) {
  3167. var keyCode = event.which || event.keyCode || event.charCode;
  3168. if (keyCode === null || keyCode === undefined) {
  3169. return false;
  3170. }
  3171. if (typeof nameOrCode === 'string') {
  3172. // check codes
  3173. var foundNamedKey = codes[nameOrCode.toLowerCase()];
  3174. if (foundNamedKey) {
  3175. return foundNamedKey === keyCode;
  3176. }
  3177. // check aliases
  3178. var foundNamedKey = aliases[nameOrCode.toLowerCase()];
  3179. if (foundNamedKey) {
  3180. return foundNamedKey === keyCode;
  3181. }
  3182. } else if (typeof nameOrCode === 'number') {
  3183. return nameOrCode === keyCode;
  3184. }
  3185. return false;
  3186. }
  3187. };
  3188. exports = module.exports = keyCode;
  3189. /**
  3190. * Get by name
  3191. *
  3192. * exports.code['enter'] // => 13
  3193. */
  3194. var codes = exports.code = exports.codes = {
  3195. 'backspace': 8,
  3196. 'tab': 9,
  3197. 'enter': 13,
  3198. 'shift': 16,
  3199. 'ctrl': 17,
  3200. 'alt': 18,
  3201. 'pause/break': 19,
  3202. 'caps lock': 20,
  3203. 'esc': 27,
  3204. 'space': 32,
  3205. 'page up': 33,
  3206. 'page down': 34,
  3207. 'end': 35,
  3208. 'home': 36,
  3209. 'left': 37,
  3210. 'up': 38,
  3211. 'right': 39,
  3212. 'down': 40,
  3213. 'insert': 45,
  3214. 'delete': 46,
  3215. 'command': 91,
  3216. 'left command': 91,
  3217. 'right command': 93,
  3218. 'numpad *': 106,
  3219. 'numpad +': 107,
  3220. 'numpad -': 109,
  3221. 'numpad .': 110,
  3222. 'numpad /': 111,
  3223. 'num lock': 144,
  3224. 'scroll lock': 145,
  3225. 'my computer': 182,
  3226. 'my calculator': 183,
  3227. ';': 186,
  3228. '=': 187,
  3229. ',': 188,
  3230. '-': 189,
  3231. '.': 190,
  3232. '/': 191,
  3233. '`': 192,
  3234. '[': 219,
  3235. '\\': 220,
  3236. ']': 221,
  3237. "'": 222
  3238. };
  3239. // Helper aliases
  3240. var aliases = exports.aliases = {
  3241. 'windows': 91,
  3242. '⇧': 16,
  3243. '⌥': 18,
  3244. '⌃': 17,
  3245. '⌘': 91,
  3246. 'ctl': 17,
  3247. 'control': 17,
  3248. 'option': 18,
  3249. 'pause': 19,
  3250. 'break': 19,
  3251. 'caps': 20,
  3252. 'return': 13,
  3253. 'escape': 27,
  3254. 'spc': 32,
  3255. 'spacebar': 32,
  3256. 'pgup': 33,
  3257. 'pgdn': 34,
  3258. 'ins': 45,
  3259. 'del': 46,
  3260. 'cmd': 91
  3261. };
  3262. /*!
  3263. * Programatically add the following
  3264. */
  3265. // lower case chars
  3266. for (i = 97; i < 123; i++) codes[String.fromCharCode(i)] = i - 32;
  3267. // numbers
  3268. for (var i = 48; i < 58; i++) codes[i - 48] = i;
  3269. // function keys
  3270. for (i = 1; i < 13; i++) codes['f' + i] = i + 111;
  3271. // numpad keys
  3272. for (i = 0; i < 10; i++) codes['numpad ' + i] = i + 96;
  3273. /**
  3274. * Get by code
  3275. *
  3276. * exports.name[13] // => 'Enter'
  3277. */
  3278. var names = exports.names = exports.title = {}; // title for backward compat
  3279. // Create reverse mapping
  3280. for (i in codes) names[codes[i]] = i;
  3281. // Add aliases
  3282. for (var alias in aliases) {
  3283. codes[alias] = aliases[alias];
  3284. }
  3285. });
  3286. keycode.code;
  3287. keycode.codes;
  3288. keycode.aliases;
  3289. keycode.names;
  3290. keycode.title;
  3291. /**
  3292. * Player Component - Base class for all UI objects
  3293. *
  3294. * @file component.js
  3295. */
  3296. /**
  3297. * Base class for all UI Components.
  3298. * Components are UI objects which represent both a javascript object and an element
  3299. * in the DOM. They can be children of other components, and can have
  3300. * children themselves.
  3301. *
  3302. * Components can also use methods from {@link EventTarget}
  3303. */
  3304. class Component$1 {
  3305. /**
  3306. * A callback that is called when a component is ready. Does not have any
  3307. * parameters and any callback value will be ignored.
  3308. *
  3309. * @callback ReadyCallback
  3310. * @this Component
  3311. */
  3312. /**
  3313. * Creates an instance of this class.
  3314. *
  3315. * @param { import('./player').default } player
  3316. * The `Player` that this class should be attached to.
  3317. *
  3318. * @param {Object} [options]
  3319. * The key/value store of component options.
  3320. *
  3321. * @param {Object[]} [options.children]
  3322. * An array of children objects to initialize this component with. Children objects have
  3323. * a name property that will be used if more than one component of the same type needs to be
  3324. * added.
  3325. *
  3326. * @param {string} [options.className]
  3327. * A class or space separated list of classes to add the component
  3328. *
  3329. * @param {ReadyCallback} [ready]
  3330. * Function that gets called when the `Component` is ready.
  3331. */
  3332. constructor(player, options, ready) {
  3333. // The component might be the player itself and we can't pass `this` to super
  3334. if (!player && this.play) {
  3335. this.player_ = player = this; // eslint-disable-line
  3336. } else {
  3337. this.player_ = player;
  3338. }
  3339. this.isDisposed_ = false;
  3340. // Hold the reference to the parent component via `addChild` method
  3341. this.parentComponent_ = null;
  3342. // Make a copy of prototype.options_ to protect against overriding defaults
  3343. this.options_ = merge$2({}, this.options_);
  3344. // Updated options with supplied options
  3345. options = this.options_ = merge$2(this.options_, options);
  3346. // Get ID from options or options element if one is supplied
  3347. this.id_ = options.id || options.el && options.el.id;
  3348. // If there was no ID from the options, generate one
  3349. if (!this.id_) {
  3350. // Don't require the player ID function in the case of mock players
  3351. const id = player && player.id && player.id() || 'no_player';
  3352. this.id_ = `${id}_component_${newGUID()}`;
  3353. }
  3354. this.name_ = options.name || null;
  3355. // Create element if one wasn't provided in options
  3356. if (options.el) {
  3357. this.el_ = options.el;
  3358. } else if (options.createEl !== false) {
  3359. this.el_ = this.createEl();
  3360. }
  3361. if (options.className && this.el_) {
  3362. options.className.split(' ').forEach(c => this.addClass(c));
  3363. }
  3364. // Remove the placeholder event methods. If the component is evented, the
  3365. // real methods are added next
  3366. ['on', 'off', 'one', 'any', 'trigger'].forEach(fn => {
  3367. this[fn] = undefined;
  3368. });
  3369. // if evented is anything except false, we want to mixin in evented
  3370. if (options.evented !== false) {
  3371. // Make this an evented object and use `el_`, if available, as its event bus
  3372. evented(this, {
  3373. eventBusKey: this.el_ ? 'el_' : null
  3374. });
  3375. this.handleLanguagechange = this.handleLanguagechange.bind(this);
  3376. this.on(this.player_, 'languagechange', this.handleLanguagechange);
  3377. }
  3378. stateful(this, this.constructor.defaultState);
  3379. this.children_ = [];
  3380. this.childIndex_ = {};
  3381. this.childNameIndex_ = {};
  3382. this.setTimeoutIds_ = new Set();
  3383. this.setIntervalIds_ = new Set();
  3384. this.rafIds_ = new Set();
  3385. this.namedRafs_ = new Map();
  3386. this.clearingTimersOnDispose_ = false;
  3387. // Add any child components in options
  3388. if (options.initChildren !== false) {
  3389. this.initChildren();
  3390. }
  3391. // Don't want to trigger ready here or it will go before init is actually
  3392. // finished for all children that run this constructor
  3393. this.ready(ready);
  3394. if (options.reportTouchActivity !== false) {
  3395. this.enableTouchActivity();
  3396. }
  3397. }
  3398. // `on`, `off`, `one`, `any` and `trigger` are here so tsc includes them in definitions.
  3399. // They are replaced or removed in the constructor
  3400. /**
  3401. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  3402. * function that will get called when an event with a certain name gets triggered.
  3403. *
  3404. * @param {string|string[]} type
  3405. * An event name or an array of event names.
  3406. *
  3407. * @param {Function} fn
  3408. * The function to call with `EventTarget`s
  3409. */
  3410. on(type, fn) {}
  3411. /**
  3412. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  3413. * This makes it so that the `event listener` will no longer get called when the
  3414. * named event happens.
  3415. *
  3416. * @param {string|string[]} type
  3417. * An event name or an array of event names.
  3418. *
  3419. * @param {Function} fn
  3420. * The function to remove.
  3421. */
  3422. off(type, fn) {}
  3423. /**
  3424. * This function will add an `event listener` that gets triggered only once. After the
  3425. * first trigger it will get removed. This is like adding an `event listener`
  3426. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  3427. *
  3428. * @param {string|string[]} type
  3429. * An event name or an array of event names.
  3430. *
  3431. * @param {Function} fn
  3432. * The function to be called once for each event name.
  3433. */
  3434. one(type, fn) {}
  3435. /**
  3436. * This function will add an `event listener` that gets triggered only once and is
  3437. * removed from all events. This is like adding an array of `event listener`s
  3438. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  3439. * first time it is triggered.
  3440. *
  3441. * @param {string|string[]} type
  3442. * An event name or an array of event names.
  3443. *
  3444. * @param {Function} fn
  3445. * The function to be called once for each event name.
  3446. */
  3447. any(type, fn) {}
  3448. /**
  3449. * This function causes an event to happen. This will then cause any `event listeners`
  3450. * that are waiting for that event, to get called. If there are no `event listeners`
  3451. * for an event then nothing will happen.
  3452. *
  3453. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  3454. * Trigger will also call the `on` + `uppercaseEventName` function.
  3455. *
  3456. * Example:
  3457. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  3458. * `onClick` if it exists.
  3459. *
  3460. * @param {string|Event|Object} event
  3461. * The name of the event, an `Event`, or an object with a key of type set to
  3462. * an event name.
  3463. */
  3464. trigger(event) {}
  3465. /**
  3466. * Dispose of the `Component` and all child components.
  3467. *
  3468. * @fires Component#dispose
  3469. *
  3470. * @param {Object} options
  3471. * @param {Element} options.originalEl element with which to replace player element
  3472. */
  3473. dispose(options = {}) {
  3474. // Bail out if the component has already been disposed.
  3475. if (this.isDisposed_) {
  3476. return;
  3477. }
  3478. if (this.readyQueue_) {
  3479. this.readyQueue_.length = 0;
  3480. }
  3481. /**
  3482. * Triggered when a `Component` is disposed.
  3483. *
  3484. * @event Component#dispose
  3485. * @type {Event}
  3486. *
  3487. * @property {boolean} [bubbles=false]
  3488. * set to false so that the dispose event does not
  3489. * bubble up
  3490. */
  3491. this.trigger({
  3492. type: 'dispose',
  3493. bubbles: false
  3494. });
  3495. this.isDisposed_ = true;
  3496. // Dispose all children.
  3497. if (this.children_) {
  3498. for (let i = this.children_.length - 1; i >= 0; i--) {
  3499. if (this.children_[i].dispose) {
  3500. this.children_[i].dispose();
  3501. }
  3502. }
  3503. }
  3504. // Delete child references
  3505. this.children_ = null;
  3506. this.childIndex_ = null;
  3507. this.childNameIndex_ = null;
  3508. this.parentComponent_ = null;
  3509. if (this.el_) {
  3510. // Remove element from DOM
  3511. if (this.el_.parentNode) {
  3512. if (options.restoreEl) {
  3513. this.el_.parentNode.replaceChild(options.restoreEl, this.el_);
  3514. } else {
  3515. this.el_.parentNode.removeChild(this.el_);
  3516. }
  3517. }
  3518. this.el_ = null;
  3519. }
  3520. // remove reference to the player after disposing of the element
  3521. this.player_ = null;
  3522. }
  3523. /**
  3524. * Determine whether or not this component has been disposed.
  3525. *
  3526. * @return {boolean}
  3527. * If the component has been disposed, will be `true`. Otherwise, `false`.
  3528. */
  3529. isDisposed() {
  3530. return Boolean(this.isDisposed_);
  3531. }
  3532. /**
  3533. * Return the {@link Player} that the `Component` has attached to.
  3534. *
  3535. * @return { import('./player').default }
  3536. * The player that this `Component` has attached to.
  3537. */
  3538. player() {
  3539. return this.player_;
  3540. }
  3541. /**
  3542. * Deep merge of options objects with new options.
  3543. * > Note: When both `obj` and `options` contain properties whose values are objects.
  3544. * The two properties get merged using {@link module:obj.merge}
  3545. *
  3546. * @param {Object} obj
  3547. * The object that contains new options.
  3548. *
  3549. * @return {Object}
  3550. * A new object of `this.options_` and `obj` merged together.
  3551. */
  3552. options(obj) {
  3553. if (!obj) {
  3554. return this.options_;
  3555. }
  3556. this.options_ = merge$2(this.options_, obj);
  3557. return this.options_;
  3558. }
  3559. /**
  3560. * Get the `Component`s DOM element
  3561. *
  3562. * @return {Element}
  3563. * The DOM element for this `Component`.
  3564. */
  3565. el() {
  3566. return this.el_;
  3567. }
  3568. /**
  3569. * Create the `Component`s DOM element.
  3570. *
  3571. * @param {string} [tagName]
  3572. * Element's DOM node type. e.g. 'div'
  3573. *
  3574. * @param {Object} [properties]
  3575. * An object of properties that should be set.
  3576. *
  3577. * @param {Object} [attributes]
  3578. * An object of attributes that should be set.
  3579. *
  3580. * @return {Element}
  3581. * The element that gets created.
  3582. */
  3583. createEl(tagName, properties, attributes) {
  3584. return createEl(tagName, properties, attributes);
  3585. }
  3586. /**
  3587. * Localize a string given the string in english.
  3588. *
  3589. * If tokens are provided, it'll try and run a simple token replacement on the provided string.
  3590. * The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.
  3591. *
  3592. * If a `defaultValue` is provided, it'll use that over `string`,
  3593. * if a value isn't found in provided language files.
  3594. * This is useful if you want to have a descriptive key for token replacement
  3595. * but have a succinct localized string and not require `en.json` to be included.
  3596. *
  3597. * Currently, it is used for the progress bar timing.
  3598. * ```js
  3599. * {
  3600. * "progress bar timing: currentTime={1} duration={2}": "{1} of {2}"
  3601. * }
  3602. * ```
  3603. * It is then used like so:
  3604. * ```js
  3605. * this.localize('progress bar timing: currentTime={1} duration{2}',
  3606. * [this.player_.currentTime(), this.player_.duration()],
  3607. * '{1} of {2}');
  3608. * ```
  3609. *
  3610. * Which outputs something like: `01:23 of 24:56`.
  3611. *
  3612. *
  3613. * @param {string} string
  3614. * The string to localize and the key to lookup in the language files.
  3615. * @param {string[]} [tokens]
  3616. * If the current item has token replacements, provide the tokens here.
  3617. * @param {string} [defaultValue]
  3618. * Defaults to `string`. Can be a default value to use for token replacement
  3619. * if the lookup key is needed to be separate.
  3620. *
  3621. * @return {string}
  3622. * The localized string or if no localization exists the english string.
  3623. */
  3624. localize(string, tokens, defaultValue = string) {
  3625. const code = this.player_.language && this.player_.language();
  3626. const languages = this.player_.languages && this.player_.languages();
  3627. const language = languages && languages[code];
  3628. const primaryCode = code && code.split('-')[0];
  3629. const primaryLang = languages && languages[primaryCode];
  3630. let localizedString = defaultValue;
  3631. if (language && language[string]) {
  3632. localizedString = language[string];
  3633. } else if (primaryLang && primaryLang[string]) {
  3634. localizedString = primaryLang[string];
  3635. }
  3636. if (tokens) {
  3637. localizedString = localizedString.replace(/\{(\d+)\}/g, function (match, index) {
  3638. const value = tokens[index - 1];
  3639. let ret = value;
  3640. if (typeof value === 'undefined') {
  3641. ret = match;
  3642. }
  3643. return ret;
  3644. });
  3645. }
  3646. return localizedString;
  3647. }
  3648. /**
  3649. * Handles language change for the player in components. Should be overridden by sub-components.
  3650. *
  3651. * @abstract
  3652. */
  3653. handleLanguagechange() {}
  3654. /**
  3655. * Return the `Component`s DOM element. This is where children get inserted.
  3656. * This will usually be the the same as the element returned in {@link Component#el}.
  3657. *
  3658. * @return {Element}
  3659. * The content element for this `Component`.
  3660. */
  3661. contentEl() {
  3662. return this.contentEl_ || this.el_;
  3663. }
  3664. /**
  3665. * Get this `Component`s ID
  3666. *
  3667. * @return {string}
  3668. * The id of this `Component`
  3669. */
  3670. id() {
  3671. return this.id_;
  3672. }
  3673. /**
  3674. * Get the `Component`s name. The name gets used to reference the `Component`
  3675. * and is set during registration.
  3676. *
  3677. * @return {string}
  3678. * The name of this `Component`.
  3679. */
  3680. name() {
  3681. return this.name_;
  3682. }
  3683. /**
  3684. * Get an array of all child components
  3685. *
  3686. * @return {Array}
  3687. * The children
  3688. */
  3689. children() {
  3690. return this.children_;
  3691. }
  3692. /**
  3693. * Returns the child `Component` with the given `id`.
  3694. *
  3695. * @param {string} id
  3696. * The id of the child `Component` to get.
  3697. *
  3698. * @return {Component|undefined}
  3699. * The child `Component` with the given `id` or undefined.
  3700. */
  3701. getChildById(id) {
  3702. return this.childIndex_[id];
  3703. }
  3704. /**
  3705. * Returns the child `Component` with the given `name`.
  3706. *
  3707. * @param {string} name
  3708. * The name of the child `Component` to get.
  3709. *
  3710. * @return {Component|undefined}
  3711. * The child `Component` with the given `name` or undefined.
  3712. */
  3713. getChild(name) {
  3714. if (!name) {
  3715. return;
  3716. }
  3717. return this.childNameIndex_[name];
  3718. }
  3719. /**
  3720. * Returns the descendant `Component` following the givent
  3721. * descendant `names`. For instance ['foo', 'bar', 'baz'] would
  3722. * try to get 'foo' on the current component, 'bar' on the 'foo'
  3723. * component and 'baz' on the 'bar' component and return undefined
  3724. * if any of those don't exist.
  3725. *
  3726. * @param {...string[]|...string} names
  3727. * The name of the child `Component` to get.
  3728. *
  3729. * @return {Component|undefined}
  3730. * The descendant `Component` following the given descendant
  3731. * `names` or undefined.
  3732. */
  3733. getDescendant(...names) {
  3734. // flatten array argument into the main array
  3735. names = names.reduce((acc, n) => acc.concat(n), []);
  3736. let currentChild = this;
  3737. for (let i = 0; i < names.length; i++) {
  3738. currentChild = currentChild.getChild(names[i]);
  3739. if (!currentChild || !currentChild.getChild) {
  3740. return;
  3741. }
  3742. }
  3743. return currentChild;
  3744. }
  3745. /**
  3746. * Add a child `Component` inside the current `Component`.
  3747. *
  3748. *
  3749. * @param {string|Component} child
  3750. * The name or instance of a child to add.
  3751. *
  3752. * @param {Object} [options={}]
  3753. * The key/value store of options that will get passed to children of
  3754. * the child.
  3755. *
  3756. * @param {number} [index=this.children_.length]
  3757. * The index to attempt to add a child into.
  3758. *
  3759. * @return {Component}
  3760. * The `Component` that gets added as a child. When using a string the
  3761. * `Component` will get created by this process.
  3762. */
  3763. addChild(child, options = {}, index = this.children_.length) {
  3764. let component;
  3765. let componentName;
  3766. // If child is a string, create component with options
  3767. if (typeof child === 'string') {
  3768. componentName = toTitleCase$1(child);
  3769. const componentClassName = options.componentClass || componentName;
  3770. // Set name through options
  3771. options.name = componentName;
  3772. // Create a new object & element for this controls set
  3773. // If there's no .player_, this is a player
  3774. const ComponentClass = Component$1.getComponent(componentClassName);
  3775. if (!ComponentClass) {
  3776. throw new Error(`Component ${componentClassName} does not exist`);
  3777. }
  3778. // data stored directly on the videojs object may be
  3779. // misidentified as a component to retain
  3780. // backwards-compatibility with 4.x. check to make sure the
  3781. // component class can be instantiated.
  3782. if (typeof ComponentClass !== 'function') {
  3783. return null;
  3784. }
  3785. component = new ComponentClass(this.player_ || this, options);
  3786. // child is a component instance
  3787. } else {
  3788. component = child;
  3789. }
  3790. if (component.parentComponent_) {
  3791. component.parentComponent_.removeChild(component);
  3792. }
  3793. this.children_.splice(index, 0, component);
  3794. component.parentComponent_ = this;
  3795. if (typeof component.id === 'function') {
  3796. this.childIndex_[component.id()] = component;
  3797. }
  3798. // If a name wasn't used to create the component, check if we can use the
  3799. // name function of the component
  3800. componentName = componentName || component.name && toTitleCase$1(component.name());
  3801. if (componentName) {
  3802. this.childNameIndex_[componentName] = component;
  3803. this.childNameIndex_[toLowerCase(componentName)] = component;
  3804. }
  3805. // Add the UI object's element to the container div (box)
  3806. // Having an element is not required
  3807. if (typeof component.el === 'function' && component.el()) {
  3808. // If inserting before a component, insert before that component's element
  3809. let refNode = null;
  3810. if (this.children_[index + 1]) {
  3811. // Most children are components, but the video tech is an HTML element
  3812. if (this.children_[index + 1].el_) {
  3813. refNode = this.children_[index + 1].el_;
  3814. } else if (isEl(this.children_[index + 1])) {
  3815. refNode = this.children_[index + 1];
  3816. }
  3817. }
  3818. this.contentEl().insertBefore(component.el(), refNode);
  3819. }
  3820. // Return so it can stored on parent object if desired.
  3821. return component;
  3822. }
  3823. /**
  3824. * Remove a child `Component` from this `Component`s list of children. Also removes
  3825. * the child `Component`s element from this `Component`s element.
  3826. *
  3827. * @param {Component} component
  3828. * The child `Component` to remove.
  3829. */
  3830. removeChild(component) {
  3831. if (typeof component === 'string') {
  3832. component = this.getChild(component);
  3833. }
  3834. if (!component || !this.children_) {
  3835. return;
  3836. }
  3837. let childFound = false;
  3838. for (let i = this.children_.length - 1; i >= 0; i--) {
  3839. if (this.children_[i] === component) {
  3840. childFound = true;
  3841. this.children_.splice(i, 1);
  3842. break;
  3843. }
  3844. }
  3845. if (!childFound) {
  3846. return;
  3847. }
  3848. component.parentComponent_ = null;
  3849. this.childIndex_[component.id()] = null;
  3850. this.childNameIndex_[toTitleCase$1(component.name())] = null;
  3851. this.childNameIndex_[toLowerCase(component.name())] = null;
  3852. const compEl = component.el();
  3853. if (compEl && compEl.parentNode === this.contentEl()) {
  3854. this.contentEl().removeChild(component.el());
  3855. }
  3856. }
  3857. /**
  3858. * Add and initialize default child `Component`s based upon options.
  3859. */
  3860. initChildren() {
  3861. const children = this.options_.children;
  3862. if (children) {
  3863. // `this` is `parent`
  3864. const parentOptions = this.options_;
  3865. const handleAdd = child => {
  3866. const name = child.name;
  3867. let opts = child.opts;
  3868. // Allow options for children to be set at the parent options
  3869. // e.g. videojs(id, { controlBar: false });
  3870. // instead of videojs(id, { children: { controlBar: false });
  3871. if (parentOptions[name] !== undefined) {
  3872. opts = parentOptions[name];
  3873. }
  3874. // Allow for disabling default components
  3875. // e.g. options['children']['posterImage'] = false
  3876. if (opts === false) {
  3877. return;
  3878. }
  3879. // Allow options to be passed as a simple boolean if no configuration
  3880. // is necessary.
  3881. if (opts === true) {
  3882. opts = {};
  3883. }
  3884. // We also want to pass the original player options
  3885. // to each component as well so they don't need to
  3886. // reach back into the player for options later.
  3887. opts.playerOptions = this.options_.playerOptions;
  3888. // Create and add the child component.
  3889. // Add a direct reference to the child by name on the parent instance.
  3890. // If two of the same component are used, different names should be supplied
  3891. // for each
  3892. const newChild = this.addChild(name, opts);
  3893. if (newChild) {
  3894. this[name] = newChild;
  3895. }
  3896. };
  3897. // Allow for an array of children details to passed in the options
  3898. let workingChildren;
  3899. const Tech = Component$1.getComponent('Tech');
  3900. if (Array.isArray(children)) {
  3901. workingChildren = children;
  3902. } else {
  3903. workingChildren = Object.keys(children);
  3904. }
  3905. workingChildren
  3906. // children that are in this.options_ but also in workingChildren would
  3907. // give us extra children we do not want. So, we want to filter them out.
  3908. .concat(Object.keys(this.options_).filter(function (child) {
  3909. return !workingChildren.some(function (wchild) {
  3910. if (typeof wchild === 'string') {
  3911. return child === wchild;
  3912. }
  3913. return child === wchild.name;
  3914. });
  3915. })).map(child => {
  3916. let name;
  3917. let opts;
  3918. if (typeof child === 'string') {
  3919. name = child;
  3920. opts = children[name] || this.options_[name] || {};
  3921. } else {
  3922. name = child.name;
  3923. opts = child;
  3924. }
  3925. return {
  3926. name,
  3927. opts
  3928. };
  3929. }).filter(child => {
  3930. // we have to make sure that child.name isn't in the techOrder since
  3931. // techs are registered as Components but can't aren't compatible
  3932. // See https://github.com/videojs/video.js/issues/2772
  3933. const c = Component$1.getComponent(child.opts.componentClass || toTitleCase$1(child.name));
  3934. return c && !Tech.isTech(c);
  3935. }).forEach(handleAdd);
  3936. }
  3937. }
  3938. /**
  3939. * Builds the default DOM class name. Should be overridden by sub-components.
  3940. *
  3941. * @return {string}
  3942. * The DOM class name for this object.
  3943. *
  3944. * @abstract
  3945. */
  3946. buildCSSClass() {
  3947. // Child classes can include a function that does:
  3948. // return 'CLASS NAME' + this._super();
  3949. return '';
  3950. }
  3951. /**
  3952. * Bind a listener to the component's ready state.
  3953. * Different from event listeners in that if the ready event has already happened
  3954. * it will trigger the function immediately.
  3955. *
  3956. * @param {ReadyCallback} fn
  3957. * Function that gets called when the `Component` is ready.
  3958. *
  3959. * @return {Component}
  3960. * Returns itself; method can be chained.
  3961. */
  3962. ready(fn, sync = false) {
  3963. if (!fn) {
  3964. return;
  3965. }
  3966. if (!this.isReady_) {
  3967. this.readyQueue_ = this.readyQueue_ || [];
  3968. this.readyQueue_.push(fn);
  3969. return;
  3970. }
  3971. if (sync) {
  3972. fn.call(this);
  3973. } else {
  3974. // Call the function asynchronously by default for consistency
  3975. this.setTimeout(fn, 1);
  3976. }
  3977. }
  3978. /**
  3979. * Trigger all the ready listeners for this `Component`.
  3980. *
  3981. * @fires Component#ready
  3982. */
  3983. triggerReady() {
  3984. this.isReady_ = true;
  3985. // Ensure ready is triggered asynchronously
  3986. this.setTimeout(function () {
  3987. const readyQueue = this.readyQueue_;
  3988. // Reset Ready Queue
  3989. this.readyQueue_ = [];
  3990. if (readyQueue && readyQueue.length > 0) {
  3991. readyQueue.forEach(function (fn) {
  3992. fn.call(this);
  3993. }, this);
  3994. }
  3995. // Allow for using event listeners also
  3996. /**
  3997. * Triggered when a `Component` is ready.
  3998. *
  3999. * @event Component#ready
  4000. * @type {Event}
  4001. */
  4002. this.trigger('ready');
  4003. }, 1);
  4004. }
  4005. /**
  4006. * Find a single DOM element matching a `selector`. This can be within the `Component`s
  4007. * `contentEl()` or another custom context.
  4008. *
  4009. * @param {string} selector
  4010. * A valid CSS selector, which will be passed to `querySelector`.
  4011. *
  4012. * @param {Element|string} [context=this.contentEl()]
  4013. * A DOM element within which to query. Can also be a selector string in
  4014. * which case the first matching element will get used as context. If
  4015. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  4016. * nothing it falls back to `document`.
  4017. *
  4018. * @return {Element|null}
  4019. * the dom element that was found, or null
  4020. *
  4021. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  4022. */
  4023. $(selector, context) {
  4024. return $(selector, context || this.contentEl());
  4025. }
  4026. /**
  4027. * Finds all DOM element matching a `selector`. This can be within the `Component`s
  4028. * `contentEl()` or another custom context.
  4029. *
  4030. * @param {string} selector
  4031. * A valid CSS selector, which will be passed to `querySelectorAll`.
  4032. *
  4033. * @param {Element|string} [context=this.contentEl()]
  4034. * A DOM element within which to query. Can also be a selector string in
  4035. * which case the first matching element will get used as context. If
  4036. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  4037. * nothing it falls back to `document`.
  4038. *
  4039. * @return {NodeList}
  4040. * a list of dom elements that were found
  4041. *
  4042. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  4043. */
  4044. $$(selector, context) {
  4045. return $$(selector, context || this.contentEl());
  4046. }
  4047. /**
  4048. * Check if a component's element has a CSS class name.
  4049. *
  4050. * @param {string} classToCheck
  4051. * CSS class name to check.
  4052. *
  4053. * @return {boolean}
  4054. * - True if the `Component` has the class.
  4055. * - False if the `Component` does not have the class`
  4056. */
  4057. hasClass(classToCheck) {
  4058. return hasClass(this.el_, classToCheck);
  4059. }
  4060. /**
  4061. * Add a CSS class name to the `Component`s element.
  4062. *
  4063. * @param {...string} classesToAdd
  4064. * One or more CSS class name to add.
  4065. */
  4066. addClass(...classesToAdd) {
  4067. addClass(this.el_, ...classesToAdd);
  4068. }
  4069. /**
  4070. * Remove a CSS class name from the `Component`s element.
  4071. *
  4072. * @param {...string} classesToRemove
  4073. * One or more CSS class name to remove.
  4074. */
  4075. removeClass(...classesToRemove) {
  4076. removeClass(this.el_, ...classesToRemove);
  4077. }
  4078. /**
  4079. * Add or remove a CSS class name from the component's element.
  4080. * - `classToToggle` gets added when {@link Component#hasClass} would return false.
  4081. * - `classToToggle` gets removed when {@link Component#hasClass} would return true.
  4082. *
  4083. * @param {string} classToToggle
  4084. * The class to add or remove based on (@link Component#hasClass}
  4085. *
  4086. * @param {boolean|Dom~predicate} [predicate]
  4087. * An {@link Dom~predicate} function or a boolean
  4088. */
  4089. toggleClass(classToToggle, predicate) {
  4090. toggleClass(this.el_, classToToggle, predicate);
  4091. }
  4092. /**
  4093. * Show the `Component`s element if it is hidden by removing the
  4094. * 'vjs-hidden' class name from it.
  4095. */
  4096. show() {
  4097. this.removeClass('vjs-hidden');
  4098. }
  4099. /**
  4100. * Hide the `Component`s element if it is currently showing by adding the
  4101. * 'vjs-hidden` class name to it.
  4102. */
  4103. hide() {
  4104. this.addClass('vjs-hidden');
  4105. }
  4106. /**
  4107. * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing'
  4108. * class name to it. Used during fadeIn/fadeOut.
  4109. *
  4110. * @private
  4111. */
  4112. lockShowing() {
  4113. this.addClass('vjs-lock-showing');
  4114. }
  4115. /**
  4116. * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing'
  4117. * class name from it. Used during fadeIn/fadeOut.
  4118. *
  4119. * @private
  4120. */
  4121. unlockShowing() {
  4122. this.removeClass('vjs-lock-showing');
  4123. }
  4124. /**
  4125. * Get the value of an attribute on the `Component`s element.
  4126. *
  4127. * @param {string} attribute
  4128. * Name of the attribute to get the value from.
  4129. *
  4130. * @return {string|null}
  4131. * - The value of the attribute that was asked for.
  4132. * - Can be an empty string on some browsers if the attribute does not exist
  4133. * or has no value
  4134. * - Most browsers will return null if the attribute does not exist or has
  4135. * no value.
  4136. *
  4137. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute}
  4138. */
  4139. getAttribute(attribute) {
  4140. return getAttribute(this.el_, attribute);
  4141. }
  4142. /**
  4143. * Set the value of an attribute on the `Component`'s element
  4144. *
  4145. * @param {string} attribute
  4146. * Name of the attribute to set.
  4147. *
  4148. * @param {string} value
  4149. * Value to set the attribute to.
  4150. *
  4151. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute}
  4152. */
  4153. setAttribute(attribute, value) {
  4154. setAttribute(this.el_, attribute, value);
  4155. }
  4156. /**
  4157. * Remove an attribute from the `Component`s element.
  4158. *
  4159. * @param {string} attribute
  4160. * Name of the attribute to remove.
  4161. *
  4162. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute}
  4163. */
  4164. removeAttribute(attribute) {
  4165. removeAttribute(this.el_, attribute);
  4166. }
  4167. /**
  4168. * Get or set the width of the component based upon the CSS styles.
  4169. * See {@link Component#dimension} for more detailed information.
  4170. *
  4171. * @param {number|string} [num]
  4172. * The width that you want to set postfixed with '%', 'px' or nothing.
  4173. *
  4174. * @param {boolean} [skipListeners]
  4175. * Skip the componentresize event trigger
  4176. *
  4177. * @return {number|string}
  4178. * The width when getting, zero if there is no width. Can be a string
  4179. * postpixed with '%' or 'px'.
  4180. */
  4181. width(num, skipListeners) {
  4182. return this.dimension('width', num, skipListeners);
  4183. }
  4184. /**
  4185. * Get or set the height of the component based upon the CSS styles.
  4186. * See {@link Component#dimension} for more detailed information.
  4187. *
  4188. * @param {number|string} [num]
  4189. * The height that you want to set postfixed with '%', 'px' or nothing.
  4190. *
  4191. * @param {boolean} [skipListeners]
  4192. * Skip the componentresize event trigger
  4193. *
  4194. * @return {number|string}
  4195. * The width when getting, zero if there is no width. Can be a string
  4196. * postpixed with '%' or 'px'.
  4197. */
  4198. height(num, skipListeners) {
  4199. return this.dimension('height', num, skipListeners);
  4200. }
  4201. /**
  4202. * Set both the width and height of the `Component` element at the same time.
  4203. *
  4204. * @param {number|string} width
  4205. * Width to set the `Component`s element to.
  4206. *
  4207. * @param {number|string} height
  4208. * Height to set the `Component`s element to.
  4209. */
  4210. dimensions(width, height) {
  4211. // Skip componentresize listeners on width for optimization
  4212. this.width(width, true);
  4213. this.height(height);
  4214. }
  4215. /**
  4216. * Get or set width or height of the `Component` element. This is the shared code
  4217. * for the {@link Component#width} and {@link Component#height}.
  4218. *
  4219. * Things to know:
  4220. * - If the width or height in an number this will return the number postfixed with 'px'.
  4221. * - If the width/height is a percent this will return the percent postfixed with '%'
  4222. * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function
  4223. * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`.
  4224. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/}
  4225. * for more information
  4226. * - If you want the computed style of the component, use {@link Component#currentWidth}
  4227. * and {@link {Component#currentHeight}
  4228. *
  4229. * @fires Component#componentresize
  4230. *
  4231. * @param {string} widthOrHeight
  4232. 8 'width' or 'height'
  4233. *
  4234. * @param {number|string} [num]
  4235. 8 New dimension
  4236. *
  4237. * @param {boolean} [skipListeners]
  4238. * Skip componentresize event trigger
  4239. *
  4240. * @return {number}
  4241. * The dimension when getting or 0 if unset
  4242. */
  4243. dimension(widthOrHeight, num, skipListeners) {
  4244. if (num !== undefined) {
  4245. // Set to zero if null or literally NaN (NaN !== NaN)
  4246. if (num === null || num !== num) {
  4247. num = 0;
  4248. }
  4249. // Check if using css width/height (% or px) and adjust
  4250. if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {
  4251. this.el_.style[widthOrHeight] = num;
  4252. } else if (num === 'auto') {
  4253. this.el_.style[widthOrHeight] = '';
  4254. } else {
  4255. this.el_.style[widthOrHeight] = num + 'px';
  4256. }
  4257. // skipListeners allows us to avoid triggering the resize event when setting both width and height
  4258. if (!skipListeners) {
  4259. /**
  4260. * Triggered when a component is resized.
  4261. *
  4262. * @event Component#componentresize
  4263. * @type {Event}
  4264. */
  4265. this.trigger('componentresize');
  4266. }
  4267. return;
  4268. }
  4269. // Not setting a value, so getting it
  4270. // Make sure element exists
  4271. if (!this.el_) {
  4272. return 0;
  4273. }
  4274. // Get dimension value from style
  4275. const val = this.el_.style[widthOrHeight];
  4276. const pxIndex = val.indexOf('px');
  4277. if (pxIndex !== -1) {
  4278. // Return the pixel value with no 'px'
  4279. return parseInt(val.slice(0, pxIndex), 10);
  4280. }
  4281. // No px so using % or no style was set, so falling back to offsetWidth/height
  4282. // If component has display:none, offset will return 0
  4283. // TODO: handle display:none and no dimension style using px
  4284. return parseInt(this.el_['offset' + toTitleCase$1(widthOrHeight)], 10);
  4285. }
  4286. /**
  4287. * Get the computed width or the height of the component's element.
  4288. *
  4289. * Uses `window.getComputedStyle`.
  4290. *
  4291. * @param {string} widthOrHeight
  4292. * A string containing 'width' or 'height'. Whichever one you want to get.
  4293. *
  4294. * @return {number}
  4295. * The dimension that gets asked for or 0 if nothing was set
  4296. * for that dimension.
  4297. */
  4298. currentDimension(widthOrHeight) {
  4299. let computedWidthOrHeight = 0;
  4300. if (widthOrHeight !== 'width' && widthOrHeight !== 'height') {
  4301. throw new Error('currentDimension only accepts width or height value');
  4302. }
  4303. computedWidthOrHeight = computedStyle(this.el_, widthOrHeight);
  4304. // remove 'px' from variable and parse as integer
  4305. computedWidthOrHeight = parseFloat(computedWidthOrHeight);
  4306. // if the computed value is still 0, it's possible that the browser is lying
  4307. // and we want to check the offset values.
  4308. // This code also runs wherever getComputedStyle doesn't exist.
  4309. if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) {
  4310. const rule = `offset${toTitleCase$1(widthOrHeight)}`;
  4311. computedWidthOrHeight = this.el_[rule];
  4312. }
  4313. return computedWidthOrHeight;
  4314. }
  4315. /**
  4316. * An object that contains width and height values of the `Component`s
  4317. * computed style. Uses `window.getComputedStyle`.
  4318. *
  4319. * @typedef {Object} Component~DimensionObject
  4320. *
  4321. * @property {number} width
  4322. * The width of the `Component`s computed style.
  4323. *
  4324. * @property {number} height
  4325. * The height of the `Component`s computed style.
  4326. */
  4327. /**
  4328. * Get an object that contains computed width and height values of the
  4329. * component's element.
  4330. *
  4331. * Uses `window.getComputedStyle`.
  4332. *
  4333. * @return {Component~DimensionObject}
  4334. * The computed dimensions of the component's element.
  4335. */
  4336. currentDimensions() {
  4337. return {
  4338. width: this.currentDimension('width'),
  4339. height: this.currentDimension('height')
  4340. };
  4341. }
  4342. /**
  4343. * Get the computed width of the component's element.
  4344. *
  4345. * Uses `window.getComputedStyle`.
  4346. *
  4347. * @return {number}
  4348. * The computed width of the component's element.
  4349. */
  4350. currentWidth() {
  4351. return this.currentDimension('width');
  4352. }
  4353. /**
  4354. * Get the computed height of the component's element.
  4355. *
  4356. * Uses `window.getComputedStyle`.
  4357. *
  4358. * @return {number}
  4359. * The computed height of the component's element.
  4360. */
  4361. currentHeight() {
  4362. return this.currentDimension('height');
  4363. }
  4364. /**
  4365. * Set the focus to this component
  4366. */
  4367. focus() {
  4368. this.el_.focus();
  4369. }
  4370. /**
  4371. * Remove the focus from this component
  4372. */
  4373. blur() {
  4374. this.el_.blur();
  4375. }
  4376. /**
  4377. * When this Component receives a `keydown` event which it does not process,
  4378. * it passes the event to the Player for handling.
  4379. *
  4380. * @param {KeyboardEvent} event
  4381. * The `keydown` event that caused this function to be called.
  4382. */
  4383. handleKeyDown(event) {
  4384. if (this.player_) {
  4385. // We only stop propagation here because we want unhandled events to fall
  4386. // back to the browser. Exclude Tab for focus trapping.
  4387. if (!keycode.isEventKey(event, 'Tab')) {
  4388. event.stopPropagation();
  4389. }
  4390. this.player_.handleKeyDown(event);
  4391. }
  4392. }
  4393. /**
  4394. * Many components used to have a `handleKeyPress` method, which was poorly
  4395. * named because it listened to a `keydown` event. This method name now
  4396. * delegates to `handleKeyDown`. This means anyone calling `handleKeyPress`
  4397. * will not see their method calls stop working.
  4398. *
  4399. * @param {Event} event
  4400. * The event that caused this function to be called.
  4401. */
  4402. handleKeyPress(event) {
  4403. this.handleKeyDown(event);
  4404. }
  4405. /**
  4406. * Emit a 'tap' events when touch event support gets detected. This gets used to
  4407. * support toggling the controls through a tap on the video. They get enabled
  4408. * because every sub-component would have extra overhead otherwise.
  4409. *
  4410. * @private
  4411. * @fires Component#tap
  4412. * @listens Component#touchstart
  4413. * @listens Component#touchmove
  4414. * @listens Component#touchleave
  4415. * @listens Component#touchcancel
  4416. * @listens Component#touchend
  4417. */
  4418. emitTapEvents() {
  4419. // Track the start time so we can determine how long the touch lasted
  4420. let touchStart = 0;
  4421. let firstTouch = null;
  4422. // Maximum movement allowed during a touch event to still be considered a tap
  4423. // Other popular libs use anywhere from 2 (hammer.js) to 15,
  4424. // so 10 seems like a nice, round number.
  4425. const tapMovementThreshold = 10;
  4426. // The maximum length a touch can be while still being considered a tap
  4427. const touchTimeThreshold = 200;
  4428. let couldBeTap;
  4429. this.on('touchstart', function (event) {
  4430. // If more than one finger, don't consider treating this as a click
  4431. if (event.touches.length === 1) {
  4432. // Copy pageX/pageY from the object
  4433. firstTouch = {
  4434. pageX: event.touches[0].pageX,
  4435. pageY: event.touches[0].pageY
  4436. };
  4437. // Record start time so we can detect a tap vs. "touch and hold"
  4438. touchStart = window.performance.now();
  4439. // Reset couldBeTap tracking
  4440. couldBeTap = true;
  4441. }
  4442. });
  4443. this.on('touchmove', function (event) {
  4444. // If more than one finger, don't consider treating this as a click
  4445. if (event.touches.length > 1) {
  4446. couldBeTap = false;
  4447. } else if (firstTouch) {
  4448. // Some devices will throw touchmoves for all but the slightest of taps.
  4449. // So, if we moved only a small distance, this could still be a tap
  4450. const xdiff = event.touches[0].pageX - firstTouch.pageX;
  4451. const ydiff = event.touches[0].pageY - firstTouch.pageY;
  4452. const touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
  4453. if (touchDistance > tapMovementThreshold) {
  4454. couldBeTap = false;
  4455. }
  4456. }
  4457. });
  4458. const noTap = function () {
  4459. couldBeTap = false;
  4460. };
  4461. // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
  4462. this.on('touchleave', noTap);
  4463. this.on('touchcancel', noTap);
  4464. // When the touch ends, measure how long it took and trigger the appropriate
  4465. // event
  4466. this.on('touchend', function (event) {
  4467. firstTouch = null;
  4468. // Proceed only if the touchmove/leave/cancel event didn't happen
  4469. if (couldBeTap === true) {
  4470. // Measure how long the touch lasted
  4471. const touchTime = window.performance.now() - touchStart;
  4472. // Make sure the touch was less than the threshold to be considered a tap
  4473. if (touchTime < touchTimeThreshold) {
  4474. // Don't let browser turn this into a click
  4475. event.preventDefault();
  4476. /**
  4477. * Triggered when a `Component` is tapped.
  4478. *
  4479. * @event Component#tap
  4480. * @type {MouseEvent}
  4481. */
  4482. this.trigger('tap');
  4483. // It may be good to copy the touchend event object and change the
  4484. // type to tap, if the other event properties aren't exact after
  4485. // Events.fixEvent runs (e.g. event.target)
  4486. }
  4487. }
  4488. });
  4489. }
  4490. /**
  4491. * This function reports user activity whenever touch events happen. This can get
  4492. * turned off by any sub-components that wants touch events to act another way.
  4493. *
  4494. * Report user touch activity when touch events occur. User activity gets used to
  4495. * determine when controls should show/hide. It is simple when it comes to mouse
  4496. * events, because any mouse event should show the controls. So we capture mouse
  4497. * events that bubble up to the player and report activity when that happens.
  4498. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player
  4499. * controls. So touch events can't help us at the player level either.
  4500. *
  4501. * User activity gets checked asynchronously. So what could happen is a tap event
  4502. * on the video turns the controls off. Then the `touchend` event bubbles up to
  4503. * the player. Which, if it reported user activity, would turn the controls right
  4504. * back on. We also don't want to completely block touch events from bubbling up.
  4505. * Furthermore a `touchmove` event and anything other than a tap, should not turn
  4506. * controls back on.
  4507. *
  4508. * @listens Component#touchstart
  4509. * @listens Component#touchmove
  4510. * @listens Component#touchend
  4511. * @listens Component#touchcancel
  4512. */
  4513. enableTouchActivity() {
  4514. // Don't continue if the root player doesn't support reporting user activity
  4515. if (!this.player() || !this.player().reportUserActivity) {
  4516. return;
  4517. }
  4518. // listener for reporting that the user is active
  4519. const report = bind_(this.player(), this.player().reportUserActivity);
  4520. let touchHolding;
  4521. this.on('touchstart', function () {
  4522. report();
  4523. // For as long as the they are touching the device or have their mouse down,
  4524. // we consider them active even if they're not moving their finger or mouse.
  4525. // So we want to continue to update that they are active
  4526. this.clearInterval(touchHolding);
  4527. // report at the same interval as activityCheck
  4528. touchHolding = this.setInterval(report, 250);
  4529. });
  4530. const touchEnd = function (event) {
  4531. report();
  4532. // stop the interval that maintains activity if the touch is holding
  4533. this.clearInterval(touchHolding);
  4534. };
  4535. this.on('touchmove', report);
  4536. this.on('touchend', touchEnd);
  4537. this.on('touchcancel', touchEnd);
  4538. }
  4539. /**
  4540. * A callback that has no parameters and is bound into `Component`s context.
  4541. *
  4542. * @callback Component~GenericCallback
  4543. * @this Component
  4544. */
  4545. /**
  4546. * Creates a function that runs after an `x` millisecond timeout. This function is a
  4547. * wrapper around `window.setTimeout`. There are a few reasons to use this one
  4548. * instead though:
  4549. * 1. It gets cleared via {@link Component#clearTimeout} when
  4550. * {@link Component#dispose} gets called.
  4551. * 2. The function callback will gets turned into a {@link Component~GenericCallback}
  4552. *
  4553. * > Note: You can't use `window.clearTimeout` on the id returned by this function. This
  4554. * will cause its dispose listener not to get cleaned up! Please use
  4555. * {@link Component#clearTimeout} or {@link Component#dispose} instead.
  4556. *
  4557. * @param {Component~GenericCallback} fn
  4558. * The function that will be run after `timeout`.
  4559. *
  4560. * @param {number} timeout
  4561. * Timeout in milliseconds to delay before executing the specified function.
  4562. *
  4563. * @return {number}
  4564. * Returns a timeout ID that gets used to identify the timeout. It can also
  4565. * get used in {@link Component#clearTimeout} to clear the timeout that
  4566. * was set.
  4567. *
  4568. * @listens Component#dispose
  4569. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout}
  4570. */
  4571. setTimeout(fn, timeout) {
  4572. // declare as variables so they are properly available in timeout function
  4573. // eslint-disable-next-line
  4574. var timeoutId;
  4575. fn = bind_(this, fn);
  4576. this.clearTimersOnDispose_();
  4577. timeoutId = window.setTimeout(() => {
  4578. if (this.setTimeoutIds_.has(timeoutId)) {
  4579. this.setTimeoutIds_.delete(timeoutId);
  4580. }
  4581. fn();
  4582. }, timeout);
  4583. this.setTimeoutIds_.add(timeoutId);
  4584. return timeoutId;
  4585. }
  4586. /**
  4587. * Clears a timeout that gets created via `window.setTimeout` or
  4588. * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout}
  4589. * use this function instead of `window.clearTimout`. If you don't your dispose
  4590. * listener will not get cleaned up until {@link Component#dispose}!
  4591. *
  4592. * @param {number} timeoutId
  4593. * The id of the timeout to clear. The return value of
  4594. * {@link Component#setTimeout} or `window.setTimeout`.
  4595. *
  4596. * @return {number}
  4597. * Returns the timeout id that was cleared.
  4598. *
  4599. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout}
  4600. */
  4601. clearTimeout(timeoutId) {
  4602. if (this.setTimeoutIds_.has(timeoutId)) {
  4603. this.setTimeoutIds_.delete(timeoutId);
  4604. window.clearTimeout(timeoutId);
  4605. }
  4606. return timeoutId;
  4607. }
  4608. /**
  4609. * Creates a function that gets run every `x` milliseconds. This function is a wrapper
  4610. * around `window.setInterval`. There are a few reasons to use this one instead though.
  4611. * 1. It gets cleared via {@link Component#clearInterval} when
  4612. * {@link Component#dispose} gets called.
  4613. * 2. The function callback will be a {@link Component~GenericCallback}
  4614. *
  4615. * @param {Component~GenericCallback} fn
  4616. * The function to run every `x` seconds.
  4617. *
  4618. * @param {number} interval
  4619. * Execute the specified function every `x` milliseconds.
  4620. *
  4621. * @return {number}
  4622. * Returns an id that can be used to identify the interval. It can also be be used in
  4623. * {@link Component#clearInterval} to clear the interval.
  4624. *
  4625. * @listens Component#dispose
  4626. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval}
  4627. */
  4628. setInterval(fn, interval) {
  4629. fn = bind_(this, fn);
  4630. this.clearTimersOnDispose_();
  4631. const intervalId = window.setInterval(fn, interval);
  4632. this.setIntervalIds_.add(intervalId);
  4633. return intervalId;
  4634. }
  4635. /**
  4636. * Clears an interval that gets created via `window.setInterval` or
  4637. * {@link Component#setInterval}. If you set an interval via {@link Component#setInterval}
  4638. * use this function instead of `window.clearInterval`. If you don't your dispose
  4639. * listener will not get cleaned up until {@link Component#dispose}!
  4640. *
  4641. * @param {number} intervalId
  4642. * The id of the interval to clear. The return value of
  4643. * {@link Component#setInterval} or `window.setInterval`.
  4644. *
  4645. * @return {number}
  4646. * Returns the interval id that was cleared.
  4647. *
  4648. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval}
  4649. */
  4650. clearInterval(intervalId) {
  4651. if (this.setIntervalIds_.has(intervalId)) {
  4652. this.setIntervalIds_.delete(intervalId);
  4653. window.clearInterval(intervalId);
  4654. }
  4655. return intervalId;
  4656. }
  4657. /**
  4658. * Queues up a callback to be passed to requestAnimationFrame (rAF), but
  4659. * with a few extra bonuses:
  4660. *
  4661. * - Supports browsers that do not support rAF by falling back to
  4662. * {@link Component#setTimeout}.
  4663. *
  4664. * - The callback is turned into a {@link Component~GenericCallback} (i.e.
  4665. * bound to the component).
  4666. *
  4667. * - Automatic cancellation of the rAF callback is handled if the component
  4668. * is disposed before it is called.
  4669. *
  4670. * @param {Component~GenericCallback} fn
  4671. * A function that will be bound to this component and executed just
  4672. * before the browser's next repaint.
  4673. *
  4674. * @return {number}
  4675. * Returns an rAF ID that gets used to identify the timeout. It can
  4676. * also be used in {@link Component#cancelAnimationFrame} to cancel
  4677. * the animation frame callback.
  4678. *
  4679. * @listens Component#dispose
  4680. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}
  4681. */
  4682. requestAnimationFrame(fn) {
  4683. this.clearTimersOnDispose_();
  4684. // declare as variables so they are properly available in rAF function
  4685. // eslint-disable-next-line
  4686. var id;
  4687. fn = bind_(this, fn);
  4688. id = window.requestAnimationFrame(() => {
  4689. if (this.rafIds_.has(id)) {
  4690. this.rafIds_.delete(id);
  4691. }
  4692. fn();
  4693. });
  4694. this.rafIds_.add(id);
  4695. return id;
  4696. }
  4697. /**
  4698. * Request an animation frame, but only one named animation
  4699. * frame will be queued. Another will never be added until
  4700. * the previous one finishes.
  4701. *
  4702. * @param {string} name
  4703. * The name to give this requestAnimationFrame
  4704. *
  4705. * @param {Component~GenericCallback} fn
  4706. * A function that will be bound to this component and executed just
  4707. * before the browser's next repaint.
  4708. */
  4709. requestNamedAnimationFrame(name, fn) {
  4710. if (this.namedRafs_.has(name)) {
  4711. return;
  4712. }
  4713. this.clearTimersOnDispose_();
  4714. fn = bind_(this, fn);
  4715. const id = this.requestAnimationFrame(() => {
  4716. fn();
  4717. if (this.namedRafs_.has(name)) {
  4718. this.namedRafs_.delete(name);
  4719. }
  4720. });
  4721. this.namedRafs_.set(name, id);
  4722. return name;
  4723. }
  4724. /**
  4725. * Cancels a current named animation frame if it exists.
  4726. *
  4727. * @param {string} name
  4728. * The name of the requestAnimationFrame to cancel.
  4729. */
  4730. cancelNamedAnimationFrame(name) {
  4731. if (!this.namedRafs_.has(name)) {
  4732. return;
  4733. }
  4734. this.cancelAnimationFrame(this.namedRafs_.get(name));
  4735. this.namedRafs_.delete(name);
  4736. }
  4737. /**
  4738. * Cancels a queued callback passed to {@link Component#requestAnimationFrame}
  4739. * (rAF).
  4740. *
  4741. * If you queue an rAF callback via {@link Component#requestAnimationFrame},
  4742. * use this function instead of `window.cancelAnimationFrame`. If you don't,
  4743. * your dispose listener will not get cleaned up until {@link Component#dispose}!
  4744. *
  4745. * @param {number} id
  4746. * The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}.
  4747. *
  4748. * @return {number}
  4749. * Returns the rAF ID that was cleared.
  4750. *
  4751. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame}
  4752. */
  4753. cancelAnimationFrame(id) {
  4754. if (this.rafIds_.has(id)) {
  4755. this.rafIds_.delete(id);
  4756. window.cancelAnimationFrame(id);
  4757. }
  4758. return id;
  4759. }
  4760. /**
  4761. * A function to setup `requestAnimationFrame`, `setTimeout`,
  4762. * and `setInterval`, clearing on dispose.
  4763. *
  4764. * > Previously each timer added and removed dispose listeners on it's own.
  4765. * For better performance it was decided to batch them all, and use `Set`s
  4766. * to track outstanding timer ids.
  4767. *
  4768. * @private
  4769. */
  4770. clearTimersOnDispose_() {
  4771. if (this.clearingTimersOnDispose_) {
  4772. return;
  4773. }
  4774. this.clearingTimersOnDispose_ = true;
  4775. this.one('dispose', () => {
  4776. [['namedRafs_', 'cancelNamedAnimationFrame'], ['rafIds_', 'cancelAnimationFrame'], ['setTimeoutIds_', 'clearTimeout'], ['setIntervalIds_', 'clearInterval']].forEach(([idName, cancelName]) => {
  4777. // for a `Set` key will actually be the value again
  4778. // so forEach((val, val) =>` but for maps we want to use
  4779. // the key.
  4780. this[idName].forEach((val, key) => this[cancelName](key));
  4781. });
  4782. this.clearingTimersOnDispose_ = false;
  4783. });
  4784. }
  4785. /**
  4786. * Register a `Component` with `videojs` given the name and the component.
  4787. *
  4788. * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s
  4789. * should be registered using {@link Tech.registerTech} or
  4790. * {@link videojs:videojs.registerTech}.
  4791. *
  4792. * > NOTE: This function can also be seen on videojs as
  4793. * {@link videojs:videojs.registerComponent}.
  4794. *
  4795. * @param {string} name
  4796. * The name of the `Component` to register.
  4797. *
  4798. * @param {Component} ComponentToRegister
  4799. * The `Component` class to register.
  4800. *
  4801. * @return {Component}
  4802. * The `Component` that was registered.
  4803. */
  4804. static registerComponent(name, ComponentToRegister) {
  4805. if (typeof name !== 'string' || !name) {
  4806. throw new Error(`Illegal component name, "${name}"; must be a non-empty string.`);
  4807. }
  4808. const Tech = Component$1.getComponent('Tech');
  4809. // We need to make sure this check is only done if Tech has been registered.
  4810. const isTech = Tech && Tech.isTech(ComponentToRegister);
  4811. const isComp = Component$1 === ComponentToRegister || Component$1.prototype.isPrototypeOf(ComponentToRegister.prototype);
  4812. if (isTech || !isComp) {
  4813. let reason;
  4814. if (isTech) {
  4815. reason = 'techs must be registered using Tech.registerTech()';
  4816. } else {
  4817. reason = 'must be a Component subclass';
  4818. }
  4819. throw new Error(`Illegal component, "${name}"; ${reason}.`);
  4820. }
  4821. name = toTitleCase$1(name);
  4822. if (!Component$1.components_) {
  4823. Component$1.components_ = {};
  4824. }
  4825. const Player = Component$1.getComponent('Player');
  4826. if (name === 'Player' && Player && Player.players) {
  4827. const players = Player.players;
  4828. const playerNames = Object.keys(players);
  4829. // If we have players that were disposed, then their name will still be
  4830. // in Players.players. So, we must loop through and verify that the value
  4831. // for each item is not null. This allows registration of the Player component
  4832. // after all players have been disposed or before any were created.
  4833. if (players && playerNames.length > 0 && playerNames.map(pname => players[pname]).every(Boolean)) {
  4834. throw new Error('Can not register Player component after player has been created.');
  4835. }
  4836. }
  4837. Component$1.components_[name] = ComponentToRegister;
  4838. Component$1.components_[toLowerCase(name)] = ComponentToRegister;
  4839. return ComponentToRegister;
  4840. }
  4841. /**
  4842. * Get a `Component` based on the name it was registered with.
  4843. *
  4844. * @param {string} name
  4845. * The Name of the component to get.
  4846. *
  4847. * @return {Component}
  4848. * The `Component` that got registered under the given name.
  4849. */
  4850. static getComponent(name) {
  4851. if (!name || !Component$1.components_) {
  4852. return;
  4853. }
  4854. return Component$1.components_[name];
  4855. }
  4856. }
  4857. Component$1.registerComponent('Component', Component$1);
  4858. /**
  4859. * @file time.js
  4860. * @module time
  4861. */
  4862. /**
  4863. * Returns the time for the specified index at the start or end
  4864. * of a TimeRange object.
  4865. *
  4866. * @typedef {Function} TimeRangeIndex
  4867. *
  4868. * @param {number} [index=0]
  4869. * The range number to return the time for.
  4870. *
  4871. * @return {number}
  4872. * The time offset at the specified index.
  4873. *
  4874. * @deprecated The index argument must be provided.
  4875. * In the future, leaving it out will throw an error.
  4876. */
  4877. /**
  4878. * An object that contains ranges of time, which mimics {@link TimeRanges}.
  4879. *
  4880. * @typedef {Object} TimeRange
  4881. *
  4882. * @property {number} length
  4883. * The number of time ranges represented by this object.
  4884. *
  4885. * @property {module:time~TimeRangeIndex} start
  4886. * Returns the time offset at which a specified time range begins.
  4887. *
  4888. * @property {module:time~TimeRangeIndex} end
  4889. * Returns the time offset at which a specified time range ends.
  4890. *
  4891. * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges
  4892. */
  4893. /**
  4894. * Check if any of the time ranges are over the maximum index.
  4895. *
  4896. * @private
  4897. * @param {string} fnName
  4898. * The function name to use for logging
  4899. *
  4900. * @param {number} index
  4901. * The index to check
  4902. *
  4903. * @param {number} maxIndex
  4904. * The maximum possible index
  4905. *
  4906. * @throws {Error} if the timeRanges provided are over the maxIndex
  4907. */
  4908. function rangeCheck(fnName, index, maxIndex) {
  4909. if (typeof index !== 'number' || index < 0 || index > maxIndex) {
  4910. throw new Error(`Failed to execute '${fnName}' on 'TimeRanges': The index provided (${index}) is non-numeric or out of bounds (0-${maxIndex}).`);
  4911. }
  4912. }
  4913. /**
  4914. * Get the time for the specified index at the start or end
  4915. * of a TimeRange object.
  4916. *
  4917. * @private
  4918. * @param {string} fnName
  4919. * The function name to use for logging
  4920. *
  4921. * @param {string} valueIndex
  4922. * The property that should be used to get the time. should be
  4923. * 'start' or 'end'
  4924. *
  4925. * @param {Array} ranges
  4926. * An array of time ranges
  4927. *
  4928. * @param {Array} [rangeIndex=0]
  4929. * The index to start the search at
  4930. *
  4931. * @return {number}
  4932. * The time that offset at the specified index.
  4933. *
  4934. * @deprecated rangeIndex must be set to a value, in the future this will throw an error.
  4935. * @throws {Error} if rangeIndex is more than the length of ranges
  4936. */
  4937. function getRange(fnName, valueIndex, ranges, rangeIndex) {
  4938. rangeCheck(fnName, rangeIndex, ranges.length - 1);
  4939. return ranges[rangeIndex][valueIndex];
  4940. }
  4941. /**
  4942. * Create a time range object given ranges of time.
  4943. *
  4944. * @private
  4945. * @param {Array} [ranges]
  4946. * An array of time ranges.
  4947. *
  4948. * @return {TimeRange}
  4949. */
  4950. function createTimeRangesObj(ranges) {
  4951. let timeRangesObj;
  4952. if (ranges === undefined || ranges.length === 0) {
  4953. timeRangesObj = {
  4954. length: 0,
  4955. start() {
  4956. throw new Error('This TimeRanges object is empty');
  4957. },
  4958. end() {
  4959. throw new Error('This TimeRanges object is empty');
  4960. }
  4961. };
  4962. } else {
  4963. timeRangesObj = {
  4964. length: ranges.length,
  4965. start: getRange.bind(null, 'start', 0, ranges),
  4966. end: getRange.bind(null, 'end', 1, ranges)
  4967. };
  4968. }
  4969. if (window.Symbol && window.Symbol.iterator) {
  4970. timeRangesObj[window.Symbol.iterator] = () => (ranges || []).values();
  4971. }
  4972. return timeRangesObj;
  4973. }
  4974. /**
  4975. * Create a `TimeRange` object which mimics an
  4976. * {@link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges|HTML5 TimeRanges instance}.
  4977. *
  4978. * @param {number|Array[]} start
  4979. * The start of a single range (a number) or an array of ranges (an
  4980. * array of arrays of two numbers each).
  4981. *
  4982. * @param {number} end
  4983. * The end of a single range. Cannot be used with the array form of
  4984. * the `start` argument.
  4985. *
  4986. * @return {TimeRange}
  4987. */
  4988. function createTimeRanges$1(start, end) {
  4989. if (Array.isArray(start)) {
  4990. return createTimeRangesObj(start);
  4991. } else if (start === undefined || end === undefined) {
  4992. return createTimeRangesObj();
  4993. }
  4994. return createTimeRangesObj([[start, end]]);
  4995. }
  4996. /**
  4997. * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in
  4998. * seconds) will force a number of leading zeros to cover the length of the
  4999. * guide.
  5000. *
  5001. * @private
  5002. * @param {number} seconds
  5003. * Number of seconds to be turned into a string
  5004. *
  5005. * @param {number} guide
  5006. * Number (in seconds) to model the string after
  5007. *
  5008. * @return {string}
  5009. * Time formatted as H:MM:SS or M:SS
  5010. */
  5011. const defaultImplementation = function (seconds, guide) {
  5012. seconds = seconds < 0 ? 0 : seconds;
  5013. let s = Math.floor(seconds % 60);
  5014. let m = Math.floor(seconds / 60 % 60);
  5015. let h = Math.floor(seconds / 3600);
  5016. const gm = Math.floor(guide / 60 % 60);
  5017. const gh = Math.floor(guide / 3600);
  5018. // handle invalid times
  5019. if (isNaN(seconds) || seconds === Infinity) {
  5020. // '-' is false for all relational operators (e.g. <, >=) so this setting
  5021. // will add the minimum number of fields specified by the guide
  5022. h = m = s = '-';
  5023. }
  5024. // Check if we need to show hours
  5025. h = h > 0 || gh > 0 ? h + ':' : '';
  5026. // If hours are showing, we may need to add a leading zero.
  5027. // Always show at least one digit of minutes.
  5028. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':';
  5029. // Check if leading zero is need for seconds
  5030. s = s < 10 ? '0' + s : s;
  5031. return h + m + s;
  5032. };
  5033. // Internal pointer to the current implementation.
  5034. let implementation = defaultImplementation;
  5035. /**
  5036. * Replaces the default formatTime implementation with a custom implementation.
  5037. *
  5038. * @param {Function} customImplementation
  5039. * A function which will be used in place of the default formatTime
  5040. * implementation. Will receive the current time in seconds and the
  5041. * guide (in seconds) as arguments.
  5042. */
  5043. function setFormatTime(customImplementation) {
  5044. implementation = customImplementation;
  5045. }
  5046. /**
  5047. * Resets formatTime to the default implementation.
  5048. */
  5049. function resetFormatTime() {
  5050. implementation = defaultImplementation;
  5051. }
  5052. /**
  5053. * Delegates to either the default time formatting function or a custom
  5054. * function supplied via `setFormatTime`.
  5055. *
  5056. * Formats seconds as a time string (H:MM:SS or M:SS). Supplying a
  5057. * guide (in seconds) will force a number of leading zeros to cover the
  5058. * length of the guide.
  5059. *
  5060. * @example formatTime(125, 600) === "02:05"
  5061. * @param {number} seconds
  5062. * Number of seconds to be turned into a string
  5063. *
  5064. * @param {number} guide
  5065. * Number (in seconds) to model the string after
  5066. *
  5067. * @return {string}
  5068. * Time formatted as H:MM:SS or M:SS
  5069. */
  5070. function formatTime(seconds, guide = seconds) {
  5071. return implementation(seconds, guide);
  5072. }
  5073. var Time = /*#__PURE__*/Object.freeze({
  5074. __proto__: null,
  5075. createTimeRanges: createTimeRanges$1,
  5076. createTimeRange: createTimeRanges$1,
  5077. setFormatTime: setFormatTime,
  5078. resetFormatTime: resetFormatTime,
  5079. formatTime: formatTime
  5080. });
  5081. /**
  5082. * @file buffer.js
  5083. * @module buffer
  5084. */
  5085. /**
  5086. * Compute the percentage of the media that has been buffered.
  5087. *
  5088. * @param { import('./time').TimeRange } buffered
  5089. * The current `TimeRanges` object representing buffered time ranges
  5090. *
  5091. * @param {number} duration
  5092. * Total duration of the media
  5093. *
  5094. * @return {number}
  5095. * Percent buffered of the total duration in decimal form.
  5096. */
  5097. function bufferedPercent(buffered, duration) {
  5098. let bufferedDuration = 0;
  5099. let start;
  5100. let end;
  5101. if (!duration) {
  5102. return 0;
  5103. }
  5104. if (!buffered || !buffered.length) {
  5105. buffered = createTimeRanges$1(0, 0);
  5106. }
  5107. for (let i = 0; i < buffered.length; i++) {
  5108. start = buffered.start(i);
  5109. end = buffered.end(i);
  5110. // buffered end can be bigger than duration by a very small fraction
  5111. if (end > duration) {
  5112. end = duration;
  5113. }
  5114. bufferedDuration += end - start;
  5115. }
  5116. return bufferedDuration / duration;
  5117. }
  5118. /**
  5119. * @file media-error.js
  5120. */
  5121. /**
  5122. * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class.
  5123. *
  5124. * @param {number|string|Object|MediaError} value
  5125. * This can be of multiple types:
  5126. * - number: should be a standard error code
  5127. * - string: an error message (the code will be 0)
  5128. * - Object: arbitrary properties
  5129. * - `MediaError` (native): used to populate a video.js `MediaError` object
  5130. * - `MediaError` (video.js): will return itself if it's already a
  5131. * video.js `MediaError` object.
  5132. *
  5133. * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror}
  5134. * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes}
  5135. *
  5136. * @class MediaError
  5137. */
  5138. function MediaError(value) {
  5139. // Allow redundant calls to this constructor to avoid having `instanceof`
  5140. // checks peppered around the code.
  5141. if (value instanceof MediaError) {
  5142. return value;
  5143. }
  5144. if (typeof value === 'number') {
  5145. this.code = value;
  5146. } else if (typeof value === 'string') {
  5147. // default code is zero, so this is a custom error
  5148. this.message = value;
  5149. } else if (isObject$1(value)) {
  5150. // We assign the `code` property manually because native `MediaError` objects
  5151. // do not expose it as an own/enumerable property of the object.
  5152. if (typeof value.code === 'number') {
  5153. this.code = value.code;
  5154. }
  5155. Object.assign(this, value);
  5156. }
  5157. if (!this.message) {
  5158. this.message = MediaError.defaultMessages[this.code] || '';
  5159. }
  5160. }
  5161. /**
  5162. * The error code that refers two one of the defined `MediaError` types
  5163. *
  5164. * @type {Number}
  5165. */
  5166. MediaError.prototype.code = 0;
  5167. /**
  5168. * An optional message that to show with the error. Message is not part of the HTML5
  5169. * video spec but allows for more informative custom errors.
  5170. *
  5171. * @type {String}
  5172. */
  5173. MediaError.prototype.message = '';
  5174. /**
  5175. * An optional status code that can be set by plugins to allow even more detail about
  5176. * the error. For example a plugin might provide a specific HTTP status code and an
  5177. * error message for that code. Then when the plugin gets that error this class will
  5178. * know how to display an error message for it. This allows a custom message to show
  5179. * up on the `Player` error overlay.
  5180. *
  5181. * @type {Array}
  5182. */
  5183. MediaError.prototype.status = null;
  5184. /**
  5185. * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the
  5186. * specification listed under {@link MediaError} for more information.
  5187. *
  5188. * @enum {array}
  5189. * @readonly
  5190. * @property {string} 0 - MEDIA_ERR_CUSTOM
  5191. * @property {string} 1 - MEDIA_ERR_ABORTED
  5192. * @property {string} 2 - MEDIA_ERR_NETWORK
  5193. * @property {string} 3 - MEDIA_ERR_DECODE
  5194. * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED
  5195. * @property {string} 5 - MEDIA_ERR_ENCRYPTED
  5196. */
  5197. MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED'];
  5198. /**
  5199. * The default `MediaError` messages based on the {@link MediaError.errorTypes}.
  5200. *
  5201. * @type {Array}
  5202. * @constant
  5203. */
  5204. MediaError.defaultMessages = {
  5205. 1: 'You aborted the media playback',
  5206. 2: 'A network error caused the media download to fail part-way.',
  5207. 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
  5208. 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
  5209. 5: 'The media is encrypted and we do not have the keys to decrypt it.'
  5210. };
  5211. // Add types as properties on MediaError
  5212. // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  5213. for (let errNum = 0; errNum < MediaError.errorTypes.length; errNum++) {
  5214. MediaError[MediaError.errorTypes[errNum]] = errNum;
  5215. // values should be accessible on both the class and instance
  5216. MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
  5217. }
  5218. var tuple = SafeParseTuple;
  5219. function SafeParseTuple(obj, reviver) {
  5220. var json;
  5221. var error = null;
  5222. try {
  5223. json = JSON.parse(obj, reviver);
  5224. } catch (err) {
  5225. error = err;
  5226. }
  5227. return [error, json];
  5228. }
  5229. /**
  5230. * Returns whether an object is `Promise`-like (i.e. has a `then` method).
  5231. *
  5232. * @param {Object} value
  5233. * An object that may or may not be `Promise`-like.
  5234. *
  5235. * @return {boolean}
  5236. * Whether or not the object is `Promise`-like.
  5237. */
  5238. function isPromise(value) {
  5239. return value !== undefined && value !== null && typeof value.then === 'function';
  5240. }
  5241. /**
  5242. * Silence a Promise-like object.
  5243. *
  5244. * This is useful for avoiding non-harmful, but potentially confusing "uncaught
  5245. * play promise" rejection error messages.
  5246. *
  5247. * @param {Object} value
  5248. * An object that may or may not be `Promise`-like.
  5249. */
  5250. function silencePromise(value) {
  5251. if (isPromise(value)) {
  5252. value.then(null, e => {});
  5253. }
  5254. }
  5255. /**
  5256. * @file text-track-list-converter.js Utilities for capturing text track state and
  5257. * re-creating tracks based on a capture.
  5258. *
  5259. * @module text-track-list-converter
  5260. */
  5261. /**
  5262. * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that
  5263. * represents the {@link TextTrack}'s state.
  5264. *
  5265. * @param {TextTrack} track
  5266. * The text track to query.
  5267. *
  5268. * @return {Object}
  5269. * A serializable javascript representation of the TextTrack.
  5270. * @private
  5271. */
  5272. const trackToJson_ = function (track) {
  5273. const ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce((acc, prop, i) => {
  5274. if (track[prop]) {
  5275. acc[prop] = track[prop];
  5276. }
  5277. return acc;
  5278. }, {
  5279. cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {
  5280. return {
  5281. startTime: cue.startTime,
  5282. endTime: cue.endTime,
  5283. text: cue.text,
  5284. id: cue.id
  5285. };
  5286. })
  5287. });
  5288. return ret;
  5289. };
  5290. /**
  5291. * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the
  5292. * state of all {@link TextTrack}s currently configured. The return array is compatible with
  5293. * {@link text-track-list-converter:jsonToTextTracks}.
  5294. *
  5295. * @param { import('../tech/tech').default } tech
  5296. * The tech object to query
  5297. *
  5298. * @return {Array}
  5299. * A serializable javascript representation of the {@link Tech}s
  5300. * {@link TextTrackList}.
  5301. */
  5302. const textTracksToJson = function (tech) {
  5303. const trackEls = tech.$$('track');
  5304. const trackObjs = Array.prototype.map.call(trackEls, t => t.track);
  5305. const tracks = Array.prototype.map.call(trackEls, function (trackEl) {
  5306. const json = trackToJson_(trackEl.track);
  5307. if (trackEl.src) {
  5308. json.src = trackEl.src;
  5309. }
  5310. return json;
  5311. });
  5312. return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
  5313. return trackObjs.indexOf(track) === -1;
  5314. }).map(trackToJson_));
  5315. };
  5316. /**
  5317. * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript
  5318. * object {@link TextTrack} representations.
  5319. *
  5320. * @param {Array} json
  5321. * An array of `TextTrack` representation objects, like those that would be
  5322. * produced by `textTracksToJson`.
  5323. *
  5324. * @param {Tech} tech
  5325. * The `Tech` to create the `TextTrack`s on.
  5326. */
  5327. const jsonToTextTracks = function (json, tech) {
  5328. json.forEach(function (track) {
  5329. const addedTrack = tech.addRemoteTextTrack(track).track;
  5330. if (!track.src && track.cues) {
  5331. track.cues.forEach(cue => addedTrack.addCue(cue));
  5332. }
  5333. });
  5334. return tech.textTracks();
  5335. };
  5336. var textTrackConverter = {
  5337. textTracksToJson,
  5338. jsonToTextTracks,
  5339. trackToJson_
  5340. };
  5341. /**
  5342. * @file modal-dialog.js
  5343. */
  5344. const MODAL_CLASS_NAME = 'vjs-modal-dialog';
  5345. /**
  5346. * The `ModalDialog` displays over the video and its controls, which blocks
  5347. * interaction with the player until it is closed.
  5348. *
  5349. * Modal dialogs include a "Close" button and will close when that button
  5350. * is activated - or when ESC is pressed anywhere.
  5351. *
  5352. * @extends Component
  5353. */
  5354. class ModalDialog extends Component$1 {
  5355. /**
  5356. * Create an instance of this class.
  5357. *
  5358. * @param { import('./player').default } player
  5359. * The `Player` that this class should be attached to.
  5360. *
  5361. * @param {Object} [options]
  5362. * The key/value store of player options.
  5363. *
  5364. * @param { import('./utils/dom').ContentDescriptor} [options.content=undefined]
  5365. * Provide customized content for this modal.
  5366. *
  5367. * @param {string} [options.description]
  5368. * A text description for the modal, primarily for accessibility.
  5369. *
  5370. * @param {boolean} [options.fillAlways=false]
  5371. * Normally, modals are automatically filled only the first time
  5372. * they open. This tells the modal to refresh its content
  5373. * every time it opens.
  5374. *
  5375. * @param {string} [options.label]
  5376. * A text label for the modal, primarily for accessibility.
  5377. *
  5378. * @param {boolean} [options.pauseOnOpen=true]
  5379. * If `true`, playback will will be paused if playing when
  5380. * the modal opens, and resumed when it closes.
  5381. *
  5382. * @param {boolean} [options.temporary=true]
  5383. * If `true`, the modal can only be opened once; it will be
  5384. * disposed as soon as it's closed.
  5385. *
  5386. * @param {boolean} [options.uncloseable=false]
  5387. * If `true`, the user will not be able to close the modal
  5388. * through the UI in the normal ways. Programmatic closing is
  5389. * still possible.
  5390. */
  5391. constructor(player, options) {
  5392. super(player, options);
  5393. this.handleKeyDown_ = e => this.handleKeyDown(e);
  5394. this.close_ = e => this.close(e);
  5395. this.opened_ = this.hasBeenOpened_ = this.hasBeenFilled_ = false;
  5396. this.closeable(!this.options_.uncloseable);
  5397. this.content(this.options_.content);
  5398. // Make sure the contentEl is defined AFTER any children are initialized
  5399. // because we only want the contents of the modal in the contentEl
  5400. // (not the UI elements like the close button).
  5401. this.contentEl_ = createEl('div', {
  5402. className: `${MODAL_CLASS_NAME}-content`
  5403. }, {
  5404. role: 'document'
  5405. });
  5406. this.descEl_ = createEl('p', {
  5407. className: `${MODAL_CLASS_NAME}-description vjs-control-text`,
  5408. id: this.el().getAttribute('aria-describedby')
  5409. });
  5410. textContent(this.descEl_, this.description());
  5411. this.el_.appendChild(this.descEl_);
  5412. this.el_.appendChild(this.contentEl_);
  5413. }
  5414. /**
  5415. * Create the `ModalDialog`'s DOM element
  5416. *
  5417. * @return {Element}
  5418. * The DOM element that gets created.
  5419. */
  5420. createEl() {
  5421. return super.createEl('div', {
  5422. className: this.buildCSSClass(),
  5423. tabIndex: -1
  5424. }, {
  5425. 'aria-describedby': `${this.id()}_description`,
  5426. 'aria-hidden': 'true',
  5427. 'aria-label': this.label(),
  5428. 'role': 'dialog'
  5429. });
  5430. }
  5431. dispose() {
  5432. this.contentEl_ = null;
  5433. this.descEl_ = null;
  5434. this.previouslyActiveEl_ = null;
  5435. super.dispose();
  5436. }
  5437. /**
  5438. * Builds the default DOM `className`.
  5439. *
  5440. * @return {string}
  5441. * The DOM `className` for this object.
  5442. */
  5443. buildCSSClass() {
  5444. return `${MODAL_CLASS_NAME} vjs-hidden ${super.buildCSSClass()}`;
  5445. }
  5446. /**
  5447. * Returns the label string for this modal. Primarily used for accessibility.
  5448. *
  5449. * @return {string}
  5450. * the localized or raw label of this modal.
  5451. */
  5452. label() {
  5453. return this.localize(this.options_.label || 'Modal Window');
  5454. }
  5455. /**
  5456. * Returns the description string for this modal. Primarily used for
  5457. * accessibility.
  5458. *
  5459. * @return {string}
  5460. * The localized or raw description of this modal.
  5461. */
  5462. description() {
  5463. let desc = this.options_.description || this.localize('This is a modal window.');
  5464. // Append a universal closeability message if the modal is closeable.
  5465. if (this.closeable()) {
  5466. desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.');
  5467. }
  5468. return desc;
  5469. }
  5470. /**
  5471. * Opens the modal.
  5472. *
  5473. * @fires ModalDialog#beforemodalopen
  5474. * @fires ModalDialog#modalopen
  5475. */
  5476. open() {
  5477. if (!this.opened_) {
  5478. const player = this.player();
  5479. /**
  5480. * Fired just before a `ModalDialog` is opened.
  5481. *
  5482. * @event ModalDialog#beforemodalopen
  5483. * @type {Event}
  5484. */
  5485. this.trigger('beforemodalopen');
  5486. this.opened_ = true;
  5487. // Fill content if the modal has never opened before and
  5488. // never been filled.
  5489. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {
  5490. this.fill();
  5491. }
  5492. // If the player was playing, pause it and take note of its previously
  5493. // playing state.
  5494. this.wasPlaying_ = !player.paused();
  5495. if (this.options_.pauseOnOpen && this.wasPlaying_) {
  5496. player.pause();
  5497. }
  5498. this.on('keydown', this.handleKeyDown_);
  5499. // Hide controls and note if they were enabled.
  5500. this.hadControls_ = player.controls();
  5501. player.controls(false);
  5502. this.show();
  5503. this.conditionalFocus_();
  5504. this.el().setAttribute('aria-hidden', 'false');
  5505. /**
  5506. * Fired just after a `ModalDialog` is opened.
  5507. *
  5508. * @event ModalDialog#modalopen
  5509. * @type {Event}
  5510. */
  5511. this.trigger('modalopen');
  5512. this.hasBeenOpened_ = true;
  5513. }
  5514. }
  5515. /**
  5516. * If the `ModalDialog` is currently open or closed.
  5517. *
  5518. * @param {boolean} [value]
  5519. * If given, it will open (`true`) or close (`false`) the modal.
  5520. *
  5521. * @return {boolean}
  5522. * the current open state of the modaldialog
  5523. */
  5524. opened(value) {
  5525. if (typeof value === 'boolean') {
  5526. this[value ? 'open' : 'close']();
  5527. }
  5528. return this.opened_;
  5529. }
  5530. /**
  5531. * Closes the modal, does nothing if the `ModalDialog` is
  5532. * not open.
  5533. *
  5534. * @fires ModalDialog#beforemodalclose
  5535. * @fires ModalDialog#modalclose
  5536. */
  5537. close() {
  5538. if (!this.opened_) {
  5539. return;
  5540. }
  5541. const player = this.player();
  5542. /**
  5543. * Fired just before a `ModalDialog` is closed.
  5544. *
  5545. * @event ModalDialog#beforemodalclose
  5546. * @type {Event}
  5547. */
  5548. this.trigger('beforemodalclose');
  5549. this.opened_ = false;
  5550. if (this.wasPlaying_ && this.options_.pauseOnOpen) {
  5551. player.play();
  5552. }
  5553. this.off('keydown', this.handleKeyDown_);
  5554. if (this.hadControls_) {
  5555. player.controls(true);
  5556. }
  5557. this.hide();
  5558. this.el().setAttribute('aria-hidden', 'true');
  5559. /**
  5560. * Fired just after a `ModalDialog` is closed.
  5561. *
  5562. * @event ModalDialog#modalclose
  5563. * @type {Event}
  5564. */
  5565. this.trigger('modalclose');
  5566. this.conditionalBlur_();
  5567. if (this.options_.temporary) {
  5568. this.dispose();
  5569. }
  5570. }
  5571. /**
  5572. * Check to see if the `ModalDialog` is closeable via the UI.
  5573. *
  5574. * @param {boolean} [value]
  5575. * If given as a boolean, it will set the `closeable` option.
  5576. *
  5577. * @return {boolean}
  5578. * Returns the final value of the closable option.
  5579. */
  5580. closeable(value) {
  5581. if (typeof value === 'boolean') {
  5582. const closeable = this.closeable_ = !!value;
  5583. let close = this.getChild('closeButton');
  5584. // If this is being made closeable and has no close button, add one.
  5585. if (closeable && !close) {
  5586. // The close button should be a child of the modal - not its
  5587. // content element, so temporarily change the content element.
  5588. const temp = this.contentEl_;
  5589. this.contentEl_ = this.el_;
  5590. close = this.addChild('closeButton', {
  5591. controlText: 'Close Modal Dialog'
  5592. });
  5593. this.contentEl_ = temp;
  5594. this.on(close, 'close', this.close_);
  5595. }
  5596. // If this is being made uncloseable and has a close button, remove it.
  5597. if (!closeable && close) {
  5598. this.off(close, 'close', this.close_);
  5599. this.removeChild(close);
  5600. close.dispose();
  5601. }
  5602. }
  5603. return this.closeable_;
  5604. }
  5605. /**
  5606. * Fill the modal's content element with the modal's "content" option.
  5607. * The content element will be emptied before this change takes place.
  5608. */
  5609. fill() {
  5610. this.fillWith(this.content());
  5611. }
  5612. /**
  5613. * Fill the modal's content element with arbitrary content.
  5614. * The content element will be emptied before this change takes place.
  5615. *
  5616. * @fires ModalDialog#beforemodalfill
  5617. * @fires ModalDialog#modalfill
  5618. *
  5619. * @param { import('./utils/dom').ContentDescriptor} [content]
  5620. * The same rules apply to this as apply to the `content` option.
  5621. */
  5622. fillWith(content) {
  5623. const contentEl = this.contentEl();
  5624. const parentEl = contentEl.parentNode;
  5625. const nextSiblingEl = contentEl.nextSibling;
  5626. /**
  5627. * Fired just before a `ModalDialog` is filled with content.
  5628. *
  5629. * @event ModalDialog#beforemodalfill
  5630. * @type {Event}
  5631. */
  5632. this.trigger('beforemodalfill');
  5633. this.hasBeenFilled_ = true;
  5634. // Detach the content element from the DOM before performing
  5635. // manipulation to avoid modifying the live DOM multiple times.
  5636. parentEl.removeChild(contentEl);
  5637. this.empty();
  5638. insertContent(contentEl, content);
  5639. /**
  5640. * Fired just after a `ModalDialog` is filled with content.
  5641. *
  5642. * @event ModalDialog#modalfill
  5643. * @type {Event}
  5644. */
  5645. this.trigger('modalfill');
  5646. // Re-inject the re-filled content element.
  5647. if (nextSiblingEl) {
  5648. parentEl.insertBefore(contentEl, nextSiblingEl);
  5649. } else {
  5650. parentEl.appendChild(contentEl);
  5651. }
  5652. // make sure that the close button is last in the dialog DOM
  5653. const closeButton = this.getChild('closeButton');
  5654. if (closeButton) {
  5655. parentEl.appendChild(closeButton.el_);
  5656. }
  5657. }
  5658. /**
  5659. * Empties the content element. This happens anytime the modal is filled.
  5660. *
  5661. * @fires ModalDialog#beforemodalempty
  5662. * @fires ModalDialog#modalempty
  5663. */
  5664. empty() {
  5665. /**
  5666. * Fired just before a `ModalDialog` is emptied.
  5667. *
  5668. * @event ModalDialog#beforemodalempty
  5669. * @type {Event}
  5670. */
  5671. this.trigger('beforemodalempty');
  5672. emptyEl(this.contentEl());
  5673. /**
  5674. * Fired just after a `ModalDialog` is emptied.
  5675. *
  5676. * @event ModalDialog#modalempty
  5677. * @type {Event}
  5678. */
  5679. this.trigger('modalempty');
  5680. }
  5681. /**
  5682. * Gets or sets the modal content, which gets normalized before being
  5683. * rendered into the DOM.
  5684. *
  5685. * This does not update the DOM or fill the modal, but it is called during
  5686. * that process.
  5687. *
  5688. * @param { import('./utils/dom').ContentDescriptor} [value]
  5689. * If defined, sets the internal content value to be used on the
  5690. * next call(s) to `fill`. This value is normalized before being
  5691. * inserted. To "clear" the internal content value, pass `null`.
  5692. *
  5693. * @return { import('./utils/dom').ContentDescriptor}
  5694. * The current content of the modal dialog
  5695. */
  5696. content(value) {
  5697. if (typeof value !== 'undefined') {
  5698. this.content_ = value;
  5699. }
  5700. return this.content_;
  5701. }
  5702. /**
  5703. * conditionally focus the modal dialog if focus was previously on the player.
  5704. *
  5705. * @private
  5706. */
  5707. conditionalFocus_() {
  5708. const activeEl = document.activeElement;
  5709. const playerEl = this.player_.el_;
  5710. this.previouslyActiveEl_ = null;
  5711. if (playerEl.contains(activeEl) || playerEl === activeEl) {
  5712. this.previouslyActiveEl_ = activeEl;
  5713. this.focus();
  5714. }
  5715. }
  5716. /**
  5717. * conditionally blur the element and refocus the last focused element
  5718. *
  5719. * @private
  5720. */
  5721. conditionalBlur_() {
  5722. if (this.previouslyActiveEl_) {
  5723. this.previouslyActiveEl_.focus();
  5724. this.previouslyActiveEl_ = null;
  5725. }
  5726. }
  5727. /**
  5728. * Keydown handler. Attached when modal is focused.
  5729. *
  5730. * @listens keydown
  5731. */
  5732. handleKeyDown(event) {
  5733. // Do not allow keydowns to reach out of the modal dialog.
  5734. event.stopPropagation();
  5735. if (keycode.isEventKey(event, 'Escape') && this.closeable()) {
  5736. event.preventDefault();
  5737. this.close();
  5738. return;
  5739. }
  5740. // exit early if it isn't a tab key
  5741. if (!keycode.isEventKey(event, 'Tab')) {
  5742. return;
  5743. }
  5744. const focusableEls = this.focusableEls_();
  5745. const activeEl = this.el_.querySelector(':focus');
  5746. let focusIndex;
  5747. for (let i = 0; i < focusableEls.length; i++) {
  5748. if (activeEl === focusableEls[i]) {
  5749. focusIndex = i;
  5750. break;
  5751. }
  5752. }
  5753. if (document.activeElement === this.el_) {
  5754. focusIndex = 0;
  5755. }
  5756. if (event.shiftKey && focusIndex === 0) {
  5757. focusableEls[focusableEls.length - 1].focus();
  5758. event.preventDefault();
  5759. } else if (!event.shiftKey && focusIndex === focusableEls.length - 1) {
  5760. focusableEls[0].focus();
  5761. event.preventDefault();
  5762. }
  5763. }
  5764. /**
  5765. * get all focusable elements
  5766. *
  5767. * @private
  5768. */
  5769. focusableEls_() {
  5770. const allChildren = this.el_.querySelectorAll('*');
  5771. return Array.prototype.filter.call(allChildren, child => {
  5772. return (child instanceof window.HTMLAnchorElement || child instanceof window.HTMLAreaElement) && child.hasAttribute('href') || (child instanceof window.HTMLInputElement || child instanceof window.HTMLSelectElement || child instanceof window.HTMLTextAreaElement || child instanceof window.HTMLButtonElement) && !child.hasAttribute('disabled') || child instanceof window.HTMLIFrameElement || child instanceof window.HTMLObjectElement || child instanceof window.HTMLEmbedElement || child.hasAttribute('tabindex') && child.getAttribute('tabindex') !== -1 || child.hasAttribute('contenteditable');
  5773. });
  5774. }
  5775. }
  5776. /**
  5777. * Default options for `ModalDialog` default options.
  5778. *
  5779. * @type {Object}
  5780. * @private
  5781. */
  5782. ModalDialog.prototype.options_ = {
  5783. pauseOnOpen: true,
  5784. temporary: true
  5785. };
  5786. Component$1.registerComponent('ModalDialog', ModalDialog);
  5787. /**
  5788. * @file track-list.js
  5789. */
  5790. /**
  5791. * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and
  5792. * {@link VideoTrackList}
  5793. *
  5794. * @extends EventTarget
  5795. */
  5796. class TrackList extends EventTarget$2 {
  5797. /**
  5798. * Create an instance of this class
  5799. *
  5800. * @param { import('./track').default[] } tracks
  5801. * A list of tracks to initialize the list with.
  5802. *
  5803. * @abstract
  5804. */
  5805. constructor(tracks = []) {
  5806. super();
  5807. this.tracks_ = [];
  5808. /**
  5809. * @memberof TrackList
  5810. * @member {number} length
  5811. * The current number of `Track`s in the this Trackist.
  5812. * @instance
  5813. */
  5814. Object.defineProperty(this, 'length', {
  5815. get() {
  5816. return this.tracks_.length;
  5817. }
  5818. });
  5819. for (let i = 0; i < tracks.length; i++) {
  5820. this.addTrack(tracks[i]);
  5821. }
  5822. }
  5823. /**
  5824. * Add a {@link Track} to the `TrackList`
  5825. *
  5826. * @param { import('./track').default } track
  5827. * The audio, video, or text track to add to the list.
  5828. *
  5829. * @fires TrackList#addtrack
  5830. */
  5831. addTrack(track) {
  5832. const index = this.tracks_.length;
  5833. if (!('' + index in this)) {
  5834. Object.defineProperty(this, index, {
  5835. get() {
  5836. return this.tracks_[index];
  5837. }
  5838. });
  5839. }
  5840. // Do not add duplicate tracks
  5841. if (this.tracks_.indexOf(track) === -1) {
  5842. this.tracks_.push(track);
  5843. /**
  5844. * Triggered when a track is added to a track list.
  5845. *
  5846. * @event TrackList#addtrack
  5847. * @type {Event}
  5848. * @property {Track} track
  5849. * A reference to track that was added.
  5850. */
  5851. this.trigger({
  5852. track,
  5853. type: 'addtrack',
  5854. target: this
  5855. });
  5856. }
  5857. /**
  5858. * Triggered when a track label is changed.
  5859. *
  5860. * @event TrackList#addtrack
  5861. * @type {Event}
  5862. * @property {Track} track
  5863. * A reference to track that was added.
  5864. */
  5865. track.labelchange_ = () => {
  5866. this.trigger({
  5867. track,
  5868. type: 'labelchange',
  5869. target: this
  5870. });
  5871. };
  5872. if (isEvented(track)) {
  5873. track.addEventListener('labelchange', track.labelchange_);
  5874. }
  5875. }
  5876. /**
  5877. * Remove a {@link Track} from the `TrackList`
  5878. *
  5879. * @param { import('./track').default } rtrack
  5880. * The audio, video, or text track to remove from the list.
  5881. *
  5882. * @fires TrackList#removetrack
  5883. */
  5884. removeTrack(rtrack) {
  5885. let track;
  5886. for (let i = 0, l = this.length; i < l; i++) {
  5887. if (this[i] === rtrack) {
  5888. track = this[i];
  5889. if (track.off) {
  5890. track.off();
  5891. }
  5892. this.tracks_.splice(i, 1);
  5893. break;
  5894. }
  5895. }
  5896. if (!track) {
  5897. return;
  5898. }
  5899. /**
  5900. * Triggered when a track is removed from track list.
  5901. *
  5902. * @event TrackList#removetrack
  5903. * @type {Event}
  5904. * @property {Track} track
  5905. * A reference to track that was removed.
  5906. */
  5907. this.trigger({
  5908. track,
  5909. type: 'removetrack',
  5910. target: this
  5911. });
  5912. }
  5913. /**
  5914. * Get a Track from the TrackList by a tracks id
  5915. *
  5916. * @param {string} id - the id of the track to get
  5917. * @method getTrackById
  5918. * @return { import('./track').default }
  5919. * @private
  5920. */
  5921. getTrackById(id) {
  5922. let result = null;
  5923. for (let i = 0, l = this.length; i < l; i++) {
  5924. const track = this[i];
  5925. if (track.id === id) {
  5926. result = track;
  5927. break;
  5928. }
  5929. }
  5930. return result;
  5931. }
  5932. }
  5933. /**
  5934. * Triggered when a different track is selected/enabled.
  5935. *
  5936. * @event TrackList#change
  5937. * @type {Event}
  5938. */
  5939. /**
  5940. * Events that can be called with on + eventName. See {@link EventHandler}.
  5941. *
  5942. * @property {Object} TrackList#allowedEvents_
  5943. * @private
  5944. */
  5945. TrackList.prototype.allowedEvents_ = {
  5946. change: 'change',
  5947. addtrack: 'addtrack',
  5948. removetrack: 'removetrack',
  5949. labelchange: 'labelchange'
  5950. };
  5951. // emulate attribute EventHandler support to allow for feature detection
  5952. for (const event in TrackList.prototype.allowedEvents_) {
  5953. TrackList.prototype['on' + event] = null;
  5954. }
  5955. /**
  5956. * @file audio-track-list.js
  5957. */
  5958. /**
  5959. * Anywhere we call this function we diverge from the spec
  5960. * as we only support one enabled audiotrack at a time
  5961. *
  5962. * @param {AudioTrackList} list
  5963. * list to work on
  5964. *
  5965. * @param { import('./audio-track').default } track
  5966. * The track to skip
  5967. *
  5968. * @private
  5969. */
  5970. const disableOthers$1 = function (list, track) {
  5971. for (let i = 0; i < list.length; i++) {
  5972. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  5973. continue;
  5974. }
  5975. // another audio track is enabled, disable it
  5976. list[i].enabled = false;
  5977. }
  5978. };
  5979. /**
  5980. * The current list of {@link AudioTrack} for a media file.
  5981. *
  5982. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist}
  5983. * @extends TrackList
  5984. */
  5985. class AudioTrackList extends TrackList {
  5986. /**
  5987. * Create an instance of this class.
  5988. *
  5989. * @param {AudioTrack[]} [tracks=[]]
  5990. * A list of `AudioTrack` to instantiate the list with.
  5991. */
  5992. constructor(tracks = []) {
  5993. // make sure only 1 track is enabled
  5994. // sorted from last index to first index
  5995. for (let i = tracks.length - 1; i >= 0; i--) {
  5996. if (tracks[i].enabled) {
  5997. disableOthers$1(tracks, tracks[i]);
  5998. break;
  5999. }
  6000. }
  6001. super(tracks);
  6002. this.changing_ = false;
  6003. }
  6004. /**
  6005. * Add an {@link AudioTrack} to the `AudioTrackList`.
  6006. *
  6007. * @param { import('./audio-track').default } track
  6008. * The AudioTrack to add to the list
  6009. *
  6010. * @fires TrackList#addtrack
  6011. */
  6012. addTrack(track) {
  6013. if (track.enabled) {
  6014. disableOthers$1(this, track);
  6015. }
  6016. super.addTrack(track);
  6017. // native tracks don't have this
  6018. if (!track.addEventListener) {
  6019. return;
  6020. }
  6021. track.enabledChange_ = () => {
  6022. // when we are disabling other tracks (since we don't support
  6023. // more than one track at a time) we will set changing_
  6024. // to true so that we don't trigger additional change events
  6025. if (this.changing_) {
  6026. return;
  6027. }
  6028. this.changing_ = true;
  6029. disableOthers$1(this, track);
  6030. this.changing_ = false;
  6031. this.trigger('change');
  6032. };
  6033. /**
  6034. * @listens AudioTrack#enabledchange
  6035. * @fires TrackList#change
  6036. */
  6037. track.addEventListener('enabledchange', track.enabledChange_);
  6038. }
  6039. removeTrack(rtrack) {
  6040. super.removeTrack(rtrack);
  6041. if (rtrack.removeEventListener && rtrack.enabledChange_) {
  6042. rtrack.removeEventListener('enabledchange', rtrack.enabledChange_);
  6043. rtrack.enabledChange_ = null;
  6044. }
  6045. }
  6046. }
  6047. /**
  6048. * @file video-track-list.js
  6049. */
  6050. /**
  6051. * Un-select all other {@link VideoTrack}s that are selected.
  6052. *
  6053. * @param {VideoTrackList} list
  6054. * list to work on
  6055. *
  6056. * @param { import('./video-track').default } track
  6057. * The track to skip
  6058. *
  6059. * @private
  6060. */
  6061. const disableOthers = function (list, track) {
  6062. for (let i = 0; i < list.length; i++) {
  6063. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  6064. continue;
  6065. }
  6066. // another video track is enabled, disable it
  6067. list[i].selected = false;
  6068. }
  6069. };
  6070. /**
  6071. * The current list of {@link VideoTrack} for a video.
  6072. *
  6073. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist}
  6074. * @extends TrackList
  6075. */
  6076. class VideoTrackList extends TrackList {
  6077. /**
  6078. * Create an instance of this class.
  6079. *
  6080. * @param {VideoTrack[]} [tracks=[]]
  6081. * A list of `VideoTrack` to instantiate the list with.
  6082. */
  6083. constructor(tracks = []) {
  6084. // make sure only 1 track is enabled
  6085. // sorted from last index to first index
  6086. for (let i = tracks.length - 1; i >= 0; i--) {
  6087. if (tracks[i].selected) {
  6088. disableOthers(tracks, tracks[i]);
  6089. break;
  6090. }
  6091. }
  6092. super(tracks);
  6093. this.changing_ = false;
  6094. /**
  6095. * @member {number} VideoTrackList#selectedIndex
  6096. * The current index of the selected {@link VideoTrack`}.
  6097. */
  6098. Object.defineProperty(this, 'selectedIndex', {
  6099. get() {
  6100. for (let i = 0; i < this.length; i++) {
  6101. if (this[i].selected) {
  6102. return i;
  6103. }
  6104. }
  6105. return -1;
  6106. },
  6107. set() {}
  6108. });
  6109. }
  6110. /**
  6111. * Add a {@link VideoTrack} to the `VideoTrackList`.
  6112. *
  6113. * @param { import('./video-track').default } track
  6114. * The VideoTrack to add to the list
  6115. *
  6116. * @fires TrackList#addtrack
  6117. */
  6118. addTrack(track) {
  6119. if (track.selected) {
  6120. disableOthers(this, track);
  6121. }
  6122. super.addTrack(track);
  6123. // native tracks don't have this
  6124. if (!track.addEventListener) {
  6125. return;
  6126. }
  6127. track.selectedChange_ = () => {
  6128. if (this.changing_) {
  6129. return;
  6130. }
  6131. this.changing_ = true;
  6132. disableOthers(this, track);
  6133. this.changing_ = false;
  6134. this.trigger('change');
  6135. };
  6136. /**
  6137. * @listens VideoTrack#selectedchange
  6138. * @fires TrackList#change
  6139. */
  6140. track.addEventListener('selectedchange', track.selectedChange_);
  6141. }
  6142. removeTrack(rtrack) {
  6143. super.removeTrack(rtrack);
  6144. if (rtrack.removeEventListener && rtrack.selectedChange_) {
  6145. rtrack.removeEventListener('selectedchange', rtrack.selectedChange_);
  6146. rtrack.selectedChange_ = null;
  6147. }
  6148. }
  6149. }
  6150. /**
  6151. * @file text-track-list.js
  6152. */
  6153. /**
  6154. * The current list of {@link TextTrack} for a media file.
  6155. *
  6156. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist}
  6157. * @extends TrackList
  6158. */
  6159. class TextTrackList extends TrackList {
  6160. /**
  6161. * Add a {@link TextTrack} to the `TextTrackList`
  6162. *
  6163. * @param { import('./text-track').default } track
  6164. * The text track to add to the list.
  6165. *
  6166. * @fires TrackList#addtrack
  6167. */
  6168. addTrack(track) {
  6169. super.addTrack(track);
  6170. if (!this.queueChange_) {
  6171. this.queueChange_ = () => this.queueTrigger('change');
  6172. }
  6173. if (!this.triggerSelectedlanguagechange) {
  6174. this.triggerSelectedlanguagechange_ = () => this.trigger('selectedlanguagechange');
  6175. }
  6176. /**
  6177. * @listens TextTrack#modechange
  6178. * @fires TrackList#change
  6179. */
  6180. track.addEventListener('modechange', this.queueChange_);
  6181. const nonLanguageTextTrackKind = ['metadata', 'chapters'];
  6182. if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) {
  6183. track.addEventListener('modechange', this.triggerSelectedlanguagechange_);
  6184. }
  6185. }
  6186. removeTrack(rtrack) {
  6187. super.removeTrack(rtrack);
  6188. // manually remove the event handlers we added
  6189. if (rtrack.removeEventListener) {
  6190. if (this.queueChange_) {
  6191. rtrack.removeEventListener('modechange', this.queueChange_);
  6192. }
  6193. if (this.selectedlanguagechange_) {
  6194. rtrack.removeEventListener('modechange', this.triggerSelectedlanguagechange_);
  6195. }
  6196. }
  6197. }
  6198. }
  6199. /**
  6200. * @file html-track-element-list.js
  6201. */
  6202. /**
  6203. * The current list of {@link HtmlTrackElement}s.
  6204. */
  6205. class HtmlTrackElementList {
  6206. /**
  6207. * Create an instance of this class.
  6208. *
  6209. * @param {HtmlTrackElement[]} [tracks=[]]
  6210. * A list of `HtmlTrackElement` to instantiate the list with.
  6211. */
  6212. constructor(trackElements = []) {
  6213. this.trackElements_ = [];
  6214. /**
  6215. * @memberof HtmlTrackElementList
  6216. * @member {number} length
  6217. * The current number of `Track`s in the this Trackist.
  6218. * @instance
  6219. */
  6220. Object.defineProperty(this, 'length', {
  6221. get() {
  6222. return this.trackElements_.length;
  6223. }
  6224. });
  6225. for (let i = 0, length = trackElements.length; i < length; i++) {
  6226. this.addTrackElement_(trackElements[i]);
  6227. }
  6228. }
  6229. /**
  6230. * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList`
  6231. *
  6232. * @param {HtmlTrackElement} trackElement
  6233. * The track element to add to the list.
  6234. *
  6235. * @private
  6236. */
  6237. addTrackElement_(trackElement) {
  6238. const index = this.trackElements_.length;
  6239. if (!('' + index in this)) {
  6240. Object.defineProperty(this, index, {
  6241. get() {
  6242. return this.trackElements_[index];
  6243. }
  6244. });
  6245. }
  6246. // Do not add duplicate elements
  6247. if (this.trackElements_.indexOf(trackElement) === -1) {
  6248. this.trackElements_.push(trackElement);
  6249. }
  6250. }
  6251. /**
  6252. * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an
  6253. * {@link TextTrack}.
  6254. *
  6255. * @param {TextTrack} track
  6256. * The track associated with a track element.
  6257. *
  6258. * @return {HtmlTrackElement|undefined}
  6259. * The track element that was found or undefined.
  6260. *
  6261. * @private
  6262. */
  6263. getTrackElementByTrack_(track) {
  6264. let trackElement_;
  6265. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6266. if (track === this.trackElements_[i].track) {
  6267. trackElement_ = this.trackElements_[i];
  6268. break;
  6269. }
  6270. }
  6271. return trackElement_;
  6272. }
  6273. /**
  6274. * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList`
  6275. *
  6276. * @param {HtmlTrackElement} trackElement
  6277. * The track element to remove from the list.
  6278. *
  6279. * @private
  6280. */
  6281. removeTrackElement_(trackElement) {
  6282. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6283. if (trackElement === this.trackElements_[i]) {
  6284. if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === 'function') {
  6285. this.trackElements_[i].track.off();
  6286. }
  6287. if (typeof this.trackElements_[i].off === 'function') {
  6288. this.trackElements_[i].off();
  6289. }
  6290. this.trackElements_.splice(i, 1);
  6291. break;
  6292. }
  6293. }
  6294. }
  6295. }
  6296. /**
  6297. * @file text-track-cue-list.js
  6298. */
  6299. /**
  6300. * @typedef {Object} TextTrackCueList~TextTrackCue
  6301. *
  6302. * @property {string} id
  6303. * The unique id for this text track cue
  6304. *
  6305. * @property {number} startTime
  6306. * The start time for this text track cue
  6307. *
  6308. * @property {number} endTime
  6309. * The end time for this text track cue
  6310. *
  6311. * @property {boolean} pauseOnExit
  6312. * Pause when the end time is reached if true.
  6313. *
  6314. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue}
  6315. */
  6316. /**
  6317. * A List of TextTrackCues.
  6318. *
  6319. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist}
  6320. */
  6321. class TextTrackCueList {
  6322. /**
  6323. * Create an instance of this class..
  6324. *
  6325. * @param {Array} cues
  6326. * A list of cues to be initialized with
  6327. */
  6328. constructor(cues) {
  6329. TextTrackCueList.prototype.setCues_.call(this, cues);
  6330. /**
  6331. * @memberof TextTrackCueList
  6332. * @member {number} length
  6333. * The current number of `TextTrackCue`s in the TextTrackCueList.
  6334. * @instance
  6335. */
  6336. Object.defineProperty(this, 'length', {
  6337. get() {
  6338. return this.length_;
  6339. }
  6340. });
  6341. }
  6342. /**
  6343. * A setter for cues in this list. Creates getters
  6344. * an an index for the cues.
  6345. *
  6346. * @param {Array} cues
  6347. * An array of cues to set
  6348. *
  6349. * @private
  6350. */
  6351. setCues_(cues) {
  6352. const oldLength = this.length || 0;
  6353. let i = 0;
  6354. const l = cues.length;
  6355. this.cues_ = cues;
  6356. this.length_ = cues.length;
  6357. const defineProp = function (index) {
  6358. if (!('' + index in this)) {
  6359. Object.defineProperty(this, '' + index, {
  6360. get() {
  6361. return this.cues_[index];
  6362. }
  6363. });
  6364. }
  6365. };
  6366. if (oldLength < l) {
  6367. i = oldLength;
  6368. for (; i < l; i++) {
  6369. defineProp.call(this, i);
  6370. }
  6371. }
  6372. }
  6373. /**
  6374. * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id.
  6375. *
  6376. * @param {string} id
  6377. * The id of the cue that should be searched for.
  6378. *
  6379. * @return {TextTrackCueList~TextTrackCue|null}
  6380. * A single cue or null if none was found.
  6381. */
  6382. getCueById(id) {
  6383. let result = null;
  6384. for (let i = 0, l = this.length; i < l; i++) {
  6385. const cue = this[i];
  6386. if (cue.id === id) {
  6387. result = cue;
  6388. break;
  6389. }
  6390. }
  6391. return result;
  6392. }
  6393. }
  6394. /**
  6395. * @file track-kinds.js
  6396. */
  6397. /**
  6398. * All possible `VideoTrackKind`s
  6399. *
  6400. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind
  6401. * @typedef VideoTrack~Kind
  6402. * @enum
  6403. */
  6404. const VideoTrackKind = {
  6405. alternative: 'alternative',
  6406. captions: 'captions',
  6407. main: 'main',
  6408. sign: 'sign',
  6409. subtitles: 'subtitles',
  6410. commentary: 'commentary'
  6411. };
  6412. /**
  6413. * All possible `AudioTrackKind`s
  6414. *
  6415. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind
  6416. * @typedef AudioTrack~Kind
  6417. * @enum
  6418. */
  6419. const AudioTrackKind = {
  6420. 'alternative': 'alternative',
  6421. 'descriptions': 'descriptions',
  6422. 'main': 'main',
  6423. 'main-desc': 'main-desc',
  6424. 'translation': 'translation',
  6425. 'commentary': 'commentary'
  6426. };
  6427. /**
  6428. * All possible `TextTrackKind`s
  6429. *
  6430. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind
  6431. * @typedef TextTrack~Kind
  6432. * @enum
  6433. */
  6434. const TextTrackKind = {
  6435. subtitles: 'subtitles',
  6436. captions: 'captions',
  6437. descriptions: 'descriptions',
  6438. chapters: 'chapters',
  6439. metadata: 'metadata'
  6440. };
  6441. /**
  6442. * All possible `TextTrackMode`s
  6443. *
  6444. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
  6445. * @typedef TextTrack~Mode
  6446. * @enum
  6447. */
  6448. const TextTrackMode = {
  6449. disabled: 'disabled',
  6450. hidden: 'hidden',
  6451. showing: 'showing'
  6452. };
  6453. /**
  6454. * @file track.js
  6455. */
  6456. /**
  6457. * A Track class that contains all of the common functionality for {@link AudioTrack},
  6458. * {@link VideoTrack}, and {@link TextTrack}.
  6459. *
  6460. * > Note: This class should not be used directly
  6461. *
  6462. * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html}
  6463. * @extends EventTarget
  6464. * @abstract
  6465. */
  6466. class Track extends EventTarget$2 {
  6467. /**
  6468. * Create an instance of this class.
  6469. *
  6470. * @param {Object} [options={}]
  6471. * Object of option names and values
  6472. *
  6473. * @param {string} [options.kind='']
  6474. * A valid kind for the track type you are creating.
  6475. *
  6476. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6477. * A unique id for this AudioTrack.
  6478. *
  6479. * @param {string} [options.label='']
  6480. * The menu label for this track.
  6481. *
  6482. * @param {string} [options.language='']
  6483. * A valid two character language code.
  6484. *
  6485. * @abstract
  6486. */
  6487. constructor(options = {}) {
  6488. super();
  6489. const trackProps = {
  6490. id: options.id || 'vjs_track_' + newGUID(),
  6491. kind: options.kind || '',
  6492. language: options.language || ''
  6493. };
  6494. let label = options.label || '';
  6495. /**
  6496. * @memberof Track
  6497. * @member {string} id
  6498. * The id of this track. Cannot be changed after creation.
  6499. * @instance
  6500. *
  6501. * @readonly
  6502. */
  6503. /**
  6504. * @memberof Track
  6505. * @member {string} kind
  6506. * The kind of track that this is. Cannot be changed after creation.
  6507. * @instance
  6508. *
  6509. * @readonly
  6510. */
  6511. /**
  6512. * @memberof Track
  6513. * @member {string} language
  6514. * The two letter language code for this track. Cannot be changed after
  6515. * creation.
  6516. * @instance
  6517. *
  6518. * @readonly
  6519. */
  6520. for (const key in trackProps) {
  6521. Object.defineProperty(this, key, {
  6522. get() {
  6523. return trackProps[key];
  6524. },
  6525. set() {}
  6526. });
  6527. }
  6528. /**
  6529. * @memberof Track
  6530. * @member {string} label
  6531. * The label of this track. Cannot be changed after creation.
  6532. * @instance
  6533. *
  6534. * @fires Track#labelchange
  6535. */
  6536. Object.defineProperty(this, 'label', {
  6537. get() {
  6538. return label;
  6539. },
  6540. set(newLabel) {
  6541. if (newLabel !== label) {
  6542. label = newLabel;
  6543. /**
  6544. * An event that fires when label changes on this track.
  6545. *
  6546. * > Note: This is not part of the spec!
  6547. *
  6548. * @event Track#labelchange
  6549. * @type {Event}
  6550. */
  6551. this.trigger('labelchange');
  6552. }
  6553. }
  6554. });
  6555. }
  6556. }
  6557. /**
  6558. * @file url.js
  6559. * @module url
  6560. */
  6561. /**
  6562. * @typedef {Object} url:URLObject
  6563. *
  6564. * @property {string} protocol
  6565. * The protocol of the url that was parsed.
  6566. *
  6567. * @property {string} hostname
  6568. * The hostname of the url that was parsed.
  6569. *
  6570. * @property {string} port
  6571. * The port of the url that was parsed.
  6572. *
  6573. * @property {string} pathname
  6574. * The pathname of the url that was parsed.
  6575. *
  6576. * @property {string} search
  6577. * The search query of the url that was parsed.
  6578. *
  6579. * @property {string} hash
  6580. * The hash of the url that was parsed.
  6581. *
  6582. * @property {string} host
  6583. * The host of the url that was parsed.
  6584. */
  6585. /**
  6586. * Resolve and parse the elements of a URL.
  6587. *
  6588. * @function
  6589. * @param {String} url
  6590. * The url to parse
  6591. *
  6592. * @return {url:URLObject}
  6593. * An object of url details
  6594. */
  6595. const parseUrl = function (url) {
  6596. // This entire method can be replace with URL once we are able to drop IE11
  6597. const props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];
  6598. // add the url to an anchor and let the browser parse the URL
  6599. const a = document.createElement('a');
  6600. a.href = url;
  6601. // Copy the specific URL properties to a new object
  6602. // This is also needed for IE because the anchor loses its
  6603. // properties when it's removed from the dom
  6604. const details = {};
  6605. for (let i = 0; i < props.length; i++) {
  6606. details[props[i]] = a[props[i]];
  6607. }
  6608. // IE adds the port to the host property unlike everyone else. If
  6609. // a port identifier is added for standard ports, strip it.
  6610. if (details.protocol === 'http:') {
  6611. details.host = details.host.replace(/:80$/, '');
  6612. }
  6613. if (details.protocol === 'https:') {
  6614. details.host = details.host.replace(/:443$/, '');
  6615. }
  6616. if (!details.protocol) {
  6617. details.protocol = window.location.protocol;
  6618. }
  6619. /* istanbul ignore if */
  6620. if (!details.host) {
  6621. details.host = window.location.host;
  6622. }
  6623. return details;
  6624. };
  6625. /**
  6626. * Get absolute version of relative URL.
  6627. *
  6628. * @function
  6629. * @param {string} url
  6630. * URL to make absolute
  6631. *
  6632. * @return {string}
  6633. * Absolute URL
  6634. *
  6635. * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  6636. */
  6637. const getAbsoluteURL = function (url) {
  6638. // Check if absolute URL
  6639. if (!url.match(/^https?:\/\//)) {
  6640. // Add the url to an anchor and let the browser parse it to convert to an absolute url
  6641. const a = document.createElement('a');
  6642. a.href = url;
  6643. url = a.href;
  6644. }
  6645. return url;
  6646. };
  6647. /**
  6648. * Returns the extension of the passed file name. It will return an empty string
  6649. * if passed an invalid path.
  6650. *
  6651. * @function
  6652. * @param {string} path
  6653. * The fileName path like '/path/to/file.mp4'
  6654. *
  6655. * @return {string}
  6656. * The extension in lower case or an empty string if no
  6657. * extension could be found.
  6658. */
  6659. const getFileExtension = function (path) {
  6660. if (typeof path === 'string') {
  6661. const splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/;
  6662. const pathParts = splitPathRe.exec(path);
  6663. if (pathParts) {
  6664. return pathParts.pop().toLowerCase();
  6665. }
  6666. }
  6667. return '';
  6668. };
  6669. /**
  6670. * Returns whether the url passed is a cross domain request or not.
  6671. *
  6672. * @function
  6673. * @param {string} url
  6674. * The url to check.
  6675. *
  6676. * @param {Object} [winLoc]
  6677. * the domain to check the url against, defaults to window.location
  6678. *
  6679. * @param {string} [winLoc.protocol]
  6680. * The window location protocol defaults to window.location.protocol
  6681. *
  6682. * @param {string} [winLoc.host]
  6683. * The window location host defaults to window.location.host
  6684. *
  6685. * @return {boolean}
  6686. * Whether it is a cross domain request or not.
  6687. */
  6688. const isCrossOrigin = function (url, winLoc = window.location) {
  6689. const urlInfo = parseUrl(url);
  6690. // IE8 protocol relative urls will return ':' for protocol
  6691. const srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol;
  6692. // Check if url is for another domain/origin
  6693. // IE8 doesn't know location.origin, so we won't rely on it here
  6694. const crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host;
  6695. return crossOrigin;
  6696. };
  6697. var Url = /*#__PURE__*/Object.freeze({
  6698. __proto__: null,
  6699. parseUrl: parseUrl,
  6700. getAbsoluteURL: getAbsoluteURL,
  6701. getFileExtension: getFileExtension,
  6702. isCrossOrigin: isCrossOrigin
  6703. });
  6704. var win;
  6705. if (typeof window !== "undefined") {
  6706. win = window;
  6707. } else if (typeof commonjsGlobal !== "undefined") {
  6708. win = commonjsGlobal;
  6709. } else if (typeof self !== "undefined") {
  6710. win = self;
  6711. } else {
  6712. win = {};
  6713. }
  6714. var window_1 = win;
  6715. var _extends_1 = createCommonjsModule(function (module) {
  6716. function _extends() {
  6717. module.exports = _extends = Object.assign ? Object.assign.bind() : function (target) {
  6718. for (var i = 1; i < arguments.length; i++) {
  6719. var source = arguments[i];
  6720. for (var key in source) {
  6721. if (Object.prototype.hasOwnProperty.call(source, key)) {
  6722. target[key] = source[key];
  6723. }
  6724. }
  6725. }
  6726. return target;
  6727. }, module.exports.__esModule = true, module.exports["default"] = module.exports;
  6728. return _extends.apply(this, arguments);
  6729. }
  6730. module.exports = _extends, module.exports.__esModule = true, module.exports["default"] = module.exports;
  6731. });
  6732. var _extends$1 = unwrapExports(_extends_1);
  6733. var isFunction_1 = isFunction;
  6734. var toString = Object.prototype.toString;
  6735. function isFunction(fn) {
  6736. if (!fn) {
  6737. return false;
  6738. }
  6739. var string = toString.call(fn);
  6740. return string === '[object Function]' || typeof fn === 'function' && string !== '[object RegExp]' || typeof window !== 'undefined' && (
  6741. // IE8 and below
  6742. fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt);
  6743. }
  6744. var httpResponseHandler = function httpResponseHandler(callback, decodeResponseBody) {
  6745. if (decodeResponseBody === void 0) {
  6746. decodeResponseBody = false;
  6747. }
  6748. return function (err, response, responseBody) {
  6749. // if the XHR failed, return that error
  6750. if (err) {
  6751. callback(err);
  6752. return;
  6753. } // if the HTTP status code is 4xx or 5xx, the request also failed
  6754. if (response.statusCode >= 400 && response.statusCode <= 599) {
  6755. var cause = responseBody;
  6756. if (decodeResponseBody) {
  6757. if (window_1.TextDecoder) {
  6758. var charset = getCharset(response.headers && response.headers['content-type']);
  6759. try {
  6760. cause = new TextDecoder(charset).decode(responseBody);
  6761. } catch (e) {}
  6762. } else {
  6763. cause = String.fromCharCode.apply(null, new Uint8Array(responseBody));
  6764. }
  6765. }
  6766. callback({
  6767. cause: cause
  6768. });
  6769. return;
  6770. } // otherwise, request succeeded
  6771. callback(null, responseBody);
  6772. };
  6773. };
  6774. function getCharset(contentTypeHeader) {
  6775. if (contentTypeHeader === void 0) {
  6776. contentTypeHeader = '';
  6777. }
  6778. return contentTypeHeader.toLowerCase().split(';').reduce(function (charset, contentType) {
  6779. var _contentType$split = contentType.split('='),
  6780. type = _contentType$split[0],
  6781. value = _contentType$split[1];
  6782. if (type.trim() === 'charset') {
  6783. return value.trim();
  6784. }
  6785. return charset;
  6786. }, 'utf-8');
  6787. }
  6788. var httpHandler = httpResponseHandler;
  6789. createXHR.httpHandler = httpHandler;
  6790. /**
  6791. * @license
  6792. * slighly modified parse-headers 2.0.2 <https://github.com/kesla/parse-headers/>
  6793. * Copyright (c) 2014 David Björklund
  6794. * Available under the MIT license
  6795. * <https://github.com/kesla/parse-headers/blob/master/LICENCE>
  6796. */
  6797. var parseHeaders = function parseHeaders(headers) {
  6798. var result = {};
  6799. if (!headers) {
  6800. return result;
  6801. }
  6802. headers.trim().split('\n').forEach(function (row) {
  6803. var index = row.indexOf(':');
  6804. var key = row.slice(0, index).trim().toLowerCase();
  6805. var value = row.slice(index + 1).trim();
  6806. if (typeof result[key] === 'undefined') {
  6807. result[key] = value;
  6808. } else if (Array.isArray(result[key])) {
  6809. result[key].push(value);
  6810. } else {
  6811. result[key] = [result[key], value];
  6812. }
  6813. });
  6814. return result;
  6815. };
  6816. var lib = createXHR; // Allow use of default import syntax in TypeScript
  6817. var default_1 = createXHR;
  6818. createXHR.XMLHttpRequest = window_1.XMLHttpRequest || noop$1;
  6819. createXHR.XDomainRequest = "withCredentials" in new createXHR.XMLHttpRequest() ? createXHR.XMLHttpRequest : window_1.XDomainRequest;
  6820. forEachArray(["get", "put", "post", "patch", "head", "delete"], function (method) {
  6821. createXHR[method === "delete" ? "del" : method] = function (uri, options, callback) {
  6822. options = initParams(uri, options, callback);
  6823. options.method = method.toUpperCase();
  6824. return _createXHR(options);
  6825. };
  6826. });
  6827. function forEachArray(array, iterator) {
  6828. for (var i = 0; i < array.length; i++) {
  6829. iterator(array[i]);
  6830. }
  6831. }
  6832. function isEmpty(obj) {
  6833. for (var i in obj) {
  6834. if (obj.hasOwnProperty(i)) return false;
  6835. }
  6836. return true;
  6837. }
  6838. function initParams(uri, options, callback) {
  6839. var params = uri;
  6840. if (isFunction_1(options)) {
  6841. callback = options;
  6842. if (typeof uri === "string") {
  6843. params = {
  6844. uri: uri
  6845. };
  6846. }
  6847. } else {
  6848. params = _extends_1({}, options, {
  6849. uri: uri
  6850. });
  6851. }
  6852. params.callback = callback;
  6853. return params;
  6854. }
  6855. function createXHR(uri, options, callback) {
  6856. options = initParams(uri, options, callback);
  6857. return _createXHR(options);
  6858. }
  6859. function _createXHR(options) {
  6860. if (typeof options.callback === "undefined") {
  6861. throw new Error("callback argument missing");
  6862. }
  6863. var called = false;
  6864. var callback = function cbOnce(err, response, body) {
  6865. if (!called) {
  6866. called = true;
  6867. options.callback(err, response, body);
  6868. }
  6869. };
  6870. function readystatechange() {
  6871. if (xhr.readyState === 4) {
  6872. setTimeout(loadFunc, 0);
  6873. }
  6874. }
  6875. function getBody() {
  6876. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  6877. var body = undefined;
  6878. if (xhr.response) {
  6879. body = xhr.response;
  6880. } else {
  6881. body = xhr.responseText || getXml(xhr);
  6882. }
  6883. if (isJson) {
  6884. try {
  6885. body = JSON.parse(body);
  6886. } catch (e) {}
  6887. }
  6888. return body;
  6889. }
  6890. function errorFunc(evt) {
  6891. clearTimeout(timeoutTimer);
  6892. if (!(evt instanceof Error)) {
  6893. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error"));
  6894. }
  6895. evt.statusCode = 0;
  6896. return callback(evt, failureResponse);
  6897. } // will load the data & process the response in a special response object
  6898. function loadFunc() {
  6899. if (aborted) return;
  6900. var status;
  6901. clearTimeout(timeoutTimer);
  6902. if (options.useXDR && xhr.status === undefined) {
  6903. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  6904. status = 200;
  6905. } else {
  6906. status = xhr.status === 1223 ? 204 : xhr.status;
  6907. }
  6908. var response = failureResponse;
  6909. var err = null;
  6910. if (status !== 0) {
  6911. response = {
  6912. body: getBody(),
  6913. statusCode: status,
  6914. method: method,
  6915. headers: {},
  6916. url: uri,
  6917. rawRequest: xhr
  6918. };
  6919. if (xhr.getAllResponseHeaders) {
  6920. //remember xhr can in fact be XDR for CORS in IE
  6921. response.headers = parseHeaders(xhr.getAllResponseHeaders());
  6922. }
  6923. } else {
  6924. err = new Error("Internal XMLHttpRequest Error");
  6925. }
  6926. return callback(err, response, response.body);
  6927. }
  6928. var xhr = options.xhr || null;
  6929. if (!xhr) {
  6930. if (options.cors || options.useXDR) {
  6931. xhr = new createXHR.XDomainRequest();
  6932. } else {
  6933. xhr = new createXHR.XMLHttpRequest();
  6934. }
  6935. }
  6936. var key;
  6937. var aborted;
  6938. var uri = xhr.url = options.uri || options.url;
  6939. var method = xhr.method = options.method || "GET";
  6940. var body = options.body || options.data;
  6941. var headers = xhr.headers = options.headers || {};
  6942. var sync = !!options.sync;
  6943. var isJson = false;
  6944. var timeoutTimer;
  6945. var failureResponse = {
  6946. body: undefined,
  6947. headers: {},
  6948. statusCode: 0,
  6949. method: method,
  6950. url: uri,
  6951. rawRequest: xhr
  6952. };
  6953. if ("json" in options && options.json !== false) {
  6954. isJson = true;
  6955. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json"); //Don't override existing accept header declared by user
  6956. if (method !== "GET" && method !== "HEAD") {
  6957. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json"); //Don't override existing accept header declared by user
  6958. body = JSON.stringify(options.json === true ? body : options.json);
  6959. }
  6960. }
  6961. xhr.onreadystatechange = readystatechange;
  6962. xhr.onload = loadFunc;
  6963. xhr.onerror = errorFunc; // IE9 must have onprogress be set to a unique function.
  6964. xhr.onprogress = function () {// IE must die
  6965. };
  6966. xhr.onabort = function () {
  6967. aborted = true;
  6968. };
  6969. xhr.ontimeout = errorFunc;
  6970. xhr.open(method, uri, !sync, options.username, options.password); //has to be after open
  6971. if (!sync) {
  6972. xhr.withCredentials = !!options.withCredentials;
  6973. } // Cannot set timeout with sync request
  6974. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  6975. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  6976. if (!sync && options.timeout > 0) {
  6977. timeoutTimer = setTimeout(function () {
  6978. if (aborted) return;
  6979. aborted = true; //IE9 may still call readystatechange
  6980. xhr.abort("timeout");
  6981. var e = new Error("XMLHttpRequest timeout");
  6982. e.code = "ETIMEDOUT";
  6983. errorFunc(e);
  6984. }, options.timeout);
  6985. }
  6986. if (xhr.setRequestHeader) {
  6987. for (key in headers) {
  6988. if (headers.hasOwnProperty(key)) {
  6989. xhr.setRequestHeader(key, headers[key]);
  6990. }
  6991. }
  6992. } else if (options.headers && !isEmpty(options.headers)) {
  6993. throw new Error("Headers cannot be set on an XDomainRequest object");
  6994. }
  6995. if ("responseType" in options) {
  6996. xhr.responseType = options.responseType;
  6997. }
  6998. if ("beforeSend" in options && typeof options.beforeSend === "function") {
  6999. options.beforeSend(xhr);
  7000. } // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  7001. // XMLHttpRequest spec says to pass null as body to indicate no body
  7002. // See https://github.com/naugtur/xhr/issues/100.
  7003. xhr.send(body || null);
  7004. return xhr;
  7005. }
  7006. function getXml(xhr) {
  7007. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  7008. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  7009. try {
  7010. if (xhr.responseType === "document") {
  7011. return xhr.responseXML;
  7012. }
  7013. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror";
  7014. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  7015. return xhr.responseXML;
  7016. }
  7017. } catch (e) {}
  7018. return null;
  7019. }
  7020. function noop$1() {}
  7021. lib.default = default_1;
  7022. /**
  7023. * @file text-track.js
  7024. */
  7025. /**
  7026. * Takes a webvtt file contents and parses it into cues
  7027. *
  7028. * @param {string} srcContent
  7029. * webVTT file contents
  7030. *
  7031. * @param {TextTrack} track
  7032. * TextTrack to add cues to. Cues come from the srcContent.
  7033. *
  7034. * @private
  7035. */
  7036. const parseCues = function (srcContent, track) {
  7037. const parser = new window.WebVTT.Parser(window, window.vttjs, window.WebVTT.StringDecoder());
  7038. const errors = [];
  7039. parser.oncue = function (cue) {
  7040. track.addCue(cue);
  7041. };
  7042. parser.onparsingerror = function (error) {
  7043. errors.push(error);
  7044. };
  7045. parser.onflush = function () {
  7046. track.trigger({
  7047. type: 'loadeddata',
  7048. target: track
  7049. });
  7050. };
  7051. parser.parse(srcContent);
  7052. if (errors.length > 0) {
  7053. if (window.console && window.console.groupCollapsed) {
  7054. window.console.groupCollapsed(`Text Track parsing errors for ${track.src}`);
  7055. }
  7056. errors.forEach(error => log$1.error(error));
  7057. if (window.console && window.console.groupEnd) {
  7058. window.console.groupEnd();
  7059. }
  7060. }
  7061. parser.flush();
  7062. };
  7063. /**
  7064. * Load a `TextTrack` from a specified url.
  7065. *
  7066. * @param {string} src
  7067. * Url to load track from.
  7068. *
  7069. * @param {TextTrack} track
  7070. * Track to add cues to. Comes from the content at the end of `url`.
  7071. *
  7072. * @private
  7073. */
  7074. const loadTrack = function (src, track) {
  7075. const opts = {
  7076. uri: src
  7077. };
  7078. const crossOrigin = isCrossOrigin(src);
  7079. if (crossOrigin) {
  7080. opts.cors = crossOrigin;
  7081. }
  7082. const withCredentials = track.tech_.crossOrigin() === 'use-credentials';
  7083. if (withCredentials) {
  7084. opts.withCredentials = withCredentials;
  7085. }
  7086. lib(opts, bind_(this, function (err, response, responseBody) {
  7087. if (err) {
  7088. return log$1.error(err, response);
  7089. }
  7090. track.loaded_ = true;
  7091. // Make sure that vttjs has loaded, otherwise, wait till it finished loading
  7092. // NOTE: this is only used for the alt/video.novtt.js build
  7093. if (typeof window.WebVTT !== 'function') {
  7094. if (track.tech_) {
  7095. // to prevent use before define eslint error, we define loadHandler
  7096. // as a let here
  7097. track.tech_.any(['vttjsloaded', 'vttjserror'], event => {
  7098. if (event.type === 'vttjserror') {
  7099. log$1.error(`vttjs failed to load, stopping trying to process ${track.src}`);
  7100. return;
  7101. }
  7102. return parseCues(responseBody, track);
  7103. });
  7104. }
  7105. } else {
  7106. parseCues(responseBody, track);
  7107. }
  7108. }));
  7109. };
  7110. /**
  7111. * A representation of a single `TextTrack`.
  7112. *
  7113. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack}
  7114. * @extends Track
  7115. */
  7116. class TextTrack extends Track {
  7117. /**
  7118. * Create an instance of this class.
  7119. *
  7120. * @param {Object} options={}
  7121. * Object of option names and values
  7122. *
  7123. * @param { import('../tech/tech').default } options.tech
  7124. * A reference to the tech that owns this TextTrack.
  7125. *
  7126. * @param {TextTrack~Kind} [options.kind='subtitles']
  7127. * A valid text track kind.
  7128. *
  7129. * @param {TextTrack~Mode} [options.mode='disabled']
  7130. * A valid text track mode.
  7131. *
  7132. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7133. * A unique id for this TextTrack.
  7134. *
  7135. * @param {string} [options.label='']
  7136. * The menu label for this track.
  7137. *
  7138. * @param {string} [options.language='']
  7139. * A valid two character language code.
  7140. *
  7141. * @param {string} [options.srclang='']
  7142. * A valid two character language code. An alternative, but deprioritized
  7143. * version of `options.language`
  7144. *
  7145. * @param {string} [options.src]
  7146. * A url to TextTrack cues.
  7147. *
  7148. * @param {boolean} [options.default]
  7149. * If this track should default to on or off.
  7150. */
  7151. constructor(options = {}) {
  7152. if (!options.tech) {
  7153. throw new Error('A tech was not provided.');
  7154. }
  7155. const settings = merge$2(options, {
  7156. kind: TextTrackKind[options.kind] || 'subtitles',
  7157. language: options.language || options.srclang || ''
  7158. });
  7159. let mode = TextTrackMode[settings.mode] || 'disabled';
  7160. const default_ = settings.default;
  7161. if (settings.kind === 'metadata' || settings.kind === 'chapters') {
  7162. mode = 'hidden';
  7163. }
  7164. super(settings);
  7165. this.tech_ = settings.tech;
  7166. this.cues_ = [];
  7167. this.activeCues_ = [];
  7168. this.preload_ = this.tech_.preloadTextTracks !== false;
  7169. const cues = new TextTrackCueList(this.cues_);
  7170. const activeCues = new TextTrackCueList(this.activeCues_);
  7171. let changed = false;
  7172. this.timeupdateHandler = bind_(this, function (event = {}) {
  7173. if (this.tech_.isDisposed()) {
  7174. return;
  7175. }
  7176. if (!this.tech_.isReady_) {
  7177. if (event.type !== 'timeupdate') {
  7178. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7179. }
  7180. return;
  7181. }
  7182. // Accessing this.activeCues for the side-effects of updating itself
  7183. // due to its nature as a getter function. Do not remove or cues will
  7184. // stop updating!
  7185. // Use the setter to prevent deletion from uglify (pure_getters rule)
  7186. this.activeCues = this.activeCues;
  7187. if (changed) {
  7188. this.trigger('cuechange');
  7189. changed = false;
  7190. }
  7191. if (event.type !== 'timeupdate') {
  7192. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7193. }
  7194. });
  7195. const disposeHandler = () => {
  7196. this.stopTracking();
  7197. };
  7198. this.tech_.one('dispose', disposeHandler);
  7199. if (mode !== 'disabled') {
  7200. this.startTracking();
  7201. }
  7202. Object.defineProperties(this, {
  7203. /**
  7204. * @memberof TextTrack
  7205. * @member {boolean} default
  7206. * If this track was set to be on or off by default. Cannot be changed after
  7207. * creation.
  7208. * @instance
  7209. *
  7210. * @readonly
  7211. */
  7212. default: {
  7213. get() {
  7214. return default_;
  7215. },
  7216. set() {}
  7217. },
  7218. /**
  7219. * @memberof TextTrack
  7220. * @member {string} mode
  7221. * Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will
  7222. * not be set if setting to an invalid mode.
  7223. * @instance
  7224. *
  7225. * @fires TextTrack#modechange
  7226. */
  7227. mode: {
  7228. get() {
  7229. return mode;
  7230. },
  7231. set(newMode) {
  7232. if (!TextTrackMode[newMode]) {
  7233. return;
  7234. }
  7235. if (mode === newMode) {
  7236. return;
  7237. }
  7238. mode = newMode;
  7239. if (!this.preload_ && mode !== 'disabled' && this.cues.length === 0) {
  7240. // On-demand load.
  7241. loadTrack(this.src, this);
  7242. }
  7243. this.stopTracking();
  7244. if (mode !== 'disabled') {
  7245. this.startTracking();
  7246. }
  7247. /**
  7248. * An event that fires when mode changes on this track. This allows
  7249. * the TextTrackList that holds this track to act accordingly.
  7250. *
  7251. * > Note: This is not part of the spec!
  7252. *
  7253. * @event TextTrack#modechange
  7254. * @type {Event}
  7255. */
  7256. this.trigger('modechange');
  7257. }
  7258. },
  7259. /**
  7260. * @memberof TextTrack
  7261. * @member {TextTrackCueList} cues
  7262. * The text track cue list for this TextTrack.
  7263. * @instance
  7264. */
  7265. cues: {
  7266. get() {
  7267. if (!this.loaded_) {
  7268. return null;
  7269. }
  7270. return cues;
  7271. },
  7272. set() {}
  7273. },
  7274. /**
  7275. * @memberof TextTrack
  7276. * @member {TextTrackCueList} activeCues
  7277. * The list text track cues that are currently active for this TextTrack.
  7278. * @instance
  7279. */
  7280. activeCues: {
  7281. get() {
  7282. if (!this.loaded_) {
  7283. return null;
  7284. }
  7285. // nothing to do
  7286. if (this.cues.length === 0) {
  7287. return activeCues;
  7288. }
  7289. const ct = this.tech_.currentTime();
  7290. const active = [];
  7291. for (let i = 0, l = this.cues.length; i < l; i++) {
  7292. const cue = this.cues[i];
  7293. if (cue.startTime <= ct && cue.endTime >= ct) {
  7294. active.push(cue);
  7295. }
  7296. }
  7297. changed = false;
  7298. if (active.length !== this.activeCues_.length) {
  7299. changed = true;
  7300. } else {
  7301. for (let i = 0; i < active.length; i++) {
  7302. if (this.activeCues_.indexOf(active[i]) === -1) {
  7303. changed = true;
  7304. }
  7305. }
  7306. }
  7307. this.activeCues_ = active;
  7308. activeCues.setCues_(this.activeCues_);
  7309. return activeCues;
  7310. },
  7311. // /!\ Keep this setter empty (see the timeupdate handler above)
  7312. set() {}
  7313. }
  7314. });
  7315. if (settings.src) {
  7316. this.src = settings.src;
  7317. if (!this.preload_) {
  7318. // Tracks will load on-demand.
  7319. // Act like we're loaded for other purposes.
  7320. this.loaded_ = true;
  7321. }
  7322. if (this.preload_ || settings.kind !== 'subtitles' && settings.kind !== 'captions') {
  7323. loadTrack(this.src, this);
  7324. }
  7325. } else {
  7326. this.loaded_ = true;
  7327. }
  7328. }
  7329. startTracking() {
  7330. // More precise cues based on requestVideoFrameCallback with a requestAnimationFram fallback
  7331. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7332. // Also listen to timeupdate in case rVFC/rAF stops (window in background, audio in video el)
  7333. this.tech_.on('timeupdate', this.timeupdateHandler);
  7334. }
  7335. stopTracking() {
  7336. if (this.rvf_) {
  7337. this.tech_.cancelVideoFrameCallback(this.rvf_);
  7338. this.rvf_ = undefined;
  7339. }
  7340. this.tech_.off('timeupdate', this.timeupdateHandler);
  7341. }
  7342. /**
  7343. * Add a cue to the internal list of cues.
  7344. *
  7345. * @param {TextTrack~Cue} cue
  7346. * The cue to add to our internal list
  7347. */
  7348. addCue(originalCue) {
  7349. let cue = originalCue;
  7350. if (window.vttjs && !(originalCue instanceof window.vttjs.VTTCue)) {
  7351. cue = new window.vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text);
  7352. for (const prop in originalCue) {
  7353. if (!(prop in cue)) {
  7354. cue[prop] = originalCue[prop];
  7355. }
  7356. }
  7357. // make sure that `id` is copied over
  7358. cue.id = originalCue.id;
  7359. cue.originalCue_ = originalCue;
  7360. }
  7361. const tracks = this.tech_.textTracks();
  7362. for (let i = 0; i < tracks.length; i++) {
  7363. if (tracks[i] !== this) {
  7364. tracks[i].removeCue(cue);
  7365. }
  7366. }
  7367. this.cues_.push(cue);
  7368. this.cues.setCues_(this.cues_);
  7369. }
  7370. /**
  7371. * Remove a cue from our internal list
  7372. *
  7373. * @param {TextTrack~Cue} removeCue
  7374. * The cue to remove from our internal list
  7375. */
  7376. removeCue(removeCue) {
  7377. let i = this.cues_.length;
  7378. while (i--) {
  7379. const cue = this.cues_[i];
  7380. if (cue === removeCue || cue.originalCue_ && cue.originalCue_ === removeCue) {
  7381. this.cues_.splice(i, 1);
  7382. this.cues.setCues_(this.cues_);
  7383. break;
  7384. }
  7385. }
  7386. }
  7387. }
  7388. /**
  7389. * cuechange - One or more cues in the track have become active or stopped being active.
  7390. */
  7391. TextTrack.prototype.allowedEvents_ = {
  7392. cuechange: 'cuechange'
  7393. };
  7394. /**
  7395. * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList}
  7396. * only one `AudioTrack` in the list will be enabled at a time.
  7397. *
  7398. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack}
  7399. * @extends Track
  7400. */
  7401. class AudioTrack extends Track {
  7402. /**
  7403. * Create an instance of this class.
  7404. *
  7405. * @param {Object} [options={}]
  7406. * Object of option names and values
  7407. *
  7408. * @param {AudioTrack~Kind} [options.kind='']
  7409. * A valid audio track kind
  7410. *
  7411. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7412. * A unique id for this AudioTrack.
  7413. *
  7414. * @param {string} [options.label='']
  7415. * The menu label for this track.
  7416. *
  7417. * @param {string} [options.language='']
  7418. * A valid two character language code.
  7419. *
  7420. * @param {boolean} [options.enabled]
  7421. * If this track is the one that is currently playing. If this track is part of
  7422. * an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled.
  7423. */
  7424. constructor(options = {}) {
  7425. const settings = merge$2(options, {
  7426. kind: AudioTrackKind[options.kind] || ''
  7427. });
  7428. super(settings);
  7429. let enabled = false;
  7430. /**
  7431. * @memberof AudioTrack
  7432. * @member {boolean} enabled
  7433. * If this `AudioTrack` is enabled or not. When setting this will
  7434. * fire {@link AudioTrack#enabledchange} if the state of enabled is changed.
  7435. * @instance
  7436. *
  7437. * @fires VideoTrack#selectedchange
  7438. */
  7439. Object.defineProperty(this, 'enabled', {
  7440. get() {
  7441. return enabled;
  7442. },
  7443. set(newEnabled) {
  7444. // an invalid or unchanged value
  7445. if (typeof newEnabled !== 'boolean' || newEnabled === enabled) {
  7446. return;
  7447. }
  7448. enabled = newEnabled;
  7449. /**
  7450. * An event that fires when enabled changes on this track. This allows
  7451. * the AudioTrackList that holds this track to act accordingly.
  7452. *
  7453. * > Note: This is not part of the spec! Native tracks will do
  7454. * this internally without an event.
  7455. *
  7456. * @event AudioTrack#enabledchange
  7457. * @type {Event}
  7458. */
  7459. this.trigger('enabledchange');
  7460. }
  7461. });
  7462. // if the user sets this track to selected then
  7463. // set selected to that true value otherwise
  7464. // we keep it false
  7465. if (settings.enabled) {
  7466. this.enabled = settings.enabled;
  7467. }
  7468. this.loaded_ = true;
  7469. }
  7470. }
  7471. /**
  7472. * A representation of a single `VideoTrack`.
  7473. *
  7474. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack}
  7475. * @extends Track
  7476. */
  7477. class VideoTrack extends Track {
  7478. /**
  7479. * Create an instance of this class.
  7480. *
  7481. * @param {Object} [options={}]
  7482. * Object of option names and values
  7483. *
  7484. * @param {string} [options.kind='']
  7485. * A valid {@link VideoTrack~Kind}
  7486. *
  7487. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7488. * A unique id for this AudioTrack.
  7489. *
  7490. * @param {string} [options.label='']
  7491. * The menu label for this track.
  7492. *
  7493. * @param {string} [options.language='']
  7494. * A valid two character language code.
  7495. *
  7496. * @param {boolean} [options.selected]
  7497. * If this track is the one that is currently playing.
  7498. */
  7499. constructor(options = {}) {
  7500. const settings = merge$2(options, {
  7501. kind: VideoTrackKind[options.kind] || ''
  7502. });
  7503. super(settings);
  7504. let selected = false;
  7505. /**
  7506. * @memberof VideoTrack
  7507. * @member {boolean} selected
  7508. * If this `VideoTrack` is selected or not. When setting this will
  7509. * fire {@link VideoTrack#selectedchange} if the state of selected changed.
  7510. * @instance
  7511. *
  7512. * @fires VideoTrack#selectedchange
  7513. */
  7514. Object.defineProperty(this, 'selected', {
  7515. get() {
  7516. return selected;
  7517. },
  7518. set(newSelected) {
  7519. // an invalid or unchanged value
  7520. if (typeof newSelected !== 'boolean' || newSelected === selected) {
  7521. return;
  7522. }
  7523. selected = newSelected;
  7524. /**
  7525. * An event that fires when selected changes on this track. This allows
  7526. * the VideoTrackList that holds this track to act accordingly.
  7527. *
  7528. * > Note: This is not part of the spec! Native tracks will do
  7529. * this internally without an event.
  7530. *
  7531. * @event VideoTrack#selectedchange
  7532. * @type {Event}
  7533. */
  7534. this.trigger('selectedchange');
  7535. }
  7536. });
  7537. // if the user sets this track to selected then
  7538. // set selected to that true value otherwise
  7539. // we keep it false
  7540. if (settings.selected) {
  7541. this.selected = settings.selected;
  7542. }
  7543. }
  7544. }
  7545. /**
  7546. * @file html-track-element.js
  7547. */
  7548. /**
  7549. * A single track represented in the DOM.
  7550. *
  7551. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement}
  7552. * @extends EventTarget
  7553. */
  7554. class HTMLTrackElement extends EventTarget$2 {
  7555. /**
  7556. * Create an instance of this class.
  7557. *
  7558. * @param {Object} options={}
  7559. * Object of option names and values
  7560. *
  7561. * @param { import('../tech/tech').default } options.tech
  7562. * A reference to the tech that owns this HTMLTrackElement.
  7563. *
  7564. * @param {TextTrack~Kind} [options.kind='subtitles']
  7565. * A valid text track kind.
  7566. *
  7567. * @param {TextTrack~Mode} [options.mode='disabled']
  7568. * A valid text track mode.
  7569. *
  7570. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7571. * A unique id for this TextTrack.
  7572. *
  7573. * @param {string} [options.label='']
  7574. * The menu label for this track.
  7575. *
  7576. * @param {string} [options.language='']
  7577. * A valid two character language code.
  7578. *
  7579. * @param {string} [options.srclang='']
  7580. * A valid two character language code. An alternative, but deprioritized
  7581. * version of `options.language`
  7582. *
  7583. * @param {string} [options.src]
  7584. * A url to TextTrack cues.
  7585. *
  7586. * @param {boolean} [options.default]
  7587. * If this track should default to on or off.
  7588. */
  7589. constructor(options = {}) {
  7590. super();
  7591. let readyState;
  7592. const track = new TextTrack(options);
  7593. this.kind = track.kind;
  7594. this.src = track.src;
  7595. this.srclang = track.language;
  7596. this.label = track.label;
  7597. this.default = track.default;
  7598. Object.defineProperties(this, {
  7599. /**
  7600. * @memberof HTMLTrackElement
  7601. * @member {HTMLTrackElement~ReadyState} readyState
  7602. * The current ready state of the track element.
  7603. * @instance
  7604. */
  7605. readyState: {
  7606. get() {
  7607. return readyState;
  7608. }
  7609. },
  7610. /**
  7611. * @memberof HTMLTrackElement
  7612. * @member {TextTrack} track
  7613. * The underlying TextTrack object.
  7614. * @instance
  7615. *
  7616. */
  7617. track: {
  7618. get() {
  7619. return track;
  7620. }
  7621. }
  7622. });
  7623. readyState = HTMLTrackElement.NONE;
  7624. /**
  7625. * @listens TextTrack#loadeddata
  7626. * @fires HTMLTrackElement#load
  7627. */
  7628. track.addEventListener('loadeddata', () => {
  7629. readyState = HTMLTrackElement.LOADED;
  7630. this.trigger({
  7631. type: 'load',
  7632. target: this
  7633. });
  7634. });
  7635. }
  7636. }
  7637. HTMLTrackElement.prototype.allowedEvents_ = {
  7638. load: 'load'
  7639. };
  7640. /**
  7641. * The text track not loaded state.
  7642. *
  7643. * @type {number}
  7644. * @static
  7645. */
  7646. HTMLTrackElement.NONE = 0;
  7647. /**
  7648. * The text track loading state.
  7649. *
  7650. * @type {number}
  7651. * @static
  7652. */
  7653. HTMLTrackElement.LOADING = 1;
  7654. /**
  7655. * The text track loaded state.
  7656. *
  7657. * @type {number}
  7658. * @static
  7659. */
  7660. HTMLTrackElement.LOADED = 2;
  7661. /**
  7662. * The text track failed to load state.
  7663. *
  7664. * @type {number}
  7665. * @static
  7666. */
  7667. HTMLTrackElement.ERROR = 3;
  7668. /*
  7669. * This file contains all track properties that are used in
  7670. * player.js, tech.js, html5.js and possibly other techs in the future.
  7671. */
  7672. const NORMAL = {
  7673. audio: {
  7674. ListClass: AudioTrackList,
  7675. TrackClass: AudioTrack,
  7676. capitalName: 'Audio'
  7677. },
  7678. video: {
  7679. ListClass: VideoTrackList,
  7680. TrackClass: VideoTrack,
  7681. capitalName: 'Video'
  7682. },
  7683. text: {
  7684. ListClass: TextTrackList,
  7685. TrackClass: TextTrack,
  7686. capitalName: 'Text'
  7687. }
  7688. };
  7689. Object.keys(NORMAL).forEach(function (type) {
  7690. NORMAL[type].getterName = `${type}Tracks`;
  7691. NORMAL[type].privateName = `${type}Tracks_`;
  7692. });
  7693. const REMOTE = {
  7694. remoteText: {
  7695. ListClass: TextTrackList,
  7696. TrackClass: TextTrack,
  7697. capitalName: 'RemoteText',
  7698. getterName: 'remoteTextTracks',
  7699. privateName: 'remoteTextTracks_'
  7700. },
  7701. remoteTextEl: {
  7702. ListClass: HtmlTrackElementList,
  7703. TrackClass: HTMLTrackElement,
  7704. capitalName: 'RemoteTextTrackEls',
  7705. getterName: 'remoteTextTrackEls',
  7706. privateName: 'remoteTextTrackEls_'
  7707. }
  7708. };
  7709. const ALL = Object.assign({}, NORMAL, REMOTE);
  7710. REMOTE.names = Object.keys(REMOTE);
  7711. NORMAL.names = Object.keys(NORMAL);
  7712. ALL.names = [].concat(REMOTE.names).concat(NORMAL.names);
  7713. var minDoc = {};
  7714. var topLevel = typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : {};
  7715. var doccy;
  7716. if (typeof document !== 'undefined') {
  7717. doccy = document;
  7718. } else {
  7719. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
  7720. if (!doccy) {
  7721. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
  7722. }
  7723. }
  7724. var document_1 = doccy;
  7725. /**
  7726. * Copyright 2013 vtt.js Contributors
  7727. *
  7728. * Licensed under the Apache License, Version 2.0 (the "License");
  7729. * you may not use this file except in compliance with the License.
  7730. * You may obtain a copy of the License at
  7731. *
  7732. * http://www.apache.org/licenses/LICENSE-2.0
  7733. *
  7734. * Unless required by applicable law or agreed to in writing, software
  7735. * distributed under the License is distributed on an "AS IS" BASIS,
  7736. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7737. * See the License for the specific language governing permissions and
  7738. * limitations under the License.
  7739. */
  7740. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  7741. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  7742. var _objCreate = Object.create || function () {
  7743. function F() {}
  7744. return function (o) {
  7745. if (arguments.length !== 1) {
  7746. throw new Error('Object.create shim only accepts one parameter.');
  7747. }
  7748. F.prototype = o;
  7749. return new F();
  7750. };
  7751. }();
  7752. // Creates a new ParserError object from an errorData object. The errorData
  7753. // object should have default code and message properties. The default message
  7754. // property can be overriden by passing in a message parameter.
  7755. // See ParsingError.Errors below for acceptable errors.
  7756. function ParsingError(errorData, message) {
  7757. this.name = "ParsingError";
  7758. this.code = errorData.code;
  7759. this.message = message || errorData.message;
  7760. }
  7761. ParsingError.prototype = _objCreate(Error.prototype);
  7762. ParsingError.prototype.constructor = ParsingError;
  7763. // ParsingError metadata for acceptable ParsingErrors.
  7764. ParsingError.Errors = {
  7765. BadSignature: {
  7766. code: 0,
  7767. message: "Malformed WebVTT signature."
  7768. },
  7769. BadTimeStamp: {
  7770. code: 1,
  7771. message: "Malformed time stamp."
  7772. }
  7773. };
  7774. // Try to parse input as a time stamp.
  7775. function parseTimeStamp(input) {
  7776. function computeSeconds(h, m, s, f) {
  7777. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
  7778. }
  7779. var m = input.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);
  7780. if (!m) {
  7781. return null;
  7782. }
  7783. if (m[3]) {
  7784. // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
  7785. return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
  7786. } else if (m[1] > 59) {
  7787. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  7788. // First position is hours as it's over 59.
  7789. return computeSeconds(m[1], m[2], 0, m[4]);
  7790. } else {
  7791. // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
  7792. return computeSeconds(0, m[1], m[2], m[4]);
  7793. }
  7794. }
  7795. // A settings object holds key/value pairs and will ignore anything but the first
  7796. // assignment to a specific key.
  7797. function Settings() {
  7798. this.values = _objCreate(null);
  7799. }
  7800. Settings.prototype = {
  7801. // Only accept the first assignment to any key.
  7802. set: function (k, v) {
  7803. if (!this.get(k) && v !== "") {
  7804. this.values[k] = v;
  7805. }
  7806. },
  7807. // Return the value for a key, or a default value.
  7808. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  7809. // a number of possible default values as properties where 'defaultKey' is
  7810. // the key of the property that will be chosen; otherwise it's assumed to be
  7811. // a single value.
  7812. get: function (k, dflt, defaultKey) {
  7813. if (defaultKey) {
  7814. return this.has(k) ? this.values[k] : dflt[defaultKey];
  7815. }
  7816. return this.has(k) ? this.values[k] : dflt;
  7817. },
  7818. // Check whether we have a value for a key.
  7819. has: function (k) {
  7820. return k in this.values;
  7821. },
  7822. // Accept a setting if its one of the given alternatives.
  7823. alt: function (k, v, a) {
  7824. for (var n = 0; n < a.length; ++n) {
  7825. if (v === a[n]) {
  7826. this.set(k, v);
  7827. break;
  7828. }
  7829. }
  7830. },
  7831. // Accept a setting if its a valid (signed) integer.
  7832. integer: function (k, v) {
  7833. if (/^-?\d+$/.test(v)) {
  7834. // integer
  7835. this.set(k, parseInt(v, 10));
  7836. }
  7837. },
  7838. // Accept a setting if its a valid percentage.
  7839. percent: function (k, v) {
  7840. if (v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) {
  7841. v = parseFloat(v);
  7842. if (v >= 0 && v <= 100) {
  7843. this.set(k, v);
  7844. return true;
  7845. }
  7846. }
  7847. return false;
  7848. }
  7849. };
  7850. // Helper function to parse input into groups separated by 'groupDelim', and
  7851. // interprete each group as a key/value pair separated by 'keyValueDelim'.
  7852. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  7853. var groups = groupDelim ? input.split(groupDelim) : [input];
  7854. for (var i in groups) {
  7855. if (typeof groups[i] !== "string") {
  7856. continue;
  7857. }
  7858. var kv = groups[i].split(keyValueDelim);
  7859. if (kv.length !== 2) {
  7860. continue;
  7861. }
  7862. var k = kv[0].trim();
  7863. var v = kv[1].trim();
  7864. callback(k, v);
  7865. }
  7866. }
  7867. function parseCue(input, cue, regionList) {
  7868. // Remember the original input if we need to throw an error.
  7869. var oInput = input;
  7870. // 4.1 WebVTT timestamp
  7871. function consumeTimeStamp() {
  7872. var ts = parseTimeStamp(input);
  7873. if (ts === null) {
  7874. throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput);
  7875. }
  7876. // Remove time stamp from input.
  7877. input = input.replace(/^[^\sa-zA-Z-]+/, "");
  7878. return ts;
  7879. }
  7880. // 4.4.2 WebVTT cue settings
  7881. function consumeCueSettings(input, cue) {
  7882. var settings = new Settings();
  7883. parseOptions(input, function (k, v) {
  7884. switch (k) {
  7885. case "region":
  7886. // Find the last region we parsed with the same region id.
  7887. for (var i = regionList.length - 1; i >= 0; i--) {
  7888. if (regionList[i].id === v) {
  7889. settings.set(k, regionList[i].region);
  7890. break;
  7891. }
  7892. }
  7893. break;
  7894. case "vertical":
  7895. settings.alt(k, v, ["rl", "lr"]);
  7896. break;
  7897. case "line":
  7898. var vals = v.split(","),
  7899. vals0 = vals[0];
  7900. settings.integer(k, vals0);
  7901. settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
  7902. settings.alt(k, vals0, ["auto"]);
  7903. if (vals.length === 2) {
  7904. settings.alt("lineAlign", vals[1], ["start", "center", "end"]);
  7905. }
  7906. break;
  7907. case "position":
  7908. vals = v.split(",");
  7909. settings.percent(k, vals[0]);
  7910. if (vals.length === 2) {
  7911. settings.alt("positionAlign", vals[1], ["start", "center", "end"]);
  7912. }
  7913. break;
  7914. case "size":
  7915. settings.percent(k, v);
  7916. break;
  7917. case "align":
  7918. settings.alt(k, v, ["start", "center", "end", "left", "right"]);
  7919. break;
  7920. }
  7921. }, /:/, /\s/);
  7922. // Apply default values for any missing fields.
  7923. cue.region = settings.get("region", null);
  7924. cue.vertical = settings.get("vertical", "");
  7925. try {
  7926. cue.line = settings.get("line", "auto");
  7927. } catch (e) {}
  7928. cue.lineAlign = settings.get("lineAlign", "start");
  7929. cue.snapToLines = settings.get("snapToLines", true);
  7930. cue.size = settings.get("size", 100);
  7931. // Safari still uses the old middle value and won't accept center
  7932. try {
  7933. cue.align = settings.get("align", "center");
  7934. } catch (e) {
  7935. cue.align = settings.get("align", "middle");
  7936. }
  7937. try {
  7938. cue.position = settings.get("position", "auto");
  7939. } catch (e) {
  7940. cue.position = settings.get("position", {
  7941. start: 0,
  7942. left: 0,
  7943. center: 50,
  7944. middle: 50,
  7945. end: 100,
  7946. right: 100
  7947. }, cue.align);
  7948. }
  7949. cue.positionAlign = settings.get("positionAlign", {
  7950. start: "start",
  7951. left: "start",
  7952. center: "center",
  7953. middle: "center",
  7954. end: "end",
  7955. right: "end"
  7956. }, cue.align);
  7957. }
  7958. function skipWhitespace() {
  7959. input = input.replace(/^\s+/, "");
  7960. }
  7961. // 4.1 WebVTT cue timings.
  7962. skipWhitespace();
  7963. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  7964. skipWhitespace();
  7965. if (input.substr(0, 3) !== "-->") {
  7966. // (3) next characters must match "-->"
  7967. throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  7968. }
  7969. input = input.substr(3);
  7970. skipWhitespace();
  7971. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  7972. // 4.1 WebVTT cue settings list.
  7973. skipWhitespace();
  7974. consumeCueSettings(input, cue);
  7975. }
  7976. // When evaluating this file as part of a Webpack bundle for server
  7977. // side rendering, `document` is an empty object.
  7978. var TEXTAREA_ELEMENT = document_1.createElement && document_1.createElement("textarea");
  7979. var TAG_NAME = {
  7980. c: "span",
  7981. i: "i",
  7982. b: "b",
  7983. u: "u",
  7984. ruby: "ruby",
  7985. rt: "rt",
  7986. v: "span",
  7987. lang: "span"
  7988. };
  7989. // 5.1 default text color
  7990. // 5.2 default text background color is equivalent to text color with bg_ prefix
  7991. var DEFAULT_COLOR_CLASS = {
  7992. white: 'rgba(255,255,255,1)',
  7993. lime: 'rgba(0,255,0,1)',
  7994. cyan: 'rgba(0,255,255,1)',
  7995. red: 'rgba(255,0,0,1)',
  7996. yellow: 'rgba(255,255,0,1)',
  7997. magenta: 'rgba(255,0,255,1)',
  7998. blue: 'rgba(0,0,255,1)',
  7999. black: 'rgba(0,0,0,1)'
  8000. };
  8001. var TAG_ANNOTATION = {
  8002. v: "title",
  8003. lang: "lang"
  8004. };
  8005. var NEEDS_PARENT = {
  8006. rt: "ruby"
  8007. };
  8008. // Parse content into a document fragment.
  8009. function parseContent(window, input) {
  8010. function nextToken() {
  8011. // Check for end-of-string.
  8012. if (!input) {
  8013. return null;
  8014. }
  8015. // Consume 'n' characters from the input.
  8016. function consume(result) {
  8017. input = input.substr(result.length);
  8018. return result;
  8019. }
  8020. var m = input.match(/^([^<]*)(<[^>]*>?)?/);
  8021. // If there is some text before the next tag, return it, otherwise return
  8022. // the tag.
  8023. return consume(m[1] ? m[1] : m[2]);
  8024. }
  8025. function unescape(s) {
  8026. TEXTAREA_ELEMENT.innerHTML = s;
  8027. s = TEXTAREA_ELEMENT.textContent;
  8028. TEXTAREA_ELEMENT.textContent = "";
  8029. return s;
  8030. }
  8031. function shouldAdd(current, element) {
  8032. return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName;
  8033. }
  8034. // Create an element for this tag.
  8035. function createElement(type, annotation) {
  8036. var tagName = TAG_NAME[type];
  8037. if (!tagName) {
  8038. return null;
  8039. }
  8040. var element = window.document.createElement(tagName);
  8041. var name = TAG_ANNOTATION[type];
  8042. if (name && annotation) {
  8043. element[name] = annotation.trim();
  8044. }
  8045. return element;
  8046. }
  8047. var rootDiv = window.document.createElement("div"),
  8048. current = rootDiv,
  8049. t,
  8050. tagStack = [];
  8051. while ((t = nextToken()) !== null) {
  8052. if (t[0] === '<') {
  8053. if (t[1] === "/") {
  8054. // If the closing tag matches, move back up to the parent node.
  8055. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) {
  8056. tagStack.pop();
  8057. current = current.parentNode;
  8058. }
  8059. // Otherwise just ignore the end tag.
  8060. continue;
  8061. }
  8062. var ts = parseTimeStamp(t.substr(1, t.length - 2));
  8063. var node;
  8064. if (ts) {
  8065. // Timestamps are lead nodes as well.
  8066. node = window.document.createProcessingInstruction("timestamp", ts);
  8067. current.appendChild(node);
  8068. continue;
  8069. }
  8070. var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);
  8071. // If we can't parse the tag, skip to the next tag.
  8072. if (!m) {
  8073. continue;
  8074. }
  8075. // Try to construct an element, and ignore the tag if we couldn't.
  8076. node = createElement(m[1], m[3]);
  8077. if (!node) {
  8078. continue;
  8079. }
  8080. // Determine if the tag should be added based on the context of where it
  8081. // is placed in the cuetext.
  8082. if (!shouldAdd(current, node)) {
  8083. continue;
  8084. }
  8085. // Set the class list (as a list of classes, separated by space).
  8086. if (m[2]) {
  8087. var classes = m[2].split('.');
  8088. classes.forEach(function (cl) {
  8089. var bgColor = /^bg_/.test(cl);
  8090. // slice out `bg_` if it's a background color
  8091. var colorName = bgColor ? cl.slice(3) : cl;
  8092. if (DEFAULT_COLOR_CLASS.hasOwnProperty(colorName)) {
  8093. var propName = bgColor ? 'background-color' : 'color';
  8094. var propValue = DEFAULT_COLOR_CLASS[colorName];
  8095. node.style[propName] = propValue;
  8096. }
  8097. });
  8098. node.className = classes.join(' ');
  8099. }
  8100. // Append the node to the current node, and enter the scope of the new
  8101. // node.
  8102. tagStack.push(m[1]);
  8103. current.appendChild(node);
  8104. current = node;
  8105. continue;
  8106. }
  8107. // Text nodes are leaf nodes.
  8108. current.appendChild(window.document.createTextNode(unescape(t)));
  8109. }
  8110. return rootDiv;
  8111. }
  8112. // This is a list of all the Unicode characters that have a strong
  8113. // right-to-left category. What this means is that these characters are
  8114. // written right-to-left for sure. It was generated by pulling all the strong
  8115. // right-to-left characters out of the Unicode data table. That table can
  8116. // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
  8117. var strongRTLRanges = [[0x5be, 0x5be], [0x5c0, 0x5c0], [0x5c3, 0x5c3], [0x5c6, 0x5c6], [0x5d0, 0x5ea], [0x5f0, 0x5f4], [0x608, 0x608], [0x60b, 0x60b], [0x60d, 0x60d], [0x61b, 0x61b], [0x61e, 0x64a], [0x66d, 0x66f], [0x671, 0x6d5], [0x6e5, 0x6e6], [0x6ee, 0x6ef], [0x6fa, 0x70d], [0x70f, 0x710], [0x712, 0x72f], [0x74d, 0x7a5], [0x7b1, 0x7b1], [0x7c0, 0x7ea], [0x7f4, 0x7f5], [0x7fa, 0x7fa], [0x800, 0x815], [0x81a, 0x81a], [0x824, 0x824], [0x828, 0x828], [0x830, 0x83e], [0x840, 0x858], [0x85e, 0x85e], [0x8a0, 0x8a0], [0x8a2, 0x8ac], [0x200f, 0x200f], [0xfb1d, 0xfb1d], [0xfb1f, 0xfb28], [0xfb2a, 0xfb36], [0xfb38, 0xfb3c], [0xfb3e, 0xfb3e], [0xfb40, 0xfb41], [0xfb43, 0xfb44], [0xfb46, 0xfbc1], [0xfbd3, 0xfd3d], [0xfd50, 0xfd8f], [0xfd92, 0xfdc7], [0xfdf0, 0xfdfc], [0xfe70, 0xfe74], [0xfe76, 0xfefc], [0x10800, 0x10805], [0x10808, 0x10808], [0x1080a, 0x10835], [0x10837, 0x10838], [0x1083c, 0x1083c], [0x1083f, 0x10855], [0x10857, 0x1085f], [0x10900, 0x1091b], [0x10920, 0x10939], [0x1093f, 0x1093f], [0x10980, 0x109b7], [0x109be, 0x109bf], [0x10a00, 0x10a00], [0x10a10, 0x10a13], [0x10a15, 0x10a17], [0x10a19, 0x10a33], [0x10a40, 0x10a47], [0x10a50, 0x10a58], [0x10a60, 0x10a7f], [0x10b00, 0x10b35], [0x10b40, 0x10b55], [0x10b58, 0x10b72], [0x10b78, 0x10b7f], [0x10c00, 0x10c48], [0x1ee00, 0x1ee03], [0x1ee05, 0x1ee1f], [0x1ee21, 0x1ee22], [0x1ee24, 0x1ee24], [0x1ee27, 0x1ee27], [0x1ee29, 0x1ee32], [0x1ee34, 0x1ee37], [0x1ee39, 0x1ee39], [0x1ee3b, 0x1ee3b], [0x1ee42, 0x1ee42], [0x1ee47, 0x1ee47], [0x1ee49, 0x1ee49], [0x1ee4b, 0x1ee4b], [0x1ee4d, 0x1ee4f], [0x1ee51, 0x1ee52], [0x1ee54, 0x1ee54], [0x1ee57, 0x1ee57], [0x1ee59, 0x1ee59], [0x1ee5b, 0x1ee5b], [0x1ee5d, 0x1ee5d], [0x1ee5f, 0x1ee5f], [0x1ee61, 0x1ee62], [0x1ee64, 0x1ee64], [0x1ee67, 0x1ee6a], [0x1ee6c, 0x1ee72], [0x1ee74, 0x1ee77], [0x1ee79, 0x1ee7c], [0x1ee7e, 0x1ee7e], [0x1ee80, 0x1ee89], [0x1ee8b, 0x1ee9b], [0x1eea1, 0x1eea3], [0x1eea5, 0x1eea9], [0x1eeab, 0x1eebb], [0x10fffd, 0x10fffd]];
  8118. function isStrongRTLChar(charCode) {
  8119. for (var i = 0; i < strongRTLRanges.length; i++) {
  8120. var currentRange = strongRTLRanges[i];
  8121. if (charCode >= currentRange[0] && charCode <= currentRange[1]) {
  8122. return true;
  8123. }
  8124. }
  8125. return false;
  8126. }
  8127. function determineBidi(cueDiv) {
  8128. var nodeStack = [],
  8129. text = "",
  8130. charCode;
  8131. if (!cueDiv || !cueDiv.childNodes) {
  8132. return "ltr";
  8133. }
  8134. function pushNodes(nodeStack, node) {
  8135. for (var i = node.childNodes.length - 1; i >= 0; i--) {
  8136. nodeStack.push(node.childNodes[i]);
  8137. }
  8138. }
  8139. function nextTextNode(nodeStack) {
  8140. if (!nodeStack || !nodeStack.length) {
  8141. return null;
  8142. }
  8143. var node = nodeStack.pop(),
  8144. text = node.textContent || node.innerText;
  8145. if (text) {
  8146. // TODO: This should match all unicode type B characters (paragraph
  8147. // separator characters). See issue #115.
  8148. var m = text.match(/^.*(\n|\r)/);
  8149. if (m) {
  8150. nodeStack.length = 0;
  8151. return m[0];
  8152. }
  8153. return text;
  8154. }
  8155. if (node.tagName === "ruby") {
  8156. return nextTextNode(nodeStack);
  8157. }
  8158. if (node.childNodes) {
  8159. pushNodes(nodeStack, node);
  8160. return nextTextNode(nodeStack);
  8161. }
  8162. }
  8163. pushNodes(nodeStack, cueDiv);
  8164. while (text = nextTextNode(nodeStack)) {
  8165. for (var i = 0; i < text.length; i++) {
  8166. charCode = text.charCodeAt(i);
  8167. if (isStrongRTLChar(charCode)) {
  8168. return "rtl";
  8169. }
  8170. }
  8171. }
  8172. return "ltr";
  8173. }
  8174. function computeLinePos(cue) {
  8175. if (typeof cue.line === "number" && (cue.snapToLines || cue.line >= 0 && cue.line <= 100)) {
  8176. return cue.line;
  8177. }
  8178. if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) {
  8179. return -1;
  8180. }
  8181. var track = cue.track,
  8182. trackList = track.textTrackList,
  8183. count = 0;
  8184. for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {
  8185. if (trackList[i].mode === "showing") {
  8186. count++;
  8187. }
  8188. }
  8189. return ++count * -1;
  8190. }
  8191. function StyleBox() {}
  8192. // Apply styles to a div. If there is no div passed then it defaults to the
  8193. // div on 'this'.
  8194. StyleBox.prototype.applyStyles = function (styles, div) {
  8195. div = div || this.div;
  8196. for (var prop in styles) {
  8197. if (styles.hasOwnProperty(prop)) {
  8198. div.style[prop] = styles[prop];
  8199. }
  8200. }
  8201. };
  8202. StyleBox.prototype.formatStyle = function (val, unit) {
  8203. return val === 0 ? 0 : val + unit;
  8204. };
  8205. // Constructs the computed display state of the cue (a div). Places the div
  8206. // into the overlay which should be a block level element (usually a div).
  8207. function CueStyleBox(window, cue, styleOptions) {
  8208. StyleBox.call(this);
  8209. this.cue = cue;
  8210. // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will
  8211. // have inline positioning and will function as the cue background box.
  8212. this.cueDiv = parseContent(window, cue.text);
  8213. var styles = {
  8214. color: "rgba(255, 255, 255, 1)",
  8215. backgroundColor: "rgba(0, 0, 0, 0.8)",
  8216. position: "relative",
  8217. left: 0,
  8218. right: 0,
  8219. top: 0,
  8220. bottom: 0,
  8221. display: "inline",
  8222. writingMode: cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl",
  8223. unicodeBidi: "plaintext"
  8224. };
  8225. this.applyStyles(styles, this.cueDiv);
  8226. // Create an absolutely positioned div that will be used to position the cue
  8227. // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS
  8228. // mirrors of them except middle instead of center on Safari.
  8229. this.div = window.document.createElement("div");
  8230. styles = {
  8231. direction: determineBidi(this.cueDiv),
  8232. writingMode: cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl",
  8233. unicodeBidi: "plaintext",
  8234. textAlign: cue.align === "middle" ? "center" : cue.align,
  8235. font: styleOptions.font,
  8236. whiteSpace: "pre-line",
  8237. position: "absolute"
  8238. };
  8239. this.applyStyles(styles);
  8240. this.div.appendChild(this.cueDiv);
  8241. // Calculate the distance from the reference edge of the viewport to the text
  8242. // position of the cue box. The reference edge will be resolved later when
  8243. // the box orientation styles are applied.
  8244. var textPos = 0;
  8245. switch (cue.positionAlign) {
  8246. case "start":
  8247. textPos = cue.position;
  8248. break;
  8249. case "center":
  8250. textPos = cue.position - cue.size / 2;
  8251. break;
  8252. case "end":
  8253. textPos = cue.position - cue.size;
  8254. break;
  8255. }
  8256. // Horizontal box orientation; textPos is the distance from the left edge of the
  8257. // area to the left edge of the box and cue.size is the distance extending to
  8258. // the right from there.
  8259. if (cue.vertical === "") {
  8260. this.applyStyles({
  8261. left: this.formatStyle(textPos, "%"),
  8262. width: this.formatStyle(cue.size, "%")
  8263. });
  8264. // Vertical box orientation; textPos is the distance from the top edge of the
  8265. // area to the top edge of the box and cue.size is the height extending
  8266. // downwards from there.
  8267. } else {
  8268. this.applyStyles({
  8269. top: this.formatStyle(textPos, "%"),
  8270. height: this.formatStyle(cue.size, "%")
  8271. });
  8272. }
  8273. this.move = function (box) {
  8274. this.applyStyles({
  8275. top: this.formatStyle(box.top, "px"),
  8276. bottom: this.formatStyle(box.bottom, "px"),
  8277. left: this.formatStyle(box.left, "px"),
  8278. right: this.formatStyle(box.right, "px"),
  8279. height: this.formatStyle(box.height, "px"),
  8280. width: this.formatStyle(box.width, "px")
  8281. });
  8282. };
  8283. }
  8284. CueStyleBox.prototype = _objCreate(StyleBox.prototype);
  8285. CueStyleBox.prototype.constructor = CueStyleBox;
  8286. // Represents the co-ordinates of an Element in a way that we can easily
  8287. // compute things with such as if it overlaps or intersects with another Element.
  8288. // Can initialize it with either a StyleBox or another BoxPosition.
  8289. function BoxPosition(obj) {
  8290. // Either a BoxPosition was passed in and we need to copy it, or a StyleBox
  8291. // was passed in and we need to copy the results of 'getBoundingClientRect'
  8292. // as the object returned is readonly. All co-ordinate values are in reference
  8293. // to the viewport origin (top left).
  8294. var lh, height, width, top;
  8295. if (obj.div) {
  8296. height = obj.div.offsetHeight;
  8297. width = obj.div.offsetWidth;
  8298. top = obj.div.offsetTop;
  8299. var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects();
  8300. obj = obj.div.getBoundingClientRect();
  8301. // In certain cases the outter div will be slightly larger then the sum of
  8302. // the inner div's lines. This could be due to bold text, etc, on some platforms.
  8303. // In this case we should get the average line height and use that. This will
  8304. // result in the desired behaviour.
  8305. lh = rects ? Math.max(rects[0] && rects[0].height || 0, obj.height / rects.length) : 0;
  8306. }
  8307. this.left = obj.left;
  8308. this.right = obj.right;
  8309. this.top = obj.top || top;
  8310. this.height = obj.height || height;
  8311. this.bottom = obj.bottom || top + (obj.height || height);
  8312. this.width = obj.width || width;
  8313. this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
  8314. }
  8315. // Move the box along a particular axis. Optionally pass in an amount to move
  8316. // the box. If no amount is passed then the default is the line height of the
  8317. // box.
  8318. BoxPosition.prototype.move = function (axis, toMove) {
  8319. toMove = toMove !== undefined ? toMove : this.lineHeight;
  8320. switch (axis) {
  8321. case "+x":
  8322. this.left += toMove;
  8323. this.right += toMove;
  8324. break;
  8325. case "-x":
  8326. this.left -= toMove;
  8327. this.right -= toMove;
  8328. break;
  8329. case "+y":
  8330. this.top += toMove;
  8331. this.bottom += toMove;
  8332. break;
  8333. case "-y":
  8334. this.top -= toMove;
  8335. this.bottom -= toMove;
  8336. break;
  8337. }
  8338. };
  8339. // Check if this box overlaps another box, b2.
  8340. BoxPosition.prototype.overlaps = function (b2) {
  8341. return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top;
  8342. };
  8343. // Check if this box overlaps any other boxes in boxes.
  8344. BoxPosition.prototype.overlapsAny = function (boxes) {
  8345. for (var i = 0; i < boxes.length; i++) {
  8346. if (this.overlaps(boxes[i])) {
  8347. return true;
  8348. }
  8349. }
  8350. return false;
  8351. };
  8352. // Check if this box is within another box.
  8353. BoxPosition.prototype.within = function (container) {
  8354. return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right;
  8355. };
  8356. // Check if this box is entirely within the container or it is overlapping
  8357. // on the edge opposite of the axis direction passed. For example, if "+x" is
  8358. // passed and the box is overlapping on the left edge of the container, then
  8359. // return true.
  8360. BoxPosition.prototype.overlapsOppositeAxis = function (container, axis) {
  8361. switch (axis) {
  8362. case "+x":
  8363. return this.left < container.left;
  8364. case "-x":
  8365. return this.right > container.right;
  8366. case "+y":
  8367. return this.top < container.top;
  8368. case "-y":
  8369. return this.bottom > container.bottom;
  8370. }
  8371. };
  8372. // Find the percentage of the area that this box is overlapping with another
  8373. // box.
  8374. BoxPosition.prototype.intersectPercentage = function (b2) {
  8375. var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
  8376. y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
  8377. intersectArea = x * y;
  8378. return intersectArea / (this.height * this.width);
  8379. };
  8380. // Convert the positions from this box to CSS compatible positions using
  8381. // the reference container's positions. This has to be done because this
  8382. // box's positions are in reference to the viewport origin, whereas, CSS
  8383. // values are in referecne to their respective edges.
  8384. BoxPosition.prototype.toCSSCompatValues = function (reference) {
  8385. return {
  8386. top: this.top - reference.top,
  8387. bottom: reference.bottom - this.bottom,
  8388. left: this.left - reference.left,
  8389. right: reference.right - this.right,
  8390. height: this.height,
  8391. width: this.width
  8392. };
  8393. };
  8394. // Get an object that represents the box's position without anything extra.
  8395. // Can pass a StyleBox, HTMLElement, or another BoxPositon.
  8396. BoxPosition.getSimpleBoxPosition = function (obj) {
  8397. var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
  8398. var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
  8399. var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
  8400. obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj;
  8401. var ret = {
  8402. left: obj.left,
  8403. right: obj.right,
  8404. top: obj.top || top,
  8405. height: obj.height || height,
  8406. bottom: obj.bottom || top + (obj.height || height),
  8407. width: obj.width || width
  8408. };
  8409. return ret;
  8410. };
  8411. // Move a StyleBox to its specified, or next best, position. The containerBox
  8412. // is the box that contains the StyleBox, such as a div. boxPositions are
  8413. // a list of other boxes that the styleBox can't overlap with.
  8414. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
  8415. // Find the best position for a cue box, b, on the video. The axis parameter
  8416. // is a list of axis, the order of which, it will move the box along. For example:
  8417. // Passing ["+x", "-x"] will move the box first along the x axis in the positive
  8418. // direction. If it doesn't find a good position for it there it will then move
  8419. // it along the x axis in the negative direction.
  8420. function findBestPosition(b, axis) {
  8421. var bestPosition,
  8422. specifiedPosition = new BoxPosition(b),
  8423. percentage = 1; // Highest possible so the first thing we get is better.
  8424. for (var i = 0; i < axis.length; i++) {
  8425. while (b.overlapsOppositeAxis(containerBox, axis[i]) || b.within(containerBox) && b.overlapsAny(boxPositions)) {
  8426. b.move(axis[i]);
  8427. }
  8428. // We found a spot where we aren't overlapping anything. This is our
  8429. // best position.
  8430. if (b.within(containerBox)) {
  8431. return b;
  8432. }
  8433. var p = b.intersectPercentage(containerBox);
  8434. // If we're outside the container box less then we were on our last try
  8435. // then remember this position as the best position.
  8436. if (percentage > p) {
  8437. bestPosition = new BoxPosition(b);
  8438. percentage = p;
  8439. }
  8440. // Reset the box position to the specified position.
  8441. b = new BoxPosition(specifiedPosition);
  8442. }
  8443. return bestPosition || specifiedPosition;
  8444. }
  8445. var boxPosition = new BoxPosition(styleBox),
  8446. cue = styleBox.cue,
  8447. linePos = computeLinePos(cue),
  8448. axis = [];
  8449. // If we have a line number to align the cue to.
  8450. if (cue.snapToLines) {
  8451. var size;
  8452. switch (cue.vertical) {
  8453. case "":
  8454. axis = ["+y", "-y"];
  8455. size = "height";
  8456. break;
  8457. case "rl":
  8458. axis = ["+x", "-x"];
  8459. size = "width";
  8460. break;
  8461. case "lr":
  8462. axis = ["-x", "+x"];
  8463. size = "width";
  8464. break;
  8465. }
  8466. var step = boxPosition.lineHeight,
  8467. position = step * Math.round(linePos),
  8468. maxPosition = containerBox[size] + step,
  8469. initialAxis = axis[0];
  8470. // If the specified intial position is greater then the max position then
  8471. // clamp the box to the amount of steps it would take for the box to
  8472. // reach the max position.
  8473. if (Math.abs(position) > maxPosition) {
  8474. position = position < 0 ? -1 : 1;
  8475. position *= Math.ceil(maxPosition / step) * step;
  8476. }
  8477. // If computed line position returns negative then line numbers are
  8478. // relative to the bottom of the video instead of the top. Therefore, we
  8479. // need to increase our initial position by the length or width of the
  8480. // video, depending on the writing direction, and reverse our axis directions.
  8481. if (linePos < 0) {
  8482. position += cue.vertical === "" ? containerBox.height : containerBox.width;
  8483. axis = axis.reverse();
  8484. }
  8485. // Move the box to the specified position. This may not be its best
  8486. // position.
  8487. boxPosition.move(initialAxis, position);
  8488. } else {
  8489. // If we have a percentage line value for the cue.
  8490. var calculatedPercentage = boxPosition.lineHeight / containerBox.height * 100;
  8491. switch (cue.lineAlign) {
  8492. case "center":
  8493. linePos -= calculatedPercentage / 2;
  8494. break;
  8495. case "end":
  8496. linePos -= calculatedPercentage;
  8497. break;
  8498. }
  8499. // Apply initial line position to the cue box.
  8500. switch (cue.vertical) {
  8501. case "":
  8502. styleBox.applyStyles({
  8503. top: styleBox.formatStyle(linePos, "%")
  8504. });
  8505. break;
  8506. case "rl":
  8507. styleBox.applyStyles({
  8508. left: styleBox.formatStyle(linePos, "%")
  8509. });
  8510. break;
  8511. case "lr":
  8512. styleBox.applyStyles({
  8513. right: styleBox.formatStyle(linePos, "%")
  8514. });
  8515. break;
  8516. }
  8517. axis = ["+y", "-x", "+x", "-y"];
  8518. // Get the box position again after we've applied the specified positioning
  8519. // to it.
  8520. boxPosition = new BoxPosition(styleBox);
  8521. }
  8522. var bestPosition = findBestPosition(boxPosition, axis);
  8523. styleBox.move(bestPosition.toCSSCompatValues(containerBox));
  8524. }
  8525. function WebVTT$1() {
  8526. // Nothing
  8527. }
  8528. // Helper to allow strings to be decoded instead of the default binary utf8 data.
  8529. WebVTT$1.StringDecoder = function () {
  8530. return {
  8531. decode: function (data) {
  8532. if (!data) {
  8533. return "";
  8534. }
  8535. if (typeof data !== "string") {
  8536. throw new Error("Error - expected string data.");
  8537. }
  8538. return decodeURIComponent(encodeURIComponent(data));
  8539. }
  8540. };
  8541. };
  8542. WebVTT$1.convertCueToDOMTree = function (window, cuetext) {
  8543. if (!window || !cuetext) {
  8544. return null;
  8545. }
  8546. return parseContent(window, cuetext);
  8547. };
  8548. var FONT_SIZE_PERCENT = 0.05;
  8549. var FONT_STYLE = "sans-serif";
  8550. var CUE_BACKGROUND_PADDING = "1.5%";
  8551. // Runs the processing model over the cues and regions passed to it.
  8552. // @param overlay A block level element (usually a div) that the computed cues
  8553. // and regions will be placed into.
  8554. WebVTT$1.processCues = function (window, cues, overlay) {
  8555. if (!window || !cues || !overlay) {
  8556. return null;
  8557. }
  8558. // Remove all previous children.
  8559. while (overlay.firstChild) {
  8560. overlay.removeChild(overlay.firstChild);
  8561. }
  8562. var paddedOverlay = window.document.createElement("div");
  8563. paddedOverlay.style.position = "absolute";
  8564. paddedOverlay.style.left = "0";
  8565. paddedOverlay.style.right = "0";
  8566. paddedOverlay.style.top = "0";
  8567. paddedOverlay.style.bottom = "0";
  8568. paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
  8569. overlay.appendChild(paddedOverlay);
  8570. // Determine if we need to compute the display states of the cues. This could
  8571. // be the case if a cue's state has been changed since the last computation or
  8572. // if it has not been computed yet.
  8573. function shouldCompute(cues) {
  8574. for (var i = 0; i < cues.length; i++) {
  8575. if (cues[i].hasBeenReset || !cues[i].displayState) {
  8576. return true;
  8577. }
  8578. }
  8579. return false;
  8580. }
  8581. // We don't need to recompute the cues' display states. Just reuse them.
  8582. if (!shouldCompute(cues)) {
  8583. for (var i = 0; i < cues.length; i++) {
  8584. paddedOverlay.appendChild(cues[i].displayState);
  8585. }
  8586. return;
  8587. }
  8588. var boxPositions = [],
  8589. containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),
  8590. fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
  8591. var styleOptions = {
  8592. font: fontSize + "px " + FONT_STYLE
  8593. };
  8594. (function () {
  8595. var styleBox, cue;
  8596. for (var i = 0; i < cues.length; i++) {
  8597. cue = cues[i];
  8598. // Compute the intial position and styles of the cue div.
  8599. styleBox = new CueStyleBox(window, cue, styleOptions);
  8600. paddedOverlay.appendChild(styleBox.div);
  8601. // Move the cue div to it's correct line position.
  8602. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions);
  8603. // Remember the computed div so that we don't have to recompute it later
  8604. // if we don't have too.
  8605. cue.displayState = styleBox.div;
  8606. boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
  8607. }
  8608. })();
  8609. };
  8610. WebVTT$1.Parser = function (window, vttjs, decoder) {
  8611. if (!decoder) {
  8612. decoder = vttjs;
  8613. vttjs = {};
  8614. }
  8615. if (!vttjs) {
  8616. vttjs = {};
  8617. }
  8618. this.window = window;
  8619. this.vttjs = vttjs;
  8620. this.state = "INITIAL";
  8621. this.buffer = "";
  8622. this.decoder = decoder || new TextDecoder("utf8");
  8623. this.regionList = [];
  8624. };
  8625. WebVTT$1.Parser.prototype = {
  8626. // If the error is a ParsingError then report it to the consumer if
  8627. // possible. If it's not a ParsingError then throw it like normal.
  8628. reportOrThrowError: function (e) {
  8629. if (e instanceof ParsingError) {
  8630. this.onparsingerror && this.onparsingerror(e);
  8631. } else {
  8632. throw e;
  8633. }
  8634. },
  8635. parse: function (data) {
  8636. var self = this;
  8637. // If there is no data then we won't decode it, but will just try to parse
  8638. // whatever is in buffer already. This may occur in circumstances, for
  8639. // example when flush() is called.
  8640. if (data) {
  8641. // Try to decode the data that we received.
  8642. self.buffer += self.decoder.decode(data, {
  8643. stream: true
  8644. });
  8645. }
  8646. function collectNextLine() {
  8647. var buffer = self.buffer;
  8648. var pos = 0;
  8649. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  8650. ++pos;
  8651. }
  8652. var line = buffer.substr(0, pos);
  8653. // Advance the buffer early in case we fail below.
  8654. if (buffer[pos] === '\r') {
  8655. ++pos;
  8656. }
  8657. if (buffer[pos] === '\n') {
  8658. ++pos;
  8659. }
  8660. self.buffer = buffer.substr(pos);
  8661. return line;
  8662. }
  8663. // 3.4 WebVTT region and WebVTT region settings syntax
  8664. function parseRegion(input) {
  8665. var settings = new Settings();
  8666. parseOptions(input, function (k, v) {
  8667. switch (k) {
  8668. case "id":
  8669. settings.set(k, v);
  8670. break;
  8671. case "width":
  8672. settings.percent(k, v);
  8673. break;
  8674. case "lines":
  8675. settings.integer(k, v);
  8676. break;
  8677. case "regionanchor":
  8678. case "viewportanchor":
  8679. var xy = v.split(',');
  8680. if (xy.length !== 2) {
  8681. break;
  8682. }
  8683. // We have to make sure both x and y parse, so use a temporary
  8684. // settings object here.
  8685. var anchor = new Settings();
  8686. anchor.percent("x", xy[0]);
  8687. anchor.percent("y", xy[1]);
  8688. if (!anchor.has("x") || !anchor.has("y")) {
  8689. break;
  8690. }
  8691. settings.set(k + "X", anchor.get("x"));
  8692. settings.set(k + "Y", anchor.get("y"));
  8693. break;
  8694. case "scroll":
  8695. settings.alt(k, v, ["up"]);
  8696. break;
  8697. }
  8698. }, /=/, /\s/);
  8699. // Create the region, using default values for any values that were not
  8700. // specified.
  8701. if (settings.has("id")) {
  8702. var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();
  8703. region.width = settings.get("width", 100);
  8704. region.lines = settings.get("lines", 3);
  8705. region.regionAnchorX = settings.get("regionanchorX", 0);
  8706. region.regionAnchorY = settings.get("regionanchorY", 100);
  8707. region.viewportAnchorX = settings.get("viewportanchorX", 0);
  8708. region.viewportAnchorY = settings.get("viewportanchorY", 100);
  8709. region.scroll = settings.get("scroll", "");
  8710. // Register the region.
  8711. self.onregion && self.onregion(region);
  8712. // Remember the VTTRegion for later in case we parse any VTTCues that
  8713. // reference it.
  8714. self.regionList.push({
  8715. id: settings.get("id"),
  8716. region: region
  8717. });
  8718. }
  8719. }
  8720. // draft-pantos-http-live-streaming-20
  8721. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-20#section-3.5
  8722. // 3.5 WebVTT
  8723. function parseTimestampMap(input) {
  8724. var settings = new Settings();
  8725. parseOptions(input, function (k, v) {
  8726. switch (k) {
  8727. case "MPEGT":
  8728. settings.integer(k + 'S', v);
  8729. break;
  8730. case "LOCA":
  8731. settings.set(k + 'L', parseTimeStamp(v));
  8732. break;
  8733. }
  8734. }, /[^\d]:/, /,/);
  8735. self.ontimestampmap && self.ontimestampmap({
  8736. "MPEGTS": settings.get("MPEGTS"),
  8737. "LOCAL": settings.get("LOCAL")
  8738. });
  8739. }
  8740. // 3.2 WebVTT metadata header syntax
  8741. function parseHeader(input) {
  8742. if (input.match(/X-TIMESTAMP-MAP/)) {
  8743. // This line contains HLS X-TIMESTAMP-MAP metadata
  8744. parseOptions(input, function (k, v) {
  8745. switch (k) {
  8746. case "X-TIMESTAMP-MAP":
  8747. parseTimestampMap(v);
  8748. break;
  8749. }
  8750. }, /=/);
  8751. } else {
  8752. parseOptions(input, function (k, v) {
  8753. switch (k) {
  8754. case "Region":
  8755. // 3.3 WebVTT region metadata header syntax
  8756. parseRegion(v);
  8757. break;
  8758. }
  8759. }, /:/);
  8760. }
  8761. }
  8762. // 5.1 WebVTT file parsing.
  8763. try {
  8764. var line;
  8765. if (self.state === "INITIAL") {
  8766. // We can't start parsing until we have the first line.
  8767. if (!/\r\n|\n/.test(self.buffer)) {
  8768. return this;
  8769. }
  8770. line = collectNextLine();
  8771. var m = line.match(/^WEBVTT([ \t].*)?$/);
  8772. if (!m || !m[0]) {
  8773. throw new ParsingError(ParsingError.Errors.BadSignature);
  8774. }
  8775. self.state = "HEADER";
  8776. }
  8777. var alreadyCollectedLine = false;
  8778. while (self.buffer) {
  8779. // We can't parse a line until we have the full line.
  8780. if (!/\r\n|\n/.test(self.buffer)) {
  8781. return this;
  8782. }
  8783. if (!alreadyCollectedLine) {
  8784. line = collectNextLine();
  8785. } else {
  8786. alreadyCollectedLine = false;
  8787. }
  8788. switch (self.state) {
  8789. case "HEADER":
  8790. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  8791. if (/:/.test(line)) {
  8792. parseHeader(line);
  8793. } else if (!line) {
  8794. // An empty line terminates the header and starts the body (cues).
  8795. self.state = "ID";
  8796. }
  8797. continue;
  8798. case "NOTE":
  8799. // Ignore NOTE blocks.
  8800. if (!line) {
  8801. self.state = "ID";
  8802. }
  8803. continue;
  8804. case "ID":
  8805. // Check for the start of NOTE blocks.
  8806. if (/^NOTE($|[ \t])/.test(line)) {
  8807. self.state = "NOTE";
  8808. break;
  8809. }
  8810. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  8811. if (!line) {
  8812. continue;
  8813. }
  8814. self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, "");
  8815. // Safari still uses the old middle value and won't accept center
  8816. try {
  8817. self.cue.align = "center";
  8818. } catch (e) {
  8819. self.cue.align = "middle";
  8820. }
  8821. self.state = "CUE";
  8822. // 30-39 - Check if self line contains an optional identifier or timing data.
  8823. if (line.indexOf("-->") === -1) {
  8824. self.cue.id = line;
  8825. continue;
  8826. }
  8827. // Process line as start of a cue.
  8828. /*falls through*/
  8829. case "CUE":
  8830. // 40 - Collect cue timings and settings.
  8831. try {
  8832. parseCue(line, self.cue, self.regionList);
  8833. } catch (e) {
  8834. self.reportOrThrowError(e);
  8835. // In case of an error ignore rest of the cue.
  8836. self.cue = null;
  8837. self.state = "BADCUE";
  8838. continue;
  8839. }
  8840. self.state = "CUETEXT";
  8841. continue;
  8842. case "CUETEXT":
  8843. var hasSubstring = line.indexOf("-->") !== -1;
  8844. // 34 - If we have an empty line then report the cue.
  8845. // 35 - If we have the special substring '-->' then report the cue,
  8846. // but do not collect the line as we need to process the current
  8847. // one as a new cue.
  8848. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  8849. // We are done parsing self cue.
  8850. self.oncue && self.oncue(self.cue);
  8851. self.cue = null;
  8852. self.state = "ID";
  8853. continue;
  8854. }
  8855. if (self.cue.text) {
  8856. self.cue.text += "\n";
  8857. }
  8858. self.cue.text += line.replace(/\u2028/g, '\n').replace(/u2029/g, '\n');
  8859. continue;
  8860. case "BADCUE":
  8861. // BADCUE
  8862. // 54-62 - Collect and discard the remaining cue.
  8863. if (!line) {
  8864. self.state = "ID";
  8865. }
  8866. continue;
  8867. }
  8868. }
  8869. } catch (e) {
  8870. self.reportOrThrowError(e);
  8871. // If we are currently parsing a cue, report what we have.
  8872. if (self.state === "CUETEXT" && self.cue && self.oncue) {
  8873. self.oncue(self.cue);
  8874. }
  8875. self.cue = null;
  8876. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  8877. // another exception occurred so enter BADCUE state.
  8878. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  8879. }
  8880. return this;
  8881. },
  8882. flush: function () {
  8883. var self = this;
  8884. try {
  8885. // Finish decoding the stream.
  8886. self.buffer += self.decoder.decode();
  8887. // Synthesize the end of the current cue or region.
  8888. if (self.cue || self.state === "HEADER") {
  8889. self.buffer += "\n\n";
  8890. self.parse();
  8891. }
  8892. // If we've flushed, parsed, and we're still on the INITIAL state then
  8893. // that means we don't have enough of the stream to parse the first
  8894. // line.
  8895. if (self.state === "INITIAL") {
  8896. throw new ParsingError(ParsingError.Errors.BadSignature);
  8897. }
  8898. } catch (e) {
  8899. self.reportOrThrowError(e);
  8900. }
  8901. self.onflush && self.onflush();
  8902. return this;
  8903. }
  8904. };
  8905. var vtt = WebVTT$1;
  8906. /**
  8907. * Copyright 2013 vtt.js Contributors
  8908. *
  8909. * Licensed under the Apache License, Version 2.0 (the "License");
  8910. * you may not use this file except in compliance with the License.
  8911. * You may obtain a copy of the License at
  8912. *
  8913. * http://www.apache.org/licenses/LICENSE-2.0
  8914. *
  8915. * Unless required by applicable law or agreed to in writing, software
  8916. * distributed under the License is distributed on an "AS IS" BASIS,
  8917. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8918. * See the License for the specific language governing permissions and
  8919. * limitations under the License.
  8920. */
  8921. var autoKeyword = "auto";
  8922. var directionSetting = {
  8923. "": 1,
  8924. "lr": 1,
  8925. "rl": 1
  8926. };
  8927. var alignSetting = {
  8928. "start": 1,
  8929. "center": 1,
  8930. "end": 1,
  8931. "left": 1,
  8932. "right": 1,
  8933. "auto": 1,
  8934. "line-left": 1,
  8935. "line-right": 1
  8936. };
  8937. function findDirectionSetting(value) {
  8938. if (typeof value !== "string") {
  8939. return false;
  8940. }
  8941. var dir = directionSetting[value.toLowerCase()];
  8942. return dir ? value.toLowerCase() : false;
  8943. }
  8944. function findAlignSetting(value) {
  8945. if (typeof value !== "string") {
  8946. return false;
  8947. }
  8948. var align = alignSetting[value.toLowerCase()];
  8949. return align ? value.toLowerCase() : false;
  8950. }
  8951. function VTTCue(startTime, endTime, text) {
  8952. /**
  8953. * Shim implementation specific properties. These properties are not in
  8954. * the spec.
  8955. */
  8956. // Lets us know when the VTTCue's data has changed in such a way that we need
  8957. // to recompute its display state. This lets us compute its display state
  8958. // lazily.
  8959. this.hasBeenReset = false;
  8960. /**
  8961. * VTTCue and TextTrackCue properties
  8962. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  8963. */
  8964. var _id = "";
  8965. var _pauseOnExit = false;
  8966. var _startTime = startTime;
  8967. var _endTime = endTime;
  8968. var _text = text;
  8969. var _region = null;
  8970. var _vertical = "";
  8971. var _snapToLines = true;
  8972. var _line = "auto";
  8973. var _lineAlign = "start";
  8974. var _position = "auto";
  8975. var _positionAlign = "auto";
  8976. var _size = 100;
  8977. var _align = "center";
  8978. Object.defineProperties(this, {
  8979. "id": {
  8980. enumerable: true,
  8981. get: function () {
  8982. return _id;
  8983. },
  8984. set: function (value) {
  8985. _id = "" + value;
  8986. }
  8987. },
  8988. "pauseOnExit": {
  8989. enumerable: true,
  8990. get: function () {
  8991. return _pauseOnExit;
  8992. },
  8993. set: function (value) {
  8994. _pauseOnExit = !!value;
  8995. }
  8996. },
  8997. "startTime": {
  8998. enumerable: true,
  8999. get: function () {
  9000. return _startTime;
  9001. },
  9002. set: function (value) {
  9003. if (typeof value !== "number") {
  9004. throw new TypeError("Start time must be set to a number.");
  9005. }
  9006. _startTime = value;
  9007. this.hasBeenReset = true;
  9008. }
  9009. },
  9010. "endTime": {
  9011. enumerable: true,
  9012. get: function () {
  9013. return _endTime;
  9014. },
  9015. set: function (value) {
  9016. if (typeof value !== "number") {
  9017. throw new TypeError("End time must be set to a number.");
  9018. }
  9019. _endTime = value;
  9020. this.hasBeenReset = true;
  9021. }
  9022. },
  9023. "text": {
  9024. enumerable: true,
  9025. get: function () {
  9026. return _text;
  9027. },
  9028. set: function (value) {
  9029. _text = "" + value;
  9030. this.hasBeenReset = true;
  9031. }
  9032. },
  9033. "region": {
  9034. enumerable: true,
  9035. get: function () {
  9036. return _region;
  9037. },
  9038. set: function (value) {
  9039. _region = value;
  9040. this.hasBeenReset = true;
  9041. }
  9042. },
  9043. "vertical": {
  9044. enumerable: true,
  9045. get: function () {
  9046. return _vertical;
  9047. },
  9048. set: function (value) {
  9049. var setting = findDirectionSetting(value);
  9050. // Have to check for false because the setting an be an empty string.
  9051. if (setting === false) {
  9052. throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");
  9053. }
  9054. _vertical = setting;
  9055. this.hasBeenReset = true;
  9056. }
  9057. },
  9058. "snapToLines": {
  9059. enumerable: true,
  9060. get: function () {
  9061. return _snapToLines;
  9062. },
  9063. set: function (value) {
  9064. _snapToLines = !!value;
  9065. this.hasBeenReset = true;
  9066. }
  9067. },
  9068. "line": {
  9069. enumerable: true,
  9070. get: function () {
  9071. return _line;
  9072. },
  9073. set: function (value) {
  9074. if (typeof value !== "number" && value !== autoKeyword) {
  9075. throw new SyntaxError("Line: an invalid number or illegal string was specified.");
  9076. }
  9077. _line = value;
  9078. this.hasBeenReset = true;
  9079. }
  9080. },
  9081. "lineAlign": {
  9082. enumerable: true,
  9083. get: function () {
  9084. return _lineAlign;
  9085. },
  9086. set: function (value) {
  9087. var setting = findAlignSetting(value);
  9088. if (!setting) {
  9089. console.warn("lineAlign: an invalid or illegal string was specified.");
  9090. } else {
  9091. _lineAlign = setting;
  9092. this.hasBeenReset = true;
  9093. }
  9094. }
  9095. },
  9096. "position": {
  9097. enumerable: true,
  9098. get: function () {
  9099. return _position;
  9100. },
  9101. set: function (value) {
  9102. if (value < 0 || value > 100) {
  9103. throw new Error("Position must be between 0 and 100.");
  9104. }
  9105. _position = value;
  9106. this.hasBeenReset = true;
  9107. }
  9108. },
  9109. "positionAlign": {
  9110. enumerable: true,
  9111. get: function () {
  9112. return _positionAlign;
  9113. },
  9114. set: function (value) {
  9115. var setting = findAlignSetting(value);
  9116. if (!setting) {
  9117. console.warn("positionAlign: an invalid or illegal string was specified.");
  9118. } else {
  9119. _positionAlign = setting;
  9120. this.hasBeenReset = true;
  9121. }
  9122. }
  9123. },
  9124. "size": {
  9125. enumerable: true,
  9126. get: function () {
  9127. return _size;
  9128. },
  9129. set: function (value) {
  9130. if (value < 0 || value > 100) {
  9131. throw new Error("Size must be between 0 and 100.");
  9132. }
  9133. _size = value;
  9134. this.hasBeenReset = true;
  9135. }
  9136. },
  9137. "align": {
  9138. enumerable: true,
  9139. get: function () {
  9140. return _align;
  9141. },
  9142. set: function (value) {
  9143. var setting = findAlignSetting(value);
  9144. if (!setting) {
  9145. throw new SyntaxError("align: an invalid or illegal alignment string was specified.");
  9146. }
  9147. _align = setting;
  9148. this.hasBeenReset = true;
  9149. }
  9150. }
  9151. });
  9152. /**
  9153. * Other <track> spec defined properties
  9154. */
  9155. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  9156. this.displayState = undefined;
  9157. }
  9158. /**
  9159. * VTTCue methods
  9160. */
  9161. VTTCue.prototype.getCueAsHTML = function () {
  9162. // Assume WebVTT.convertCueToDOMTree is on the global.
  9163. return WebVTT.convertCueToDOMTree(window, this.text);
  9164. };
  9165. var vttcue = VTTCue;
  9166. /**
  9167. * Copyright 2013 vtt.js Contributors
  9168. *
  9169. * Licensed under the Apache License, Version 2.0 (the "License");
  9170. * you may not use this file except in compliance with the License.
  9171. * You may obtain a copy of the License at
  9172. *
  9173. * http://www.apache.org/licenses/LICENSE-2.0
  9174. *
  9175. * Unless required by applicable law or agreed to in writing, software
  9176. * distributed under the License is distributed on an "AS IS" BASIS,
  9177. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9178. * See the License for the specific language governing permissions and
  9179. * limitations under the License.
  9180. */
  9181. var scrollSetting = {
  9182. "": true,
  9183. "up": true
  9184. };
  9185. function findScrollSetting(value) {
  9186. if (typeof value !== "string") {
  9187. return false;
  9188. }
  9189. var scroll = scrollSetting[value.toLowerCase()];
  9190. return scroll ? value.toLowerCase() : false;
  9191. }
  9192. function isValidPercentValue(value) {
  9193. return typeof value === "number" && value >= 0 && value <= 100;
  9194. }
  9195. // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface
  9196. function VTTRegion() {
  9197. var _width = 100;
  9198. var _lines = 3;
  9199. var _regionAnchorX = 0;
  9200. var _regionAnchorY = 100;
  9201. var _viewportAnchorX = 0;
  9202. var _viewportAnchorY = 100;
  9203. var _scroll = "";
  9204. Object.defineProperties(this, {
  9205. "width": {
  9206. enumerable: true,
  9207. get: function () {
  9208. return _width;
  9209. },
  9210. set: function (value) {
  9211. if (!isValidPercentValue(value)) {
  9212. throw new Error("Width must be between 0 and 100.");
  9213. }
  9214. _width = value;
  9215. }
  9216. },
  9217. "lines": {
  9218. enumerable: true,
  9219. get: function () {
  9220. return _lines;
  9221. },
  9222. set: function (value) {
  9223. if (typeof value !== "number") {
  9224. throw new TypeError("Lines must be set to a number.");
  9225. }
  9226. _lines = value;
  9227. }
  9228. },
  9229. "regionAnchorY": {
  9230. enumerable: true,
  9231. get: function () {
  9232. return _regionAnchorY;
  9233. },
  9234. set: function (value) {
  9235. if (!isValidPercentValue(value)) {
  9236. throw new Error("RegionAnchorX must be between 0 and 100.");
  9237. }
  9238. _regionAnchorY = value;
  9239. }
  9240. },
  9241. "regionAnchorX": {
  9242. enumerable: true,
  9243. get: function () {
  9244. return _regionAnchorX;
  9245. },
  9246. set: function (value) {
  9247. if (!isValidPercentValue(value)) {
  9248. throw new Error("RegionAnchorY must be between 0 and 100.");
  9249. }
  9250. _regionAnchorX = value;
  9251. }
  9252. },
  9253. "viewportAnchorY": {
  9254. enumerable: true,
  9255. get: function () {
  9256. return _viewportAnchorY;
  9257. },
  9258. set: function (value) {
  9259. if (!isValidPercentValue(value)) {
  9260. throw new Error("ViewportAnchorY must be between 0 and 100.");
  9261. }
  9262. _viewportAnchorY = value;
  9263. }
  9264. },
  9265. "viewportAnchorX": {
  9266. enumerable: true,
  9267. get: function () {
  9268. return _viewportAnchorX;
  9269. },
  9270. set: function (value) {
  9271. if (!isValidPercentValue(value)) {
  9272. throw new Error("ViewportAnchorX must be between 0 and 100.");
  9273. }
  9274. _viewportAnchorX = value;
  9275. }
  9276. },
  9277. "scroll": {
  9278. enumerable: true,
  9279. get: function () {
  9280. return _scroll;
  9281. },
  9282. set: function (value) {
  9283. var setting = findScrollSetting(value);
  9284. // Have to check for false as an empty string is a legal value.
  9285. if (setting === false) {
  9286. console.warn("Scroll: an invalid or illegal string was specified.");
  9287. } else {
  9288. _scroll = setting;
  9289. }
  9290. }
  9291. }
  9292. });
  9293. }
  9294. var vttregion = VTTRegion;
  9295. var browserIndex = createCommonjsModule(function (module) {
  9296. /**
  9297. * Copyright 2013 vtt.js Contributors
  9298. *
  9299. * Licensed under the Apache License, Version 2.0 (the "License");
  9300. * you may not use this file except in compliance with the License.
  9301. * You may obtain a copy of the License at
  9302. *
  9303. * http://www.apache.org/licenses/LICENSE-2.0
  9304. *
  9305. * Unless required by applicable law or agreed to in writing, software
  9306. * distributed under the License is distributed on an "AS IS" BASIS,
  9307. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9308. * See the License for the specific language governing permissions and
  9309. * limitations under the License.
  9310. */
  9311. // Default exports for Node. Export the extended versions of VTTCue and
  9312. // VTTRegion in Node since we likely want the capability to convert back and
  9313. // forth between JSON. If we don't then it's not that big of a deal since we're
  9314. // off browser.
  9315. var vttjs = module.exports = {
  9316. WebVTT: vtt,
  9317. VTTCue: vttcue,
  9318. VTTRegion: vttregion
  9319. };
  9320. window_1.vttjs = vttjs;
  9321. window_1.WebVTT = vttjs.WebVTT;
  9322. var cueShim = vttjs.VTTCue;
  9323. var regionShim = vttjs.VTTRegion;
  9324. var nativeVTTCue = window_1.VTTCue;
  9325. var nativeVTTRegion = window_1.VTTRegion;
  9326. vttjs.shim = function () {
  9327. window_1.VTTCue = cueShim;
  9328. window_1.VTTRegion = regionShim;
  9329. };
  9330. vttjs.restore = function () {
  9331. window_1.VTTCue = nativeVTTCue;
  9332. window_1.VTTRegion = nativeVTTRegion;
  9333. };
  9334. if (!window_1.VTTCue) {
  9335. vttjs.shim();
  9336. }
  9337. });
  9338. browserIndex.WebVTT;
  9339. browserIndex.VTTCue;
  9340. browserIndex.VTTRegion;
  9341. /**
  9342. * @file tech.js
  9343. */
  9344. /**
  9345. * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
  9346. * that just contains the src url alone.
  9347. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
  9348. * `var SourceString = 'http://example.com/some-video.mp4';`
  9349. *
  9350. * @typedef {Object|string} Tech~SourceObject
  9351. *
  9352. * @property {string} src
  9353. * The url to the source
  9354. *
  9355. * @property {string} type
  9356. * The mime type of the source
  9357. */
  9358. /**
  9359. * A function used by {@link Tech} to create a new {@link TextTrack}.
  9360. *
  9361. * @private
  9362. *
  9363. * @param {Tech} self
  9364. * An instance of the Tech class.
  9365. *
  9366. * @param {string} kind
  9367. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  9368. *
  9369. * @param {string} [label]
  9370. * Label to identify the text track
  9371. *
  9372. * @param {string} [language]
  9373. * Two letter language abbreviation
  9374. *
  9375. * @param {Object} [options={}]
  9376. * An object with additional text track options
  9377. *
  9378. * @return {TextTrack}
  9379. * The text track that was created.
  9380. */
  9381. function createTrackHelper(self, kind, label, language, options = {}) {
  9382. const tracks = self.textTracks();
  9383. options.kind = kind;
  9384. if (label) {
  9385. options.label = label;
  9386. }
  9387. if (language) {
  9388. options.language = language;
  9389. }
  9390. options.tech = self;
  9391. const track = new ALL.text.TrackClass(options);
  9392. tracks.addTrack(track);
  9393. return track;
  9394. }
  9395. /**
  9396. * This is the base class for media playback technology controllers, such as
  9397. * {@link HTML5}
  9398. *
  9399. * @extends Component
  9400. */
  9401. class Tech extends Component$1 {
  9402. /**
  9403. * Create an instance of this Tech.
  9404. *
  9405. * @param {Object} [options]
  9406. * The key/value store of player options.
  9407. *
  9408. * @param {Function} [ready]
  9409. * Callback function to call when the `HTML5` Tech is ready.
  9410. */
  9411. constructor(options = {}, ready = function () {}) {
  9412. // we don't want the tech to report user activity automatically.
  9413. // This is done manually in addControlsListeners
  9414. options.reportTouchActivity = false;
  9415. super(null, options, ready);
  9416. this.onDurationChange_ = e => this.onDurationChange(e);
  9417. this.trackProgress_ = e => this.trackProgress(e);
  9418. this.trackCurrentTime_ = e => this.trackCurrentTime(e);
  9419. this.stopTrackingCurrentTime_ = e => this.stopTrackingCurrentTime(e);
  9420. this.disposeSourceHandler_ = e => this.disposeSourceHandler(e);
  9421. this.queuedHanders_ = new Set();
  9422. // keep track of whether the current source has played at all to
  9423. // implement a very limited played()
  9424. this.hasStarted_ = false;
  9425. this.on('playing', function () {
  9426. this.hasStarted_ = true;
  9427. });
  9428. this.on('loadstart', function () {
  9429. this.hasStarted_ = false;
  9430. });
  9431. ALL.names.forEach(name => {
  9432. const props = ALL[name];
  9433. if (options && options[props.getterName]) {
  9434. this[props.privateName] = options[props.getterName];
  9435. }
  9436. });
  9437. // Manually track progress in cases where the browser/tech doesn't report it.
  9438. if (!this.featuresProgressEvents) {
  9439. this.manualProgressOn();
  9440. }
  9441. // Manually track timeupdates in cases where the browser/tech doesn't report it.
  9442. if (!this.featuresTimeupdateEvents) {
  9443. this.manualTimeUpdatesOn();
  9444. }
  9445. ['Text', 'Audio', 'Video'].forEach(track => {
  9446. if (options[`native${track}Tracks`] === false) {
  9447. this[`featuresNative${track}Tracks`] = false;
  9448. }
  9449. });
  9450. if (options.nativeCaptions === false || options.nativeTextTracks === false) {
  9451. this.featuresNativeTextTracks = false;
  9452. } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
  9453. this.featuresNativeTextTracks = true;
  9454. }
  9455. if (!this.featuresNativeTextTracks) {
  9456. this.emulateTextTracks();
  9457. }
  9458. this.preloadTextTracks = options.preloadTextTracks !== false;
  9459. this.autoRemoteTextTracks_ = new ALL.text.ListClass();
  9460. this.initTrackListeners();
  9461. // Turn on component tap events only if not using native controls
  9462. if (!options.nativeControlsForTouch) {
  9463. this.emitTapEvents();
  9464. }
  9465. if (this.constructor) {
  9466. this.name_ = this.constructor.name || 'Unknown Tech';
  9467. }
  9468. }
  9469. /**
  9470. * A special function to trigger source set in a way that will allow player
  9471. * to re-trigger if the player or tech are not ready yet.
  9472. *
  9473. * @fires Tech#sourceset
  9474. * @param {string} src The source string at the time of the source changing.
  9475. */
  9476. triggerSourceset(src) {
  9477. if (!this.isReady_) {
  9478. // on initial ready we have to trigger source set
  9479. // 1ms after ready so that player can watch for it.
  9480. this.one('ready', () => this.setTimeout(() => this.triggerSourceset(src), 1));
  9481. }
  9482. /**
  9483. * Fired when the source is set on the tech causing the media element
  9484. * to reload.
  9485. *
  9486. * @see {@link Player#event:sourceset}
  9487. * @event Tech#sourceset
  9488. * @type {Event}
  9489. */
  9490. this.trigger({
  9491. src,
  9492. type: 'sourceset'
  9493. });
  9494. }
  9495. /* Fallbacks for unsupported event types
  9496. ================================================================================ */
  9497. /**
  9498. * Polyfill the `progress` event for browsers that don't support it natively.
  9499. *
  9500. * @see {@link Tech#trackProgress}
  9501. */
  9502. manualProgressOn() {
  9503. this.on('durationchange', this.onDurationChange_);
  9504. this.manualProgress = true;
  9505. // Trigger progress watching when a source begins loading
  9506. this.one('ready', this.trackProgress_);
  9507. }
  9508. /**
  9509. * Turn off the polyfill for `progress` events that was created in
  9510. * {@link Tech#manualProgressOn}
  9511. */
  9512. manualProgressOff() {
  9513. this.manualProgress = false;
  9514. this.stopTrackingProgress();
  9515. this.off('durationchange', this.onDurationChange_);
  9516. }
  9517. /**
  9518. * This is used to trigger a `progress` event when the buffered percent changes. It
  9519. * sets an interval function that will be called every 500 milliseconds to check if the
  9520. * buffer end percent has changed.
  9521. *
  9522. * > This function is called by {@link Tech#manualProgressOn}
  9523. *
  9524. * @param {Event} event
  9525. * The `ready` event that caused this to run.
  9526. *
  9527. * @listens Tech#ready
  9528. * @fires Tech#progress
  9529. */
  9530. trackProgress(event) {
  9531. this.stopTrackingProgress();
  9532. this.progressInterval = this.setInterval(bind_(this, function () {
  9533. // Don't trigger unless buffered amount is greater than last time
  9534. const numBufferedPercent = this.bufferedPercent();
  9535. if (this.bufferedPercent_ !== numBufferedPercent) {
  9536. /**
  9537. * See {@link Player#progress}
  9538. *
  9539. * @event Tech#progress
  9540. * @type {Event}
  9541. */
  9542. this.trigger('progress');
  9543. }
  9544. this.bufferedPercent_ = numBufferedPercent;
  9545. if (numBufferedPercent === 1) {
  9546. this.stopTrackingProgress();
  9547. }
  9548. }), 500);
  9549. }
  9550. /**
  9551. * Update our internal duration on a `durationchange` event by calling
  9552. * {@link Tech#duration}.
  9553. *
  9554. * @param {Event} event
  9555. * The `durationchange` event that caused this to run.
  9556. *
  9557. * @listens Tech#durationchange
  9558. */
  9559. onDurationChange(event) {
  9560. this.duration_ = this.duration();
  9561. }
  9562. /**
  9563. * Get and create a `TimeRange` object for buffering.
  9564. *
  9565. * @return { import('../utils/time').TimeRange }
  9566. * The time range object that was created.
  9567. */
  9568. buffered() {
  9569. return createTimeRanges$1(0, 0);
  9570. }
  9571. /**
  9572. * Get the percentage of the current video that is currently buffered.
  9573. *
  9574. * @return {number}
  9575. * A number from 0 to 1 that represents the decimal percentage of the
  9576. * video that is buffered.
  9577. *
  9578. */
  9579. bufferedPercent() {
  9580. return bufferedPercent(this.buffered(), this.duration_);
  9581. }
  9582. /**
  9583. * Turn off the polyfill for `progress` events that was created in
  9584. * {@link Tech#manualProgressOn}
  9585. * Stop manually tracking progress events by clearing the interval that was set in
  9586. * {@link Tech#trackProgress}.
  9587. */
  9588. stopTrackingProgress() {
  9589. this.clearInterval(this.progressInterval);
  9590. }
  9591. /**
  9592. * Polyfill the `timeupdate` event for browsers that don't support it.
  9593. *
  9594. * @see {@link Tech#trackCurrentTime}
  9595. */
  9596. manualTimeUpdatesOn() {
  9597. this.manualTimeUpdates = true;
  9598. this.on('play', this.trackCurrentTime_);
  9599. this.on('pause', this.stopTrackingCurrentTime_);
  9600. }
  9601. /**
  9602. * Turn off the polyfill for `timeupdate` events that was created in
  9603. * {@link Tech#manualTimeUpdatesOn}
  9604. */
  9605. manualTimeUpdatesOff() {
  9606. this.manualTimeUpdates = false;
  9607. this.stopTrackingCurrentTime();
  9608. this.off('play', this.trackCurrentTime_);
  9609. this.off('pause', this.stopTrackingCurrentTime_);
  9610. }
  9611. /**
  9612. * Sets up an interval function to track current time and trigger `timeupdate` every
  9613. * 250 milliseconds.
  9614. *
  9615. * @listens Tech#play
  9616. * @triggers Tech#timeupdate
  9617. */
  9618. trackCurrentTime() {
  9619. if (this.currentTimeInterval) {
  9620. this.stopTrackingCurrentTime();
  9621. }
  9622. this.currentTimeInterval = this.setInterval(function () {
  9623. /**
  9624. * Triggered at an interval of 250ms to indicated that time is passing in the video.
  9625. *
  9626. * @event Tech#timeupdate
  9627. * @type {Event}
  9628. */
  9629. this.trigger({
  9630. type: 'timeupdate',
  9631. target: this,
  9632. manuallyTriggered: true
  9633. });
  9634. // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  9635. }, 250);
  9636. }
  9637. /**
  9638. * Stop the interval function created in {@link Tech#trackCurrentTime} so that the
  9639. * `timeupdate` event is no longer triggered.
  9640. *
  9641. * @listens {Tech#pause}
  9642. */
  9643. stopTrackingCurrentTime() {
  9644. this.clearInterval(this.currentTimeInterval);
  9645. // #1002 - if the video ends right before the next timeupdate would happen,
  9646. // the progress bar won't make it all the way to the end
  9647. this.trigger({
  9648. type: 'timeupdate',
  9649. target: this,
  9650. manuallyTriggered: true
  9651. });
  9652. }
  9653. /**
  9654. * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},
  9655. * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.
  9656. *
  9657. * @fires Component#dispose
  9658. */
  9659. dispose() {
  9660. // clear out all tracks because we can't reuse them between techs
  9661. this.clearTracks(NORMAL.names);
  9662. // Turn off any manual progress or timeupdate tracking
  9663. if (this.manualProgress) {
  9664. this.manualProgressOff();
  9665. }
  9666. if (this.manualTimeUpdates) {
  9667. this.manualTimeUpdatesOff();
  9668. }
  9669. super.dispose();
  9670. }
  9671. /**
  9672. * Clear out a single `TrackList` or an array of `TrackLists` given their names.
  9673. *
  9674. * > Note: Techs without source handlers should call this between sources for `video`
  9675. * & `audio` tracks. You don't want to use them between tracks!
  9676. *
  9677. * @param {string[]|string} types
  9678. * TrackList names to clear, valid names are `video`, `audio`, and
  9679. * `text`.
  9680. */
  9681. clearTracks(types) {
  9682. types = [].concat(types);
  9683. // clear out all tracks because we can't reuse them between techs
  9684. types.forEach(type => {
  9685. const list = this[`${type}Tracks`]() || [];
  9686. let i = list.length;
  9687. while (i--) {
  9688. const track = list[i];
  9689. if (type === 'text') {
  9690. this.removeRemoteTextTrack(track);
  9691. }
  9692. list.removeTrack(track);
  9693. }
  9694. });
  9695. }
  9696. /**
  9697. * Remove any TextTracks added via addRemoteTextTrack that are
  9698. * flagged for automatic garbage collection
  9699. */
  9700. cleanupAutoTextTracks() {
  9701. const list = this.autoRemoteTextTracks_ || [];
  9702. let i = list.length;
  9703. while (i--) {
  9704. const track = list[i];
  9705. this.removeRemoteTextTrack(track);
  9706. }
  9707. }
  9708. /**
  9709. * Reset the tech, which will removes all sources and reset the internal readyState.
  9710. *
  9711. * @abstract
  9712. */
  9713. reset() {}
  9714. /**
  9715. * Get the value of `crossOrigin` from the tech.
  9716. *
  9717. * @abstract
  9718. *
  9719. * @see {Html5#crossOrigin}
  9720. */
  9721. crossOrigin() {}
  9722. /**
  9723. * Set the value of `crossOrigin` on the tech.
  9724. *
  9725. * @abstract
  9726. *
  9727. * @param {string} crossOrigin the crossOrigin value
  9728. * @see {Html5#setCrossOrigin}
  9729. */
  9730. setCrossOrigin() {}
  9731. /**
  9732. * Get or set an error on the Tech.
  9733. *
  9734. * @param {MediaError} [err]
  9735. * Error to set on the Tech
  9736. *
  9737. * @return {MediaError|null}
  9738. * The current error object on the tech, or null if there isn't one.
  9739. */
  9740. error(err) {
  9741. if (err !== undefined) {
  9742. this.error_ = new MediaError(err);
  9743. this.trigger('error');
  9744. }
  9745. return this.error_;
  9746. }
  9747. /**
  9748. * Returns the `TimeRange`s that have been played through for the current source.
  9749. *
  9750. * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.
  9751. * It only checks whether the source has played at all or not.
  9752. *
  9753. * @return {TimeRange}
  9754. * - A single time range if this video has played
  9755. * - An empty set of ranges if not.
  9756. */
  9757. played() {
  9758. if (this.hasStarted_) {
  9759. return createTimeRanges$1(0, 0);
  9760. }
  9761. return createTimeRanges$1();
  9762. }
  9763. /**
  9764. * Start playback
  9765. *
  9766. * @abstract
  9767. *
  9768. * @see {Html5#play}
  9769. */
  9770. play() {}
  9771. /**
  9772. * Set whether we are scrubbing or not
  9773. *
  9774. * @abstract
  9775. * @param {boolean} _isScrubbing
  9776. * - true for we are currently scrubbing
  9777. * - false for we are no longer scrubbing
  9778. *
  9779. * @see {Html5#setScrubbing}
  9780. */
  9781. setScrubbing(_isScrubbing) {}
  9782. /**
  9783. * Get whether we are scrubbing or not
  9784. *
  9785. * @abstract
  9786. *
  9787. * @see {Html5#scrubbing}
  9788. */
  9789. scrubbing() {}
  9790. /**
  9791. * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was
  9792. * previously called.
  9793. *
  9794. * @param {number} _seconds
  9795. * Set the current time of the media to this.
  9796. * @fires Tech#timeupdate
  9797. */
  9798. setCurrentTime(_seconds) {
  9799. // improve the accuracy of manual timeupdates
  9800. if (this.manualTimeUpdates) {
  9801. /**
  9802. * A manual `timeupdate` event.
  9803. *
  9804. * @event Tech#timeupdate
  9805. * @type {Event}
  9806. */
  9807. this.trigger({
  9808. type: 'timeupdate',
  9809. target: this,
  9810. manuallyTriggered: true
  9811. });
  9812. }
  9813. }
  9814. /**
  9815. * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
  9816. * {@link TextTrackList} events.
  9817. *
  9818. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
  9819. *
  9820. * @fires Tech#audiotrackchange
  9821. * @fires Tech#videotrackchange
  9822. * @fires Tech#texttrackchange
  9823. */
  9824. initTrackListeners() {
  9825. /**
  9826. * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
  9827. *
  9828. * @event Tech#audiotrackchange
  9829. * @type {Event}
  9830. */
  9831. /**
  9832. * Triggered when tracks are added or removed on the Tech {@link VideoTrackList}
  9833. *
  9834. * @event Tech#videotrackchange
  9835. * @type {Event}
  9836. */
  9837. /**
  9838. * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
  9839. *
  9840. * @event Tech#texttrackchange
  9841. * @type {Event}
  9842. */
  9843. NORMAL.names.forEach(name => {
  9844. const props = NORMAL[name];
  9845. const trackListChanges = () => {
  9846. this.trigger(`${name}trackchange`);
  9847. };
  9848. const tracks = this[props.getterName]();
  9849. tracks.addEventListener('removetrack', trackListChanges);
  9850. tracks.addEventListener('addtrack', trackListChanges);
  9851. this.on('dispose', () => {
  9852. tracks.removeEventListener('removetrack', trackListChanges);
  9853. tracks.removeEventListener('addtrack', trackListChanges);
  9854. });
  9855. });
  9856. }
  9857. /**
  9858. * Emulate TextTracks using vtt.js if necessary
  9859. *
  9860. * @fires Tech#vttjsloaded
  9861. * @fires Tech#vttjserror
  9862. */
  9863. addWebVttScript_() {
  9864. if (window.WebVTT) {
  9865. return;
  9866. }
  9867. // Initially, Tech.el_ is a child of a dummy-div wait until the Component system
  9868. // signals that the Tech is ready at which point Tech.el_ is part of the DOM
  9869. // before inserting the WebVTT script
  9870. if (document.body.contains(this.el())) {
  9871. // load via require if available and vtt.js script location was not passed in
  9872. // as an option. novtt builds will turn the above require call into an empty object
  9873. // which will cause this if check to always fail.
  9874. if (!this.options_['vtt.js'] && isPlain(browserIndex) && Object.keys(browserIndex).length > 0) {
  9875. this.trigger('vttjsloaded');
  9876. return;
  9877. }
  9878. // load vtt.js via the script location option or the cdn of no location was
  9879. // passed in
  9880. const script = document.createElement('script');
  9881. script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';
  9882. script.onload = () => {
  9883. /**
  9884. * Fired when vtt.js is loaded.
  9885. *
  9886. * @event Tech#vttjsloaded
  9887. * @type {Event}
  9888. */
  9889. this.trigger('vttjsloaded');
  9890. };
  9891. script.onerror = () => {
  9892. /**
  9893. * Fired when vtt.js was not loaded due to an error
  9894. *
  9895. * @event Tech#vttjsloaded
  9896. * @type {Event}
  9897. */
  9898. this.trigger('vttjserror');
  9899. };
  9900. this.on('dispose', () => {
  9901. script.onload = null;
  9902. script.onerror = null;
  9903. });
  9904. // but have not loaded yet and we set it to true before the inject so that
  9905. // we don't overwrite the injected window.WebVTT if it loads right away
  9906. window.WebVTT = true;
  9907. this.el().parentNode.appendChild(script);
  9908. } else {
  9909. this.ready(this.addWebVttScript_);
  9910. }
  9911. }
  9912. /**
  9913. * Emulate texttracks
  9914. *
  9915. */
  9916. emulateTextTracks() {
  9917. const tracks = this.textTracks();
  9918. const remoteTracks = this.remoteTextTracks();
  9919. const handleAddTrack = e => tracks.addTrack(e.track);
  9920. const handleRemoveTrack = e => tracks.removeTrack(e.track);
  9921. remoteTracks.on('addtrack', handleAddTrack);
  9922. remoteTracks.on('removetrack', handleRemoveTrack);
  9923. this.addWebVttScript_();
  9924. const updateDisplay = () => this.trigger('texttrackchange');
  9925. const textTracksChanges = () => {
  9926. updateDisplay();
  9927. for (let i = 0; i < tracks.length; i++) {
  9928. const track = tracks[i];
  9929. track.removeEventListener('cuechange', updateDisplay);
  9930. if (track.mode === 'showing') {
  9931. track.addEventListener('cuechange', updateDisplay);
  9932. }
  9933. }
  9934. };
  9935. textTracksChanges();
  9936. tracks.addEventListener('change', textTracksChanges);
  9937. tracks.addEventListener('addtrack', textTracksChanges);
  9938. tracks.addEventListener('removetrack', textTracksChanges);
  9939. this.on('dispose', function () {
  9940. remoteTracks.off('addtrack', handleAddTrack);
  9941. remoteTracks.off('removetrack', handleRemoveTrack);
  9942. tracks.removeEventListener('change', textTracksChanges);
  9943. tracks.removeEventListener('addtrack', textTracksChanges);
  9944. tracks.removeEventListener('removetrack', textTracksChanges);
  9945. for (let i = 0; i < tracks.length; i++) {
  9946. const track = tracks[i];
  9947. track.removeEventListener('cuechange', updateDisplay);
  9948. }
  9949. });
  9950. }
  9951. /**
  9952. * Create and returns a remote {@link TextTrack} object.
  9953. *
  9954. * @param {string} kind
  9955. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  9956. *
  9957. * @param {string} [label]
  9958. * Label to identify the text track
  9959. *
  9960. * @param {string} [language]
  9961. * Two letter language abbreviation
  9962. *
  9963. * @return {TextTrack}
  9964. * The TextTrack that gets created.
  9965. */
  9966. addTextTrack(kind, label, language) {
  9967. if (!kind) {
  9968. throw new Error('TextTrack kind is required but was not provided');
  9969. }
  9970. return createTrackHelper(this, kind, label, language);
  9971. }
  9972. /**
  9973. * Create an emulated TextTrack for use by addRemoteTextTrack
  9974. *
  9975. * This is intended to be overridden by classes that inherit from
  9976. * Tech in order to create native or custom TextTracks.
  9977. *
  9978. * @param {Object} options
  9979. * The object should contain the options to initialize the TextTrack with.
  9980. *
  9981. * @param {string} [options.kind]
  9982. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  9983. *
  9984. * @param {string} [options.label].
  9985. * Label to identify the text track
  9986. *
  9987. * @param {string} [options.language]
  9988. * Two letter language abbreviation.
  9989. *
  9990. * @return {HTMLTrackElement}
  9991. * The track element that gets created.
  9992. */
  9993. createRemoteTextTrack(options) {
  9994. const track = merge$2(options, {
  9995. tech: this
  9996. });
  9997. return new REMOTE.remoteTextEl.TrackClass(track);
  9998. }
  9999. /**
  10000. * Creates a remote text track object and returns an html track element.
  10001. *
  10002. * > Note: This can be an emulated {@link HTMLTrackElement} or a native one.
  10003. *
  10004. * @param {Object} options
  10005. * See {@link Tech#createRemoteTextTrack} for more detailed properties.
  10006. *
  10007. * @param {boolean} [manualCleanup=false]
  10008. * - When false: the TextTrack will be automatically removed from the video
  10009. * element whenever the source changes
  10010. * - When True: The TextTrack will have to be cleaned up manually
  10011. *
  10012. * @return {HTMLTrackElement}
  10013. * An Html Track Element.
  10014. *
  10015. */
  10016. addRemoteTextTrack(options = {}, manualCleanup) {
  10017. const htmlTrackElement = this.createRemoteTextTrack(options);
  10018. if (typeof manualCleanup !== 'boolean') {
  10019. manualCleanup = false;
  10020. }
  10021. // store HTMLTrackElement and TextTrack to remote list
  10022. this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
  10023. this.remoteTextTracks().addTrack(htmlTrackElement.track);
  10024. if (manualCleanup === false) {
  10025. // create the TextTrackList if it doesn't exist
  10026. this.ready(() => this.autoRemoteTextTracks_.addTrack(htmlTrackElement.track));
  10027. }
  10028. return htmlTrackElement;
  10029. }
  10030. /**
  10031. * Remove a remote text track from the remote `TextTrackList`.
  10032. *
  10033. * @param {TextTrack} track
  10034. * `TextTrack` to remove from the `TextTrackList`
  10035. */
  10036. removeRemoteTextTrack(track) {
  10037. const trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);
  10038. // remove HTMLTrackElement and TextTrack from remote list
  10039. this.remoteTextTrackEls().removeTrackElement_(trackElement);
  10040. this.remoteTextTracks().removeTrack(track);
  10041. this.autoRemoteTextTracks_.removeTrack(track);
  10042. }
  10043. /**
  10044. * Gets available media playback quality metrics as specified by the W3C's Media
  10045. * Playback Quality API.
  10046. *
  10047. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  10048. *
  10049. * @return {Object}
  10050. * An object with supported media playback quality metrics
  10051. *
  10052. * @abstract
  10053. */
  10054. getVideoPlaybackQuality() {
  10055. return {};
  10056. }
  10057. /**
  10058. * Attempt to create a floating video window always on top of other windows
  10059. * so that users may continue consuming media while they interact with other
  10060. * content sites, or applications on their device.
  10061. *
  10062. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  10063. *
  10064. * @return {Promise|undefined}
  10065. * A promise with a Picture-in-Picture window if the browser supports
  10066. * Promises (or one was passed in as an option). It returns undefined
  10067. * otherwise.
  10068. *
  10069. * @abstract
  10070. */
  10071. requestPictureInPicture() {
  10072. return Promise.reject();
  10073. }
  10074. /**
  10075. * A method to check for the value of the 'disablePictureInPicture' <video> property.
  10076. * Defaults to true, as it should be considered disabled if the tech does not support pip
  10077. *
  10078. * @abstract
  10079. */
  10080. disablePictureInPicture() {
  10081. return true;
  10082. }
  10083. /**
  10084. * A method to set or unset the 'disablePictureInPicture' <video> property.
  10085. *
  10086. * @abstract
  10087. */
  10088. setDisablePictureInPicture() {}
  10089. /**
  10090. * A fallback implementation of requestVideoFrameCallback using requestAnimationFrame
  10091. *
  10092. * @param {function} cb
  10093. * @return {number} request id
  10094. */
  10095. requestVideoFrameCallback(cb) {
  10096. const id = newGUID();
  10097. if (!this.isReady_ || this.paused()) {
  10098. this.queuedHanders_.add(id);
  10099. this.one('playing', () => {
  10100. if (this.queuedHanders_.has(id)) {
  10101. this.queuedHanders_.delete(id);
  10102. cb();
  10103. }
  10104. });
  10105. } else {
  10106. this.requestNamedAnimationFrame(id, cb);
  10107. }
  10108. return id;
  10109. }
  10110. /**
  10111. * A fallback implementation of cancelVideoFrameCallback
  10112. *
  10113. * @param {number} id id of callback to be cancelled
  10114. */
  10115. cancelVideoFrameCallback(id) {
  10116. if (this.queuedHanders_.has(id)) {
  10117. this.queuedHanders_.delete(id);
  10118. } else {
  10119. this.cancelNamedAnimationFrame(id);
  10120. }
  10121. }
  10122. /**
  10123. * A method to set a poster from a `Tech`.
  10124. *
  10125. * @abstract
  10126. */
  10127. setPoster() {}
  10128. /**
  10129. * A method to check for the presence of the 'playsinline' <video> attribute.
  10130. *
  10131. * @abstract
  10132. */
  10133. playsinline() {}
  10134. /**
  10135. * A method to set or unset the 'playsinline' <video> attribute.
  10136. *
  10137. * @abstract
  10138. */
  10139. setPlaysinline() {}
  10140. /**
  10141. * Attempt to force override of native audio tracks.
  10142. *
  10143. * @param {boolean} override - If set to true native audio will be overridden,
  10144. * otherwise native audio will potentially be used.
  10145. *
  10146. * @abstract
  10147. */
  10148. overrideNativeAudioTracks(override) {}
  10149. /**
  10150. * Attempt to force override of native video tracks.
  10151. *
  10152. * @param {boolean} override - If set to true native video will be overridden,
  10153. * otherwise native video will potentially be used.
  10154. *
  10155. * @abstract
  10156. */
  10157. overrideNativeVideoTracks(override) {}
  10158. /**
  10159. * Check if the tech can support the given mime-type.
  10160. *
  10161. * The base tech does not support any type, but source handlers might
  10162. * overwrite this.
  10163. *
  10164. * @param {string} _type
  10165. * The mimetype to check for support
  10166. *
  10167. * @return {string}
  10168. * 'probably', 'maybe', or empty string
  10169. *
  10170. * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}
  10171. *
  10172. * @abstract
  10173. */
  10174. canPlayType(_type) {
  10175. return '';
  10176. }
  10177. /**
  10178. * Check if the type is supported by this tech.
  10179. *
  10180. * The base tech does not support any type, but source handlers might
  10181. * overwrite this.
  10182. *
  10183. * @param {string} _type
  10184. * The media type to check
  10185. * @return {string} Returns the native video element's response
  10186. */
  10187. static canPlayType(_type) {
  10188. return '';
  10189. }
  10190. /**
  10191. * Check if the tech can support the given source
  10192. *
  10193. * @param {Object} srcObj
  10194. * The source object
  10195. * @param {Object} options
  10196. * The options passed to the tech
  10197. * @return {string} 'probably', 'maybe', or '' (empty string)
  10198. */
  10199. static canPlaySource(srcObj, options) {
  10200. return Tech.canPlayType(srcObj.type);
  10201. }
  10202. /*
  10203. * Return whether the argument is a Tech or not.
  10204. * Can be passed either a Class like `Html5` or a instance like `player.tech_`
  10205. *
  10206. * @param {Object} component
  10207. * The item to check
  10208. *
  10209. * @return {boolean}
  10210. * Whether it is a tech or not
  10211. * - True if it is a tech
  10212. * - False if it is not
  10213. */
  10214. static isTech(component) {
  10215. return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
  10216. }
  10217. /**
  10218. * Registers a `Tech` into a shared list for videojs.
  10219. *
  10220. * @param {string} name
  10221. * Name of the `Tech` to register.
  10222. *
  10223. * @param {Object} tech
  10224. * The `Tech` class to register.
  10225. */
  10226. static registerTech(name, tech) {
  10227. if (!Tech.techs_) {
  10228. Tech.techs_ = {};
  10229. }
  10230. if (!Tech.isTech(tech)) {
  10231. throw new Error(`Tech ${name} must be a Tech`);
  10232. }
  10233. if (!Tech.canPlayType) {
  10234. throw new Error('Techs must have a static canPlayType method on them');
  10235. }
  10236. if (!Tech.canPlaySource) {
  10237. throw new Error('Techs must have a static canPlaySource method on them');
  10238. }
  10239. name = toTitleCase$1(name);
  10240. Tech.techs_[name] = tech;
  10241. Tech.techs_[toLowerCase(name)] = tech;
  10242. if (name !== 'Tech') {
  10243. // camel case the techName for use in techOrder
  10244. Tech.defaultTechOrder_.push(name);
  10245. }
  10246. return tech;
  10247. }
  10248. /**
  10249. * Get a `Tech` from the shared list by name.
  10250. *
  10251. * @param {string} name
  10252. * `camelCase` or `TitleCase` name of the Tech to get
  10253. *
  10254. * @return {Tech|undefined}
  10255. * The `Tech` or undefined if there was no tech with the name requested.
  10256. */
  10257. static getTech(name) {
  10258. if (!name) {
  10259. return;
  10260. }
  10261. if (Tech.techs_ && Tech.techs_[name]) {
  10262. return Tech.techs_[name];
  10263. }
  10264. name = toTitleCase$1(name);
  10265. if (window && window.videojs && window.videojs[name]) {
  10266. log$1.warn(`The ${name} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`);
  10267. return window.videojs[name];
  10268. }
  10269. }
  10270. }
  10271. /**
  10272. * Get the {@link VideoTrackList}
  10273. *
  10274. * @returns {VideoTrackList}
  10275. * @method Tech.prototype.videoTracks
  10276. */
  10277. /**
  10278. * Get the {@link AudioTrackList}
  10279. *
  10280. * @returns {AudioTrackList}
  10281. * @method Tech.prototype.audioTracks
  10282. */
  10283. /**
  10284. * Get the {@link TextTrackList}
  10285. *
  10286. * @returns {TextTrackList}
  10287. * @method Tech.prototype.textTracks
  10288. */
  10289. /**
  10290. * Get the remote element {@link TextTrackList}
  10291. *
  10292. * @returns {TextTrackList}
  10293. * @method Tech.prototype.remoteTextTracks
  10294. */
  10295. /**
  10296. * Get the remote element {@link HtmlTrackElementList}
  10297. *
  10298. * @returns {HtmlTrackElementList}
  10299. * @method Tech.prototype.remoteTextTrackEls
  10300. */
  10301. ALL.names.forEach(function (name) {
  10302. const props = ALL[name];
  10303. Tech.prototype[props.getterName] = function () {
  10304. this[props.privateName] = this[props.privateName] || new props.ListClass();
  10305. return this[props.privateName];
  10306. };
  10307. });
  10308. /**
  10309. * List of associated text tracks
  10310. *
  10311. * @type {TextTrackList}
  10312. * @private
  10313. * @property Tech#textTracks_
  10314. */
  10315. /**
  10316. * List of associated audio tracks.
  10317. *
  10318. * @type {AudioTrackList}
  10319. * @private
  10320. * @property Tech#audioTracks_
  10321. */
  10322. /**
  10323. * List of associated video tracks.
  10324. *
  10325. * @type {VideoTrackList}
  10326. * @private
  10327. * @property Tech#videoTracks_
  10328. */
  10329. /**
  10330. * Boolean indicating whether the `Tech` supports volume control.
  10331. *
  10332. * @type {boolean}
  10333. * @default
  10334. */
  10335. Tech.prototype.featuresVolumeControl = true;
  10336. /**
  10337. * Boolean indicating whether the `Tech` supports muting volume.
  10338. *
  10339. * @type {boolean}
  10340. * @default
  10341. */
  10342. Tech.prototype.featuresMuteControl = true;
  10343. /**
  10344. * Boolean indicating whether the `Tech` supports fullscreen resize control.
  10345. * Resizing plugins using request fullscreen reloads the plugin
  10346. *
  10347. * @type {boolean}
  10348. * @default
  10349. */
  10350. Tech.prototype.featuresFullscreenResize = false;
  10351. /**
  10352. * Boolean indicating whether the `Tech` supports changing the speed at which the video
  10353. * plays. Examples:
  10354. * - Set player to play 2x (twice) as fast
  10355. * - Set player to play 0.5x (half) as fast
  10356. *
  10357. * @type {boolean}
  10358. * @default
  10359. */
  10360. Tech.prototype.featuresPlaybackRate = false;
  10361. /**
  10362. * Boolean indicating whether the `Tech` supports the `progress` event.
  10363. * This will be used to determine if {@link Tech#manualProgressOn} should be called.
  10364. *
  10365. * @type {boolean}
  10366. * @default
  10367. */
  10368. Tech.prototype.featuresProgressEvents = false;
  10369. /**
  10370. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  10371. *
  10372. * A tech should set this to `true` and then use {@link Tech#triggerSourceset}
  10373. * to trigger a {@link Tech#event:sourceset} at the earliest time after getting
  10374. * a new source.
  10375. *
  10376. * @type {boolean}
  10377. * @default
  10378. */
  10379. Tech.prototype.featuresSourceset = false;
  10380. /**
  10381. * Boolean indicating whether the `Tech` supports the `timeupdate` event.
  10382. * This will be used to determine if {@link Tech#manualTimeUpdates} should be called.
  10383. *
  10384. * @type {boolean}
  10385. * @default
  10386. */
  10387. Tech.prototype.featuresTimeupdateEvents = false;
  10388. /**
  10389. * Boolean indicating whether the `Tech` supports the native `TextTrack`s.
  10390. * This will help us integrate with native `TextTrack`s if the browser supports them.
  10391. *
  10392. * @type {boolean}
  10393. * @default
  10394. */
  10395. Tech.prototype.featuresNativeTextTracks = false;
  10396. /**
  10397. * Boolean indicating whether the `Tech` supports `requestVideoFrameCallback`.
  10398. *
  10399. * @type {boolean}
  10400. * @default
  10401. */
  10402. Tech.prototype.featuresVideoFrameCallback = false;
  10403. /**
  10404. * A functional mixin for techs that want to use the Source Handler pattern.
  10405. * Source handlers are scripts for handling specific formats.
  10406. * The source handler pattern is used for adaptive formats (HLS, DASH) that
  10407. * manually load video data and feed it into a Source Buffer (Media Source Extensions)
  10408. * Example: `Tech.withSourceHandlers.call(MyTech);`
  10409. *
  10410. * @param {Tech} _Tech
  10411. * The tech to add source handler functions to.
  10412. *
  10413. * @mixes Tech~SourceHandlerAdditions
  10414. */
  10415. Tech.withSourceHandlers = function (_Tech) {
  10416. /**
  10417. * Register a source handler
  10418. *
  10419. * @param {Function} handler
  10420. * The source handler class
  10421. *
  10422. * @param {number} [index]
  10423. * Register it at the following index
  10424. */
  10425. _Tech.registerSourceHandler = function (handler, index) {
  10426. let handlers = _Tech.sourceHandlers;
  10427. if (!handlers) {
  10428. handlers = _Tech.sourceHandlers = [];
  10429. }
  10430. if (index === undefined) {
  10431. // add to the end of the list
  10432. index = handlers.length;
  10433. }
  10434. handlers.splice(index, 0, handler);
  10435. };
  10436. /**
  10437. * Check if the tech can support the given type. Also checks the
  10438. * Techs sourceHandlers.
  10439. *
  10440. * @param {string} type
  10441. * The mimetype to check.
  10442. *
  10443. * @return {string}
  10444. * 'probably', 'maybe', or '' (empty string)
  10445. */
  10446. _Tech.canPlayType = function (type) {
  10447. const handlers = _Tech.sourceHandlers || [];
  10448. let can;
  10449. for (let i = 0; i < handlers.length; i++) {
  10450. can = handlers[i].canPlayType(type);
  10451. if (can) {
  10452. return can;
  10453. }
  10454. }
  10455. return '';
  10456. };
  10457. /**
  10458. * Returns the first source handler that supports the source.
  10459. *
  10460. * TODO: Answer question: should 'probably' be prioritized over 'maybe'
  10461. *
  10462. * @param {Tech~SourceObject} source
  10463. * The source object
  10464. *
  10465. * @param {Object} options
  10466. * The options passed to the tech
  10467. *
  10468. * @return {SourceHandler|null}
  10469. * The first source handler that supports the source or null if
  10470. * no SourceHandler supports the source
  10471. */
  10472. _Tech.selectSourceHandler = function (source, options) {
  10473. const handlers = _Tech.sourceHandlers || [];
  10474. let can;
  10475. for (let i = 0; i < handlers.length; i++) {
  10476. can = handlers[i].canHandleSource(source, options);
  10477. if (can) {
  10478. return handlers[i];
  10479. }
  10480. }
  10481. return null;
  10482. };
  10483. /**
  10484. * Check if the tech can support the given source.
  10485. *
  10486. * @param {Tech~SourceObject} srcObj
  10487. * The source object
  10488. *
  10489. * @param {Object} options
  10490. * The options passed to the tech
  10491. *
  10492. * @return {string}
  10493. * 'probably', 'maybe', or '' (empty string)
  10494. */
  10495. _Tech.canPlaySource = function (srcObj, options) {
  10496. const sh = _Tech.selectSourceHandler(srcObj, options);
  10497. if (sh) {
  10498. return sh.canHandleSource(srcObj, options);
  10499. }
  10500. return '';
  10501. };
  10502. /**
  10503. * When using a source handler, prefer its implementation of
  10504. * any function normally provided by the tech.
  10505. */
  10506. const deferrable = ['seekable', 'seeking', 'duration'];
  10507. /**
  10508. * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable
  10509. * function if it exists, with a fallback to the Techs seekable function.
  10510. *
  10511. * @method _Tech.seekable
  10512. */
  10513. /**
  10514. * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration
  10515. * function if it exists, otherwise it will fallback to the techs duration function.
  10516. *
  10517. * @method _Tech.duration
  10518. */
  10519. deferrable.forEach(function (fnName) {
  10520. const originalFn = this[fnName];
  10521. if (typeof originalFn !== 'function') {
  10522. return;
  10523. }
  10524. this[fnName] = function () {
  10525. if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
  10526. return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
  10527. }
  10528. return originalFn.apply(this, arguments);
  10529. };
  10530. }, _Tech.prototype);
  10531. /**
  10532. * Create a function for setting the source using a source object
  10533. * and source handlers.
  10534. * Should never be called unless a source handler was found.
  10535. *
  10536. * @param {Tech~SourceObject} source
  10537. * A source object with src and type keys
  10538. */
  10539. _Tech.prototype.setSource = function (source) {
  10540. let sh = _Tech.selectSourceHandler(source, this.options_);
  10541. if (!sh) {
  10542. // Fall back to a native source handler when unsupported sources are
  10543. // deliberately set
  10544. if (_Tech.nativeSourceHandler) {
  10545. sh = _Tech.nativeSourceHandler;
  10546. } else {
  10547. log$1.error('No source handler found for the current source.');
  10548. }
  10549. }
  10550. // Dispose any existing source handler
  10551. this.disposeSourceHandler();
  10552. this.off('dispose', this.disposeSourceHandler_);
  10553. if (sh !== _Tech.nativeSourceHandler) {
  10554. this.currentSource_ = source;
  10555. }
  10556. this.sourceHandler_ = sh.handleSource(source, this, this.options_);
  10557. this.one('dispose', this.disposeSourceHandler_);
  10558. };
  10559. /**
  10560. * Clean up any existing SourceHandlers and listeners when the Tech is disposed.
  10561. *
  10562. * @listens Tech#dispose
  10563. */
  10564. _Tech.prototype.disposeSourceHandler = function () {
  10565. // if we have a source and get another one
  10566. // then we are loading something new
  10567. // than clear all of our current tracks
  10568. if (this.currentSource_) {
  10569. this.clearTracks(['audio', 'video']);
  10570. this.currentSource_ = null;
  10571. }
  10572. // always clean up auto-text tracks
  10573. this.cleanupAutoTextTracks();
  10574. if (this.sourceHandler_) {
  10575. if (this.sourceHandler_.dispose) {
  10576. this.sourceHandler_.dispose();
  10577. }
  10578. this.sourceHandler_ = null;
  10579. }
  10580. };
  10581. };
  10582. // The base Tech class needs to be registered as a Component. It is the only
  10583. // Tech that can be registered as a Component.
  10584. Component$1.registerComponent('Tech', Tech);
  10585. Tech.registerTech('Tech', Tech);
  10586. /**
  10587. * A list of techs that should be added to techOrder on Players
  10588. *
  10589. * @private
  10590. */
  10591. Tech.defaultTechOrder_ = [];
  10592. /**
  10593. * @file middleware.js
  10594. * @module middleware
  10595. */
  10596. const middlewares = {};
  10597. const middlewareInstances = {};
  10598. const TERMINATOR = {};
  10599. /**
  10600. * A middleware object is a plain JavaScript object that has methods that
  10601. * match the {@link Tech} methods found in the lists of allowed
  10602. * {@link module:middleware.allowedGetters|getters},
  10603. * {@link module:middleware.allowedSetters|setters}, and
  10604. * {@link module:middleware.allowedMediators|mediators}.
  10605. *
  10606. * @typedef {Object} MiddlewareObject
  10607. */
  10608. /**
  10609. * A middleware factory function that should return a
  10610. * {@link module:middleware~MiddlewareObject|MiddlewareObject}.
  10611. *
  10612. * This factory will be called for each player when needed, with the player
  10613. * passed in as an argument.
  10614. *
  10615. * @callback MiddlewareFactory
  10616. * @param { import('../player').default } player
  10617. * A Video.js player.
  10618. */
  10619. /**
  10620. * Define a middleware that the player should use by way of a factory function
  10621. * that returns a middleware object.
  10622. *
  10623. * @param {string} type
  10624. * The MIME type to match or `"*"` for all MIME types.
  10625. *
  10626. * @param {MiddlewareFactory} middleware
  10627. * A middleware factory function that will be executed for
  10628. * matching types.
  10629. */
  10630. function use(type, middleware) {
  10631. middlewares[type] = middlewares[type] || [];
  10632. middlewares[type].push(middleware);
  10633. }
  10634. /**
  10635. * Asynchronously sets a source using middleware by recursing through any
  10636. * matching middlewares and calling `setSource` on each, passing along the
  10637. * previous returned value each time.
  10638. *
  10639. * @param { import('../player').default } player
  10640. * A {@link Player} instance.
  10641. *
  10642. * @param {Tech~SourceObject} src
  10643. * A source object.
  10644. *
  10645. * @param {Function}
  10646. * The next middleware to run.
  10647. */
  10648. function setSource(player, src, next) {
  10649. player.setTimeout(() => setSourceHelper(src, middlewares[src.type], next, player), 1);
  10650. }
  10651. /**
  10652. * When the tech is set, passes the tech to each middleware's `setTech` method.
  10653. *
  10654. * @param {Object[]} middleware
  10655. * An array of middleware instances.
  10656. *
  10657. * @param { import('../tech/tech').default } tech
  10658. * A Video.js tech.
  10659. */
  10660. function setTech(middleware, tech) {
  10661. middleware.forEach(mw => mw.setTech && mw.setTech(tech));
  10662. }
  10663. /**
  10664. * Calls a getter on the tech first, through each middleware
  10665. * from right to left to the player.
  10666. *
  10667. * @param {Object[]} middleware
  10668. * An array of middleware instances.
  10669. *
  10670. * @param { import('../tech/tech').default } tech
  10671. * The current tech.
  10672. *
  10673. * @param {string} method
  10674. * A method name.
  10675. *
  10676. * @return {*}
  10677. * The final value from the tech after middleware has intercepted it.
  10678. */
  10679. function get(middleware, tech, method) {
  10680. return middleware.reduceRight(middlewareIterator(method), tech[method]());
  10681. }
  10682. /**
  10683. * Takes the argument given to the player and calls the setter method on each
  10684. * middleware from left to right to the tech.
  10685. *
  10686. * @param {Object[]} middleware
  10687. * An array of middleware instances.
  10688. *
  10689. * @param { import('../tech/tech').default } tech
  10690. * The current tech.
  10691. *
  10692. * @param {string} method
  10693. * A method name.
  10694. *
  10695. * @param {*} arg
  10696. * The value to set on the tech.
  10697. *
  10698. * @return {*}
  10699. * The return value of the `method` of the `tech`.
  10700. */
  10701. function set(middleware, tech, method, arg) {
  10702. return tech[method](middleware.reduce(middlewareIterator(method), arg));
  10703. }
  10704. /**
  10705. * Takes the argument given to the player and calls the `call` version of the
  10706. * method on each middleware from left to right.
  10707. *
  10708. * Then, call the passed in method on the tech and return the result unchanged
  10709. * back to the player, through middleware, this time from right to left.
  10710. *
  10711. * @param {Object[]} middleware
  10712. * An array of middleware instances.
  10713. *
  10714. * @param { import('../tech/tech').default } tech
  10715. * The current tech.
  10716. *
  10717. * @param {string} method
  10718. * A method name.
  10719. *
  10720. * @param {*} arg
  10721. * The value to set on the tech.
  10722. *
  10723. * @return {*}
  10724. * The return value of the `method` of the `tech`, regardless of the
  10725. * return values of middlewares.
  10726. */
  10727. function mediate(middleware, tech, method, arg = null) {
  10728. const callMethod = 'call' + toTitleCase$1(method);
  10729. const middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
  10730. const terminated = middlewareValue === TERMINATOR;
  10731. // deprecated. The `null` return value should instead return TERMINATOR to
  10732. // prevent confusion if a techs method actually returns null.
  10733. const returnValue = terminated ? null : tech[method](middlewareValue);
  10734. executeRight(middleware, method, returnValue, terminated);
  10735. return returnValue;
  10736. }
  10737. /**
  10738. * Enumeration of allowed getters where the keys are method names.
  10739. *
  10740. * @type {Object}
  10741. */
  10742. const allowedGetters = {
  10743. buffered: 1,
  10744. currentTime: 1,
  10745. duration: 1,
  10746. muted: 1,
  10747. played: 1,
  10748. paused: 1,
  10749. seekable: 1,
  10750. volume: 1,
  10751. ended: 1
  10752. };
  10753. /**
  10754. * Enumeration of allowed setters where the keys are method names.
  10755. *
  10756. * @type {Object}
  10757. */
  10758. const allowedSetters = {
  10759. setCurrentTime: 1,
  10760. setMuted: 1,
  10761. setVolume: 1
  10762. };
  10763. /**
  10764. * Enumeration of allowed mediators where the keys are method names.
  10765. *
  10766. * @type {Object}
  10767. */
  10768. const allowedMediators = {
  10769. play: 1,
  10770. pause: 1
  10771. };
  10772. function middlewareIterator(method) {
  10773. return (value, mw) => {
  10774. // if the previous middleware terminated, pass along the termination
  10775. if (value === TERMINATOR) {
  10776. return TERMINATOR;
  10777. }
  10778. if (mw[method]) {
  10779. return mw[method](value);
  10780. }
  10781. return value;
  10782. };
  10783. }
  10784. function executeRight(mws, method, value, terminated) {
  10785. for (let i = mws.length - 1; i >= 0; i--) {
  10786. const mw = mws[i];
  10787. if (mw[method]) {
  10788. mw[method](terminated, value);
  10789. }
  10790. }
  10791. }
  10792. /**
  10793. * Clear the middleware cache for a player.
  10794. *
  10795. * @param { import('../player').default } player
  10796. * A {@link Player} instance.
  10797. */
  10798. function clearCacheForPlayer(player) {
  10799. middlewareInstances[player.id()] = null;
  10800. }
  10801. /**
  10802. * {
  10803. * [playerId]: [[mwFactory, mwInstance], ...]
  10804. * }
  10805. *
  10806. * @private
  10807. */
  10808. function getOrCreateFactory(player, mwFactory) {
  10809. const mws = middlewareInstances[player.id()];
  10810. let mw = null;
  10811. if (mws === undefined || mws === null) {
  10812. mw = mwFactory(player);
  10813. middlewareInstances[player.id()] = [[mwFactory, mw]];
  10814. return mw;
  10815. }
  10816. for (let i = 0; i < mws.length; i++) {
  10817. const [mwf, mwi] = mws[i];
  10818. if (mwf !== mwFactory) {
  10819. continue;
  10820. }
  10821. mw = mwi;
  10822. }
  10823. if (mw === null) {
  10824. mw = mwFactory(player);
  10825. mws.push([mwFactory, mw]);
  10826. }
  10827. return mw;
  10828. }
  10829. function setSourceHelper(src = {}, middleware = [], next, player, acc = [], lastRun = false) {
  10830. const [mwFactory, ...mwrest] = middleware;
  10831. // if mwFactory is a string, then we're at a fork in the road
  10832. if (typeof mwFactory === 'string') {
  10833. setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun);
  10834. // if we have an mwFactory, call it with the player to get the mw,
  10835. // then call the mw's setSource method
  10836. } else if (mwFactory) {
  10837. const mw = getOrCreateFactory(player, mwFactory);
  10838. // if setSource isn't present, implicitly select this middleware
  10839. if (!mw.setSource) {
  10840. acc.push(mw);
  10841. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  10842. }
  10843. mw.setSource(Object.assign({}, src), function (err, _src) {
  10844. // something happened, try the next middleware on the current level
  10845. // make sure to use the old src
  10846. if (err) {
  10847. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  10848. }
  10849. // we've succeeded, now we need to go deeper
  10850. acc.push(mw);
  10851. // if it's the same type, continue down the current chain
  10852. // otherwise, we want to go down the new chain
  10853. setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
  10854. });
  10855. } else if (mwrest.length) {
  10856. setSourceHelper(src, mwrest, next, player, acc, lastRun);
  10857. } else if (lastRun) {
  10858. next(src, acc);
  10859. } else {
  10860. setSourceHelper(src, middlewares['*'], next, player, acc, true);
  10861. }
  10862. }
  10863. /**
  10864. * Mimetypes
  10865. *
  10866. * @see https://www.iana.org/assignments/media-types/media-types.xhtml
  10867. * @typedef Mimetypes~Kind
  10868. * @enum
  10869. */
  10870. const MimetypesKind = {
  10871. opus: 'video/ogg',
  10872. ogv: 'video/ogg',
  10873. mp4: 'video/mp4',
  10874. mov: 'video/mp4',
  10875. m4v: 'video/mp4',
  10876. mkv: 'video/x-matroska',
  10877. m4a: 'audio/mp4',
  10878. mp3: 'audio/mpeg',
  10879. aac: 'audio/aac',
  10880. caf: 'audio/x-caf',
  10881. flac: 'audio/flac',
  10882. oga: 'audio/ogg',
  10883. wav: 'audio/wav',
  10884. m3u8: 'application/x-mpegURL',
  10885. mpd: 'application/dash+xml',
  10886. jpg: 'image/jpeg',
  10887. jpeg: 'image/jpeg',
  10888. gif: 'image/gif',
  10889. png: 'image/png',
  10890. svg: 'image/svg+xml',
  10891. webp: 'image/webp'
  10892. };
  10893. /**
  10894. * Get the mimetype of a given src url if possible
  10895. *
  10896. * @param {string} src
  10897. * The url to the src
  10898. *
  10899. * @return {string}
  10900. * return the mimetype if it was known or empty string otherwise
  10901. */
  10902. const getMimetype = function (src = '') {
  10903. const ext = getFileExtension(src);
  10904. const mimetype = MimetypesKind[ext.toLowerCase()];
  10905. return mimetype || '';
  10906. };
  10907. /**
  10908. * Find the mime type of a given source string if possible. Uses the player
  10909. * source cache.
  10910. *
  10911. * @param { import('../player').default } player
  10912. * The player object
  10913. *
  10914. * @param {string} src
  10915. * The source string
  10916. *
  10917. * @return {string}
  10918. * The type that was found
  10919. */
  10920. const findMimetype = (player, src) => {
  10921. if (!src) {
  10922. return '';
  10923. }
  10924. // 1. check for the type in the `source` cache
  10925. if (player.cache_.source.src === src && player.cache_.source.type) {
  10926. return player.cache_.source.type;
  10927. }
  10928. // 2. see if we have this source in our `currentSources` cache
  10929. const matchingSources = player.cache_.sources.filter(s => s.src === src);
  10930. if (matchingSources.length) {
  10931. return matchingSources[0].type;
  10932. }
  10933. // 3. look for the src url in source elements and use the type there
  10934. const sources = player.$$('source');
  10935. for (let i = 0; i < sources.length; i++) {
  10936. const s = sources[i];
  10937. if (s.type && s.src && s.src === src) {
  10938. return s.type;
  10939. }
  10940. }
  10941. // 4. finally fallback to our list of mime types based on src url extension
  10942. return getMimetype(src);
  10943. };
  10944. /**
  10945. * @module filter-source
  10946. */
  10947. /**
  10948. * Filter out single bad source objects or multiple source objects in an
  10949. * array. Also flattens nested source object arrays into a 1 dimensional
  10950. * array of source objects.
  10951. *
  10952. * @param {Tech~SourceObject|Tech~SourceObject[]} src
  10953. * The src object to filter
  10954. *
  10955. * @return {Tech~SourceObject[]}
  10956. * An array of sourceobjects containing only valid sources
  10957. *
  10958. * @private
  10959. */
  10960. const filterSource = function (src) {
  10961. // traverse array
  10962. if (Array.isArray(src)) {
  10963. let newsrc = [];
  10964. src.forEach(function (srcobj) {
  10965. srcobj = filterSource(srcobj);
  10966. if (Array.isArray(srcobj)) {
  10967. newsrc = newsrc.concat(srcobj);
  10968. } else if (isObject$1(srcobj)) {
  10969. newsrc.push(srcobj);
  10970. }
  10971. });
  10972. src = newsrc;
  10973. } else if (typeof src === 'string' && src.trim()) {
  10974. // convert string into object
  10975. src = [fixSource({
  10976. src
  10977. })];
  10978. } else if (isObject$1(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
  10979. // src is already valid
  10980. src = [fixSource(src)];
  10981. } else {
  10982. // invalid source, turn it into an empty array
  10983. src = [];
  10984. }
  10985. return src;
  10986. };
  10987. /**
  10988. * Checks src mimetype, adding it when possible
  10989. *
  10990. * @param {Tech~SourceObject} src
  10991. * The src object to check
  10992. * @return {Tech~SourceObject}
  10993. * src Object with known type
  10994. */
  10995. function fixSource(src) {
  10996. if (!src.type) {
  10997. const mimetype = getMimetype(src.src);
  10998. if (mimetype) {
  10999. src.type = mimetype;
  11000. }
  11001. }
  11002. return src;
  11003. }
  11004. /**
  11005. * @file loader.js
  11006. */
  11007. /**
  11008. * The `MediaLoader` is the `Component` that decides which playback technology to load
  11009. * when a player is initialized.
  11010. *
  11011. * @extends Component
  11012. */
  11013. class MediaLoader extends Component$1 {
  11014. /**
  11015. * Create an instance of this class.
  11016. *
  11017. * @param { import('../player').default } player
  11018. * The `Player` that this class should attach to.
  11019. *
  11020. * @param {Object} [options]
  11021. * The key/value store of player options.
  11022. *
  11023. * @param {Function} [ready]
  11024. * The function that is run when this component is ready.
  11025. */
  11026. constructor(player, options, ready) {
  11027. // MediaLoader has no element
  11028. const options_ = merge$2({
  11029. createEl: false
  11030. }, options);
  11031. super(player, options_, ready);
  11032. // If there are no sources when the player is initialized,
  11033. // load the first supported playback technology.
  11034. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
  11035. for (let i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
  11036. const techName = toTitleCase$1(j[i]);
  11037. let tech = Tech.getTech(techName);
  11038. // Support old behavior of techs being registered as components.
  11039. // Remove once that deprecated behavior is removed.
  11040. if (!techName) {
  11041. tech = Component$1.getComponent(techName);
  11042. }
  11043. // Check if the browser supports this technology
  11044. if (tech && tech.isSupported()) {
  11045. player.loadTech_(techName);
  11046. break;
  11047. }
  11048. }
  11049. } else {
  11050. // Loop through playback technologies (e.g. HTML5) and check for support.
  11051. // Then load the best source.
  11052. // A few assumptions here:
  11053. // All playback technologies respect preload false.
  11054. player.src(options.playerOptions.sources);
  11055. }
  11056. }
  11057. }
  11058. Component$1.registerComponent('MediaLoader', MediaLoader);
  11059. /**
  11060. * @file clickable-component.js
  11061. */
  11062. /**
  11063. * Component which is clickable or keyboard actionable, but is not a
  11064. * native HTML button.
  11065. *
  11066. * @extends Component
  11067. */
  11068. class ClickableComponent extends Component$1 {
  11069. /**
  11070. * Creates an instance of this class.
  11071. *
  11072. * @param { import('./player').default } player
  11073. * The `Player` that this class should be attached to.
  11074. *
  11075. * @param {Object} [options]
  11076. * The key/value store of component options.
  11077. *
  11078. * @param {function} [options.clickHandler]
  11079. * The function to call when the button is clicked / activated
  11080. *
  11081. * @param {string} [options.controlText]
  11082. * The text to set on the button
  11083. *
  11084. * @param {string} [options.className]
  11085. * A class or space separated list of classes to add the component
  11086. *
  11087. */
  11088. constructor(player, options) {
  11089. super(player, options);
  11090. if (this.options_.controlText) {
  11091. this.controlText(this.options_.controlText);
  11092. }
  11093. this.handleMouseOver_ = e => this.handleMouseOver(e);
  11094. this.handleMouseOut_ = e => this.handleMouseOut(e);
  11095. this.handleClick_ = e => this.handleClick(e);
  11096. this.handleKeyDown_ = e => this.handleKeyDown(e);
  11097. this.emitTapEvents();
  11098. this.enable();
  11099. }
  11100. /**
  11101. * Create the `ClickableComponent`s DOM element.
  11102. *
  11103. * @param {string} [tag=div]
  11104. * The element's node type.
  11105. *
  11106. * @param {Object} [props={}]
  11107. * An object of properties that should be set on the element.
  11108. *
  11109. * @param {Object} [attributes={}]
  11110. * An object of attributes that should be set on the element.
  11111. *
  11112. * @return {Element}
  11113. * The element that gets created.
  11114. */
  11115. createEl(tag = 'div', props = {}, attributes = {}) {
  11116. props = Object.assign({
  11117. className: this.buildCSSClass(),
  11118. tabIndex: 0
  11119. }, props);
  11120. if (tag === 'button') {
  11121. log$1.error(`Creating a ClickableComponent with an HTML element of ${tag} is not supported; use a Button instead.`);
  11122. }
  11123. // Add ARIA attributes for clickable element which is not a native HTML button
  11124. attributes = Object.assign({
  11125. role: 'button'
  11126. }, attributes);
  11127. this.tabIndex_ = props.tabIndex;
  11128. const el = createEl(tag, props, attributes);
  11129. el.appendChild(createEl('span', {
  11130. className: 'vjs-icon-placeholder'
  11131. }, {
  11132. 'aria-hidden': true
  11133. }));
  11134. this.createControlTextEl(el);
  11135. return el;
  11136. }
  11137. dispose() {
  11138. // remove controlTextEl_ on dispose
  11139. this.controlTextEl_ = null;
  11140. super.dispose();
  11141. }
  11142. /**
  11143. * Create a control text element on this `ClickableComponent`
  11144. *
  11145. * @param {Element} [el]
  11146. * Parent element for the control text.
  11147. *
  11148. * @return {Element}
  11149. * The control text element that gets created.
  11150. */
  11151. createControlTextEl(el) {
  11152. this.controlTextEl_ = createEl('span', {
  11153. className: 'vjs-control-text'
  11154. }, {
  11155. // let the screen reader user know that the text of the element may change
  11156. 'aria-live': 'polite'
  11157. });
  11158. if (el) {
  11159. el.appendChild(this.controlTextEl_);
  11160. }
  11161. this.controlText(this.controlText_, el);
  11162. return this.controlTextEl_;
  11163. }
  11164. /**
  11165. * Get or set the localize text to use for the controls on the `ClickableComponent`.
  11166. *
  11167. * @param {string} [text]
  11168. * Control text for element.
  11169. *
  11170. * @param {Element} [el=this.el()]
  11171. * Element to set the title on.
  11172. *
  11173. * @return {string}
  11174. * - The control text when getting
  11175. */
  11176. controlText(text, el = this.el()) {
  11177. if (text === undefined) {
  11178. return this.controlText_ || 'Need Text';
  11179. }
  11180. const localizedText = this.localize(text);
  11181. /** @protected */
  11182. this.controlText_ = text;
  11183. textContent(this.controlTextEl_, localizedText);
  11184. if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {
  11185. // Set title attribute if only an icon is shown
  11186. el.setAttribute('title', localizedText);
  11187. }
  11188. }
  11189. /**
  11190. * Builds the default DOM `className`.
  11191. *
  11192. * @return {string}
  11193. * The DOM `className` for this object.
  11194. */
  11195. buildCSSClass() {
  11196. return `vjs-control vjs-button ${super.buildCSSClass()}`;
  11197. }
  11198. /**
  11199. * Enable this `ClickableComponent`
  11200. */
  11201. enable() {
  11202. if (!this.enabled_) {
  11203. this.enabled_ = true;
  11204. this.removeClass('vjs-disabled');
  11205. this.el_.setAttribute('aria-disabled', 'false');
  11206. if (typeof this.tabIndex_ !== 'undefined') {
  11207. this.el_.setAttribute('tabIndex', this.tabIndex_);
  11208. }
  11209. this.on(['tap', 'click'], this.handleClick_);
  11210. this.on('keydown', this.handleKeyDown_);
  11211. }
  11212. }
  11213. /**
  11214. * Disable this `ClickableComponent`
  11215. */
  11216. disable() {
  11217. this.enabled_ = false;
  11218. this.addClass('vjs-disabled');
  11219. this.el_.setAttribute('aria-disabled', 'true');
  11220. if (typeof this.tabIndex_ !== 'undefined') {
  11221. this.el_.removeAttribute('tabIndex');
  11222. }
  11223. this.off('mouseover', this.handleMouseOver_);
  11224. this.off('mouseout', this.handleMouseOut_);
  11225. this.off(['tap', 'click'], this.handleClick_);
  11226. this.off('keydown', this.handleKeyDown_);
  11227. }
  11228. /**
  11229. * Handles language change in ClickableComponent for the player in components
  11230. *
  11231. *
  11232. */
  11233. handleLanguagechange() {
  11234. this.controlText(this.controlText_);
  11235. }
  11236. /**
  11237. * Event handler that is called when a `ClickableComponent` receives a
  11238. * `click` or `tap` event.
  11239. *
  11240. * @param {Event} event
  11241. * The `tap` or `click` event that caused this function to be called.
  11242. *
  11243. * @listens tap
  11244. * @listens click
  11245. * @abstract
  11246. */
  11247. handleClick(event) {
  11248. if (this.options_.clickHandler) {
  11249. this.options_.clickHandler.call(this, arguments);
  11250. }
  11251. }
  11252. /**
  11253. * Event handler that is called when a `ClickableComponent` receives a
  11254. * `keydown` event.
  11255. *
  11256. * By default, if the key is Space or Enter, it will trigger a `click` event.
  11257. *
  11258. * @param {Event} event
  11259. * The `keydown` event that caused this function to be called.
  11260. *
  11261. * @listens keydown
  11262. */
  11263. handleKeyDown(event) {
  11264. // Support Space or Enter key operation to fire a click event. Also,
  11265. // prevent the event from propagating through the DOM and triggering
  11266. // Player hotkeys.
  11267. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  11268. event.preventDefault();
  11269. event.stopPropagation();
  11270. this.trigger('click');
  11271. } else {
  11272. // Pass keypress handling up for unsupported keys
  11273. super.handleKeyDown(event);
  11274. }
  11275. }
  11276. }
  11277. Component$1.registerComponent('ClickableComponent', ClickableComponent);
  11278. /**
  11279. * @file poster-image.js
  11280. */
  11281. /**
  11282. * A `ClickableComponent` that handles showing the poster image for the player.
  11283. *
  11284. * @extends ClickableComponent
  11285. */
  11286. class PosterImage extends ClickableComponent {
  11287. /**
  11288. * Create an instance of this class.
  11289. *
  11290. * @param { import('./player').default } player
  11291. * The `Player` that this class should attach to.
  11292. *
  11293. * @param {Object} [options]
  11294. * The key/value store of player options.
  11295. */
  11296. constructor(player, options) {
  11297. super(player, options);
  11298. this.update();
  11299. this.update_ = e => this.update(e);
  11300. player.on('posterchange', this.update_);
  11301. }
  11302. /**
  11303. * Clean up and dispose of the `PosterImage`.
  11304. */
  11305. dispose() {
  11306. this.player().off('posterchange', this.update_);
  11307. super.dispose();
  11308. }
  11309. /**
  11310. * Create the `PosterImage`s DOM element.
  11311. *
  11312. * @return {Element}
  11313. * The element that gets created.
  11314. */
  11315. createEl() {
  11316. // The el is an empty div to keep position in the DOM
  11317. // A picture and img el will be inserted when a source is set
  11318. return createEl('div', {
  11319. className: 'vjs-poster'
  11320. });
  11321. }
  11322. /**
  11323. * Get or set the `PosterImage`'s crossOrigin option.
  11324. *
  11325. * @param {string|null} [value]
  11326. * The value to set the crossOrigin to. If an argument is
  11327. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  11328. *
  11329. * @return {string|null}
  11330. * - The current crossOrigin value of the `Player` when getting.
  11331. * - undefined when setting
  11332. */
  11333. crossOrigin(value) {
  11334. // `null` can be set to unset a value
  11335. if (typeof value === 'undefined') {
  11336. if (this.$('img')) {
  11337. // If the poster's element exists, give its value
  11338. return this.$('img').crossOrigin;
  11339. } else if (this.player_.tech_ && this.player_.tech_.isReady_) {
  11340. // If not but the tech is ready, query the tech
  11341. return this.player_.crossOrigin();
  11342. }
  11343. // Otherwise check options as the poster is usually set before the state of crossorigin
  11344. // can be retrieved by the getter
  11345. return this.player_.options_.crossOrigin || this.player_.options_.crossorigin || null;
  11346. }
  11347. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  11348. this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  11349. return;
  11350. }
  11351. if (this.$('img')) {
  11352. this.$('img').crossOrigin = value;
  11353. }
  11354. return;
  11355. }
  11356. /**
  11357. * An {@link EventTarget~EventListener} for {@link Player#posterchange} events.
  11358. *
  11359. * @listens Player#posterchange
  11360. *
  11361. * @param {Event} [event]
  11362. * The `Player#posterchange` event that triggered this function.
  11363. */
  11364. update(event) {
  11365. const url = this.player().poster();
  11366. this.setSrc(url);
  11367. // If there's no poster source we should display:none on this component
  11368. // so it's not still clickable or right-clickable
  11369. if (url) {
  11370. this.show();
  11371. } else {
  11372. this.hide();
  11373. }
  11374. }
  11375. /**
  11376. * Set the source of the `PosterImage` depending on the display method. (Re)creates
  11377. * the inner picture and img elementss when needed.
  11378. *
  11379. * @param {string} [url]
  11380. * The URL to the source for the `PosterImage`. If not specified or falsy,
  11381. * any source and ant inner picture/img are removed.
  11382. */
  11383. setSrc(url) {
  11384. if (!url) {
  11385. this.el_.textContent = '';
  11386. return;
  11387. }
  11388. if (!this.$('img')) {
  11389. this.el_.appendChild(createEl('picture', {
  11390. className: 'vjs-poster',
  11391. // Don't want poster to be tabbable.
  11392. tabIndex: -1
  11393. }, {}, createEl('img', {
  11394. loading: 'lazy',
  11395. crossOrigin: this.crossOrigin()
  11396. }, {
  11397. alt: ''
  11398. })));
  11399. }
  11400. this.$('img').src = url;
  11401. }
  11402. /**
  11403. * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See
  11404. * {@link ClickableComponent#handleClick} for instances where this will be triggered.
  11405. *
  11406. * @listens tap
  11407. * @listens click
  11408. * @listens keydown
  11409. *
  11410. * @param {Event} event
  11411. + The `click`, `tap` or `keydown` event that caused this function to be called.
  11412. */
  11413. handleClick(event) {
  11414. // We don't want a click to trigger playback when controls are disabled
  11415. if (!this.player_.controls()) {
  11416. return;
  11417. }
  11418. if (this.player_.tech(true)) {
  11419. this.player_.tech(true).focus();
  11420. }
  11421. if (this.player_.paused()) {
  11422. silencePromise(this.player_.play());
  11423. } else {
  11424. this.player_.pause();
  11425. }
  11426. }
  11427. }
  11428. /**
  11429. * Get or set the `PosterImage`'s crossorigin option. For the HTML5 player, this
  11430. * sets the `crossOrigin` property on the `<img>` tag to control the CORS
  11431. * behavior.
  11432. *
  11433. * @param {string|null} [value]
  11434. * The value to set the `PosterImages`'s crossorigin to. If an argument is
  11435. * given, must be one of `anonymous` or `use-credentials`.
  11436. *
  11437. * @return {string|null|undefined}
  11438. * - The current crossorigin value of the `Player` when getting.
  11439. * - undefined when setting
  11440. */
  11441. PosterImage.prototype.crossorigin = PosterImage.prototype.crossOrigin;
  11442. Component$1.registerComponent('PosterImage', PosterImage);
  11443. /**
  11444. * @file text-track-display.js
  11445. */
  11446. const darkGray = '#222';
  11447. const lightGray = '#ccc';
  11448. const fontMap = {
  11449. monospace: 'monospace',
  11450. sansSerif: 'sans-serif',
  11451. serif: 'serif',
  11452. monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
  11453. monospaceSerif: '"Courier New", monospace',
  11454. proportionalSansSerif: 'sans-serif',
  11455. proportionalSerif: 'serif',
  11456. casual: '"Comic Sans MS", Impact, fantasy',
  11457. script: '"Monotype Corsiva", cursive',
  11458. smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
  11459. };
  11460. /**
  11461. * Construct an rgba color from a given hex color code.
  11462. *
  11463. * @param {number} color
  11464. * Hex number for color, like #f0e or #f604e2.
  11465. *
  11466. * @param {number} opacity
  11467. * Value for opacity, 0.0 - 1.0.
  11468. *
  11469. * @return {string}
  11470. * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
  11471. */
  11472. function constructColor(color, opacity) {
  11473. let hex;
  11474. if (color.length === 4) {
  11475. // color looks like "#f0e"
  11476. hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
  11477. } else if (color.length === 7) {
  11478. // color looks like "#f604e2"
  11479. hex = color.slice(1);
  11480. } else {
  11481. throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
  11482. }
  11483. return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';
  11484. }
  11485. /**
  11486. * Try to update the style of a DOM element. Some style changes will throw an error,
  11487. * particularly in IE8. Those should be noops.
  11488. *
  11489. * @param {Element} el
  11490. * The DOM element to be styled.
  11491. *
  11492. * @param {string} style
  11493. * The CSS property on the element that should be styled.
  11494. *
  11495. * @param {string} rule
  11496. * The style rule that should be applied to the property.
  11497. *
  11498. * @private
  11499. */
  11500. function tryUpdateStyle(el, style, rule) {
  11501. try {
  11502. el.style[style] = rule;
  11503. } catch (e) {
  11504. // Satisfies linter.
  11505. return;
  11506. }
  11507. }
  11508. /**
  11509. * The component for displaying text track cues.
  11510. *
  11511. * @extends Component
  11512. */
  11513. class TextTrackDisplay extends Component$1 {
  11514. /**
  11515. * Creates an instance of this class.
  11516. *
  11517. * @param { import('../player').default } player
  11518. * The `Player` that this class should be attached to.
  11519. *
  11520. * @param {Object} [options]
  11521. * The key/value store of player options.
  11522. *
  11523. * @param {Function} [ready]
  11524. * The function to call when `TextTrackDisplay` is ready.
  11525. */
  11526. constructor(player, options, ready) {
  11527. super(player, options, ready);
  11528. const updateDisplayHandler = e => this.updateDisplay(e);
  11529. player.on('loadstart', e => this.toggleDisplay(e));
  11530. player.on('texttrackchange', updateDisplayHandler);
  11531. player.on('loadedmetadata', e => this.preselectTrack(e));
  11532. // This used to be called during player init, but was causing an error
  11533. // if a track should show by default and the display hadn't loaded yet.
  11534. // Should probably be moved to an external track loader when we support
  11535. // tracks that don't need a display.
  11536. player.ready(bind_(this, function () {
  11537. if (player.tech_ && player.tech_.featuresNativeTextTracks) {
  11538. this.hide();
  11539. return;
  11540. }
  11541. player.on('fullscreenchange', updateDisplayHandler);
  11542. player.on('playerresize', updateDisplayHandler);
  11543. const screenOrientation = window.screen.orientation || window;
  11544. const changeOrientationEvent = window.screen.orientation ? 'change' : 'orientationchange';
  11545. screenOrientation.addEventListener(changeOrientationEvent, updateDisplayHandler);
  11546. player.on('dispose', () => screenOrientation.removeEventListener(changeOrientationEvent, updateDisplayHandler));
  11547. const tracks = this.options_.playerOptions.tracks || [];
  11548. for (let i = 0; i < tracks.length; i++) {
  11549. this.player_.addRemoteTextTrack(tracks[i], true);
  11550. }
  11551. this.preselectTrack();
  11552. }));
  11553. }
  11554. /**
  11555. * Preselect a track following this precedence:
  11556. * - matches the previously selected {@link TextTrack}'s language and kind
  11557. * - matches the previously selected {@link TextTrack}'s language only
  11558. * - is the first default captions track
  11559. * - is the first default descriptions track
  11560. *
  11561. * @listens Player#loadstart
  11562. */
  11563. preselectTrack() {
  11564. const modes = {
  11565. captions: 1,
  11566. subtitles: 1
  11567. };
  11568. const trackList = this.player_.textTracks();
  11569. const userPref = this.player_.cache_.selectedLanguage;
  11570. let firstDesc;
  11571. let firstCaptions;
  11572. let preferredTrack;
  11573. for (let i = 0; i < trackList.length; i++) {
  11574. const track = trackList[i];
  11575. if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {
  11576. // Always choose the track that matches both language and kind
  11577. if (track.kind === userPref.kind) {
  11578. preferredTrack = track;
  11579. // or choose the first track that matches language
  11580. } else if (!preferredTrack) {
  11581. preferredTrack = track;
  11582. }
  11583. // clear everything if offTextTrackMenuItem was clicked
  11584. } else if (userPref && !userPref.enabled) {
  11585. preferredTrack = null;
  11586. firstDesc = null;
  11587. firstCaptions = null;
  11588. } else if (track.default) {
  11589. if (track.kind === 'descriptions' && !firstDesc) {
  11590. firstDesc = track;
  11591. } else if (track.kind in modes && !firstCaptions) {
  11592. firstCaptions = track;
  11593. }
  11594. }
  11595. }
  11596. // The preferredTrack matches the user preference and takes
  11597. // precedence over all the other tracks.
  11598. // So, display the preferredTrack before the first default track
  11599. // and the subtitles/captions track before the descriptions track
  11600. if (preferredTrack) {
  11601. preferredTrack.mode = 'showing';
  11602. } else if (firstCaptions) {
  11603. firstCaptions.mode = 'showing';
  11604. } else if (firstDesc) {
  11605. firstDesc.mode = 'showing';
  11606. }
  11607. }
  11608. /**
  11609. * Turn display of {@link TextTrack}'s from the current state into the other state.
  11610. * There are only two states:
  11611. * - 'shown'
  11612. * - 'hidden'
  11613. *
  11614. * @listens Player#loadstart
  11615. */
  11616. toggleDisplay() {
  11617. if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
  11618. this.hide();
  11619. } else {
  11620. this.show();
  11621. }
  11622. }
  11623. /**
  11624. * Create the {@link Component}'s DOM element.
  11625. *
  11626. * @return {Element}
  11627. * The element that was created.
  11628. */
  11629. createEl() {
  11630. return super.createEl('div', {
  11631. className: 'vjs-text-track-display'
  11632. }, {
  11633. 'translate': 'yes',
  11634. 'aria-live': 'off',
  11635. 'aria-atomic': 'true'
  11636. });
  11637. }
  11638. /**
  11639. * Clear all displayed {@link TextTrack}s.
  11640. */
  11641. clearDisplay() {
  11642. if (typeof window.WebVTT === 'function') {
  11643. window.WebVTT.processCues(window, [], this.el_);
  11644. }
  11645. }
  11646. /**
  11647. * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or
  11648. * a {@link Player#fullscreenchange} is fired.
  11649. *
  11650. * @listens Player#texttrackchange
  11651. * @listens Player#fullscreenchange
  11652. */
  11653. updateDisplay() {
  11654. const tracks = this.player_.textTracks();
  11655. const allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;
  11656. this.clearDisplay();
  11657. if (allowMultipleShowingTracks) {
  11658. const showingTracks = [];
  11659. for (let i = 0; i < tracks.length; ++i) {
  11660. const track = tracks[i];
  11661. if (track.mode !== 'showing') {
  11662. continue;
  11663. }
  11664. showingTracks.push(track);
  11665. }
  11666. this.updateForTrack(showingTracks);
  11667. return;
  11668. }
  11669. // Track display prioritization model: if multiple tracks are 'showing',
  11670. // display the first 'subtitles' or 'captions' track which is 'showing',
  11671. // otherwise display the first 'descriptions' track which is 'showing'
  11672. let descriptionsTrack = null;
  11673. let captionsSubtitlesTrack = null;
  11674. let i = tracks.length;
  11675. while (i--) {
  11676. const track = tracks[i];
  11677. if (track.mode === 'showing') {
  11678. if (track.kind === 'descriptions') {
  11679. descriptionsTrack = track;
  11680. } else {
  11681. captionsSubtitlesTrack = track;
  11682. }
  11683. }
  11684. }
  11685. if (captionsSubtitlesTrack) {
  11686. if (this.getAttribute('aria-live') !== 'off') {
  11687. this.setAttribute('aria-live', 'off');
  11688. }
  11689. this.updateForTrack(captionsSubtitlesTrack);
  11690. } else if (descriptionsTrack) {
  11691. if (this.getAttribute('aria-live') !== 'assertive') {
  11692. this.setAttribute('aria-live', 'assertive');
  11693. }
  11694. this.updateForTrack(descriptionsTrack);
  11695. }
  11696. }
  11697. /**
  11698. * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}.
  11699. *
  11700. * @param {TextTrack} track
  11701. * Text track object containing active cues to style.
  11702. */
  11703. updateDisplayState(track) {
  11704. const overrides = this.player_.textTrackSettings.getValues();
  11705. const cues = track.activeCues;
  11706. let i = cues.length;
  11707. while (i--) {
  11708. const cue = cues[i];
  11709. if (!cue) {
  11710. continue;
  11711. }
  11712. const cueDiv = cue.displayState;
  11713. if (overrides.color) {
  11714. cueDiv.firstChild.style.color = overrides.color;
  11715. }
  11716. if (overrides.textOpacity) {
  11717. tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
  11718. }
  11719. if (overrides.backgroundColor) {
  11720. cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
  11721. }
  11722. if (overrides.backgroundOpacity) {
  11723. tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
  11724. }
  11725. if (overrides.windowColor) {
  11726. if (overrides.windowOpacity) {
  11727. tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
  11728. } else {
  11729. cueDiv.style.backgroundColor = overrides.windowColor;
  11730. }
  11731. }
  11732. if (overrides.edgeStyle) {
  11733. if (overrides.edgeStyle === 'dropshadow') {
  11734. cueDiv.firstChild.style.textShadow = `2px 2px 3px ${darkGray}, 2px 2px 4px ${darkGray}, 2px 2px 5px ${darkGray}`;
  11735. } else if (overrides.edgeStyle === 'raised') {
  11736. cueDiv.firstChild.style.textShadow = `1px 1px ${darkGray}, 2px 2px ${darkGray}, 3px 3px ${darkGray}`;
  11737. } else if (overrides.edgeStyle === 'depressed') {
  11738. cueDiv.firstChild.style.textShadow = `1px 1px ${lightGray}, 0 1px ${lightGray}, -1px -1px ${darkGray}, 0 -1px ${darkGray}`;
  11739. } else if (overrides.edgeStyle === 'uniform') {
  11740. cueDiv.firstChild.style.textShadow = `0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}`;
  11741. }
  11742. }
  11743. if (overrides.fontPercent && overrides.fontPercent !== 1) {
  11744. const fontSize = window.parseFloat(cueDiv.style.fontSize);
  11745. cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
  11746. cueDiv.style.height = 'auto';
  11747. cueDiv.style.top = 'auto';
  11748. }
  11749. if (overrides.fontFamily && overrides.fontFamily !== 'default') {
  11750. if (overrides.fontFamily === 'small-caps') {
  11751. cueDiv.firstChild.style.fontVariant = 'small-caps';
  11752. } else {
  11753. cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
  11754. }
  11755. }
  11756. }
  11757. }
  11758. /**
  11759. * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}.
  11760. *
  11761. * @param {TextTrack|TextTrack[]} tracks
  11762. * Text track object or text track array to be added to the list.
  11763. */
  11764. updateForTrack(tracks) {
  11765. if (!Array.isArray(tracks)) {
  11766. tracks = [tracks];
  11767. }
  11768. if (typeof window.WebVTT !== 'function' || tracks.every(track => {
  11769. return !track.activeCues;
  11770. })) {
  11771. return;
  11772. }
  11773. const cues = [];
  11774. // push all active track cues
  11775. for (let i = 0; i < tracks.length; ++i) {
  11776. const track = tracks[i];
  11777. for (let j = 0; j < track.activeCues.length; ++j) {
  11778. cues.push(track.activeCues[j]);
  11779. }
  11780. }
  11781. // removes all cues before it processes new ones
  11782. window.WebVTT.processCues(window, cues, this.el_);
  11783. // add unique class to each language text track & add settings styling if necessary
  11784. for (let i = 0; i < tracks.length; ++i) {
  11785. const track = tracks[i];
  11786. for (let j = 0; j < track.activeCues.length; ++j) {
  11787. const cueEl = track.activeCues[j].displayState;
  11788. addClass(cueEl, 'vjs-text-track-cue', 'vjs-text-track-cue-' + (track.language ? track.language : i));
  11789. if (track.language) {
  11790. setAttribute(cueEl, 'lang', track.language);
  11791. }
  11792. }
  11793. if (this.player_.textTrackSettings) {
  11794. this.updateDisplayState(track);
  11795. }
  11796. }
  11797. }
  11798. }
  11799. Component$1.registerComponent('TextTrackDisplay', TextTrackDisplay);
  11800. /**
  11801. * @file loading-spinner.js
  11802. */
  11803. /**
  11804. * A loading spinner for use during waiting/loading events.
  11805. *
  11806. * @extends Component
  11807. */
  11808. class LoadingSpinner extends Component$1 {
  11809. /**
  11810. * Create the `LoadingSpinner`s DOM element.
  11811. *
  11812. * @return {Element}
  11813. * The dom element that gets created.
  11814. */
  11815. createEl() {
  11816. const isAudio = this.player_.isAudio();
  11817. const playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
  11818. const controlText = createEl('span', {
  11819. className: 'vjs-control-text',
  11820. textContent: this.localize('{1} is loading.', [playerType])
  11821. });
  11822. const el = super.createEl('div', {
  11823. className: 'vjs-loading-spinner',
  11824. dir: 'ltr'
  11825. });
  11826. el.appendChild(controlText);
  11827. return el;
  11828. }
  11829. /**
  11830. * Update control text on languagechange
  11831. */
  11832. handleLanguagechange() {
  11833. this.$('.vjs-control-text').textContent = this.localize('{1} is loading.', [this.player_.isAudio() ? 'Audio Player' : 'Video Player']);
  11834. }
  11835. }
  11836. Component$1.registerComponent('LoadingSpinner', LoadingSpinner);
  11837. /**
  11838. * @file button.js
  11839. */
  11840. /**
  11841. * Base class for all buttons.
  11842. *
  11843. * @extends ClickableComponent
  11844. */
  11845. class Button extends ClickableComponent {
  11846. /**
  11847. * Create the `Button`s DOM element.
  11848. *
  11849. * @param {string} [tag="button"]
  11850. * The element's node type. This argument is IGNORED: no matter what
  11851. * is passed, it will always create a `button` element.
  11852. *
  11853. * @param {Object} [props={}]
  11854. * An object of properties that should be set on the element.
  11855. *
  11856. * @param {Object} [attributes={}]
  11857. * An object of attributes that should be set on the element.
  11858. *
  11859. * @return {Element}
  11860. * The element that gets created.
  11861. */
  11862. createEl(tag, props = {}, attributes = {}) {
  11863. tag = 'button';
  11864. props = Object.assign({
  11865. className: this.buildCSSClass()
  11866. }, props);
  11867. // Add attributes for button element
  11868. attributes = Object.assign({
  11869. // Necessary since the default button type is "submit"
  11870. type: 'button'
  11871. }, attributes);
  11872. const el = createEl(tag, props, attributes);
  11873. el.appendChild(createEl('span', {
  11874. className: 'vjs-icon-placeholder'
  11875. }, {
  11876. 'aria-hidden': true
  11877. }));
  11878. this.createControlTextEl(el);
  11879. return el;
  11880. }
  11881. /**
  11882. * Add a child `Component` inside of this `Button`.
  11883. *
  11884. * @param {string|Component} child
  11885. * The name or instance of a child to add.
  11886. *
  11887. * @param {Object} [options={}]
  11888. * The key/value store of options that will get passed to children of
  11889. * the child.
  11890. *
  11891. * @return {Component}
  11892. * The `Component` that gets added as a child. When using a string the
  11893. * `Component` will get created by this process.
  11894. *
  11895. * @deprecated since version 5
  11896. */
  11897. addChild(child, options = {}) {
  11898. const className = this.constructor.name;
  11899. log$1.warn(`Adding an actionable (user controllable) child to a Button (${className}) is not supported; use a ClickableComponent instead.`);
  11900. // Avoid the error message generated by ClickableComponent's addChild method
  11901. return Component$1.prototype.addChild.call(this, child, options);
  11902. }
  11903. /**
  11904. * Enable the `Button` element so that it can be activated or clicked. Use this with
  11905. * {@link Button#disable}.
  11906. */
  11907. enable() {
  11908. super.enable();
  11909. this.el_.removeAttribute('disabled');
  11910. }
  11911. /**
  11912. * Disable the `Button` element so that it cannot be activated or clicked. Use this with
  11913. * {@link Button#enable}.
  11914. */
  11915. disable() {
  11916. super.disable();
  11917. this.el_.setAttribute('disabled', 'disabled');
  11918. }
  11919. /**
  11920. * This gets called when a `Button` has focus and `keydown` is triggered via a key
  11921. * press.
  11922. *
  11923. * @param {Event} event
  11924. * The event that caused this function to get called.
  11925. *
  11926. * @listens keydown
  11927. */
  11928. handleKeyDown(event) {
  11929. // Ignore Space or Enter key operation, which is handled by the browser for
  11930. // a button - though not for its super class, ClickableComponent. Also,
  11931. // prevent the event from propagating through the DOM and triggering Player
  11932. // hotkeys. We do not preventDefault here because we _want_ the browser to
  11933. // handle it.
  11934. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  11935. event.stopPropagation();
  11936. return;
  11937. }
  11938. // Pass keypress handling up for unsupported keys
  11939. super.handleKeyDown(event);
  11940. }
  11941. }
  11942. Component$1.registerComponent('Button', Button);
  11943. /**
  11944. * @file big-play-button.js
  11945. */
  11946. /**
  11947. * The initial play button that shows before the video has played. The hiding of the
  11948. * `BigPlayButton` get done via CSS and `Player` states.
  11949. *
  11950. * @extends Button
  11951. */
  11952. class BigPlayButton extends Button {
  11953. constructor(player, options) {
  11954. super(player, options);
  11955. this.mouseused_ = false;
  11956. this.on('mousedown', e => this.handleMouseDown(e));
  11957. }
  11958. /**
  11959. * Builds the default DOM `className`.
  11960. *
  11961. * @return {string}
  11962. * The DOM `className` for this object. Always returns 'vjs-big-play-button'.
  11963. */
  11964. buildCSSClass() {
  11965. return 'vjs-big-play-button';
  11966. }
  11967. /**
  11968. * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent}
  11969. * for more detailed information on what a click can be.
  11970. *
  11971. * @param {KeyboardEvent} event
  11972. * The `keydown`, `tap`, or `click` event that caused this function to be
  11973. * called.
  11974. *
  11975. * @listens tap
  11976. * @listens click
  11977. */
  11978. handleClick(event) {
  11979. const playPromise = this.player_.play();
  11980. // exit early if clicked via the mouse
  11981. if (this.mouseused_ && event.clientX && event.clientY) {
  11982. silencePromise(playPromise);
  11983. if (this.player_.tech(true)) {
  11984. this.player_.tech(true).focus();
  11985. }
  11986. return;
  11987. }
  11988. const cb = this.player_.getChild('controlBar');
  11989. const playToggle = cb && cb.getChild('playToggle');
  11990. if (!playToggle) {
  11991. this.player_.tech(true).focus();
  11992. return;
  11993. }
  11994. const playFocus = () => playToggle.focus();
  11995. if (isPromise(playPromise)) {
  11996. playPromise.then(playFocus, () => {});
  11997. } else {
  11998. this.setTimeout(playFocus, 1);
  11999. }
  12000. }
  12001. handleKeyDown(event) {
  12002. this.mouseused_ = false;
  12003. super.handleKeyDown(event);
  12004. }
  12005. handleMouseDown(event) {
  12006. this.mouseused_ = true;
  12007. }
  12008. }
  12009. /**
  12010. * The text that should display over the `BigPlayButton`s controls. Added to for localization.
  12011. *
  12012. * @type {string}
  12013. * @protected
  12014. */
  12015. BigPlayButton.prototype.controlText_ = 'Play Video';
  12016. Component$1.registerComponent('BigPlayButton', BigPlayButton);
  12017. /**
  12018. * @file close-button.js
  12019. */
  12020. /**
  12021. * The `CloseButton` is a `{@link Button}` that fires a `close` event when
  12022. * it gets clicked.
  12023. *
  12024. * @extends Button
  12025. */
  12026. class CloseButton extends Button {
  12027. /**
  12028. * Creates an instance of the this class.
  12029. *
  12030. * @param { import('./player').default } player
  12031. * The `Player` that this class should be attached to.
  12032. *
  12033. * @param {Object} [options]
  12034. * The key/value store of player options.
  12035. */
  12036. constructor(player, options) {
  12037. super(player, options);
  12038. this.controlText(options && options.controlText || this.localize('Close'));
  12039. }
  12040. /**
  12041. * Builds the default DOM `className`.
  12042. *
  12043. * @return {string}
  12044. * The DOM `className` for this object.
  12045. */
  12046. buildCSSClass() {
  12047. return `vjs-close-button ${super.buildCSSClass()}`;
  12048. }
  12049. /**
  12050. * This gets called when a `CloseButton` gets clicked. See
  12051. * {@link ClickableComponent#handleClick} for more information on when
  12052. * this will be triggered
  12053. *
  12054. * @param {Event} event
  12055. * The `keydown`, `tap`, or `click` event that caused this function to be
  12056. * called.
  12057. *
  12058. * @listens tap
  12059. * @listens click
  12060. * @fires CloseButton#close
  12061. */
  12062. handleClick(event) {
  12063. /**
  12064. * Triggered when the a `CloseButton` is clicked.
  12065. *
  12066. * @event CloseButton#close
  12067. * @type {Event}
  12068. *
  12069. * @property {boolean} [bubbles=false]
  12070. * set to false so that the close event does not
  12071. * bubble up to parents if there is no listener
  12072. */
  12073. this.trigger({
  12074. type: 'close',
  12075. bubbles: false
  12076. });
  12077. }
  12078. /**
  12079. * Event handler that is called when a `CloseButton` receives a
  12080. * `keydown` event.
  12081. *
  12082. * By default, if the key is Esc, it will trigger a `click` event.
  12083. *
  12084. * @param {Event} event
  12085. * The `keydown` event that caused this function to be called.
  12086. *
  12087. * @listens keydown
  12088. */
  12089. handleKeyDown(event) {
  12090. // Esc button will trigger `click` event
  12091. if (keycode.isEventKey(event, 'Esc')) {
  12092. event.preventDefault();
  12093. event.stopPropagation();
  12094. this.trigger('click');
  12095. } else {
  12096. // Pass keypress handling up for unsupported keys
  12097. super.handleKeyDown(event);
  12098. }
  12099. }
  12100. }
  12101. Component$1.registerComponent('CloseButton', CloseButton);
  12102. /**
  12103. * @file play-toggle.js
  12104. */
  12105. /**
  12106. * Button to toggle between play and pause.
  12107. *
  12108. * @extends Button
  12109. */
  12110. class PlayToggle extends Button {
  12111. /**
  12112. * Creates an instance of this class.
  12113. *
  12114. * @param { import('./player').default } player
  12115. * The `Player` that this class should be attached to.
  12116. *
  12117. * @param {Object} [options={}]
  12118. * The key/value store of player options.
  12119. */
  12120. constructor(player, options = {}) {
  12121. super(player, options);
  12122. // show or hide replay icon
  12123. options.replay = options.replay === undefined || options.replay;
  12124. this.on(player, 'play', e => this.handlePlay(e));
  12125. this.on(player, 'pause', e => this.handlePause(e));
  12126. if (options.replay) {
  12127. this.on(player, 'ended', e => this.handleEnded(e));
  12128. }
  12129. }
  12130. /**
  12131. * Builds the default DOM `className`.
  12132. *
  12133. * @return {string}
  12134. * The DOM `className` for this object.
  12135. */
  12136. buildCSSClass() {
  12137. return `vjs-play-control ${super.buildCSSClass()}`;
  12138. }
  12139. /**
  12140. * This gets called when an `PlayToggle` is "clicked". See
  12141. * {@link ClickableComponent} for more detailed information on what a click can be.
  12142. *
  12143. * @param {Event} [event]
  12144. * The `keydown`, `tap`, or `click` event that caused this function to be
  12145. * called.
  12146. *
  12147. * @listens tap
  12148. * @listens click
  12149. */
  12150. handleClick(event) {
  12151. if (this.player_.paused()) {
  12152. silencePromise(this.player_.play());
  12153. } else {
  12154. this.player_.pause();
  12155. }
  12156. }
  12157. /**
  12158. * This gets called once after the video has ended and the user seeks so that
  12159. * we can change the replay button back to a play button.
  12160. *
  12161. * @param {Event} [event]
  12162. * The event that caused this function to run.
  12163. *
  12164. * @listens Player#seeked
  12165. */
  12166. handleSeeked(event) {
  12167. this.removeClass('vjs-ended');
  12168. if (this.player_.paused()) {
  12169. this.handlePause(event);
  12170. } else {
  12171. this.handlePlay(event);
  12172. }
  12173. }
  12174. /**
  12175. * Add the vjs-playing class to the element so it can change appearance.
  12176. *
  12177. * @param {Event} [event]
  12178. * The event that caused this function to run.
  12179. *
  12180. * @listens Player#play
  12181. */
  12182. handlePlay(event) {
  12183. this.removeClass('vjs-ended', 'vjs-paused');
  12184. this.addClass('vjs-playing');
  12185. // change the button text to "Pause"
  12186. this.controlText('Pause');
  12187. }
  12188. /**
  12189. * Add the vjs-paused class to the element so it can change appearance.
  12190. *
  12191. * @param {Event} [event]
  12192. * The event that caused this function to run.
  12193. *
  12194. * @listens Player#pause
  12195. */
  12196. handlePause(event) {
  12197. this.removeClass('vjs-playing');
  12198. this.addClass('vjs-paused');
  12199. // change the button text to "Play"
  12200. this.controlText('Play');
  12201. }
  12202. /**
  12203. * Add the vjs-ended class to the element so it can change appearance
  12204. *
  12205. * @param {Event} [event]
  12206. * The event that caused this function to run.
  12207. *
  12208. * @listens Player#ended
  12209. */
  12210. handleEnded(event) {
  12211. this.removeClass('vjs-playing');
  12212. this.addClass('vjs-ended');
  12213. // change the button text to "Replay"
  12214. this.controlText('Replay');
  12215. // on the next seek remove the replay button
  12216. this.one(this.player_, 'seeked', e => this.handleSeeked(e));
  12217. }
  12218. }
  12219. /**
  12220. * The text that should display over the `PlayToggle`s controls. Added for localization.
  12221. *
  12222. * @type {string}
  12223. * @protected
  12224. */
  12225. PlayToggle.prototype.controlText_ = 'Play';
  12226. Component$1.registerComponent('PlayToggle', PlayToggle);
  12227. /**
  12228. * @file time-display.js
  12229. */
  12230. /**
  12231. * Displays time information about the video
  12232. *
  12233. * @extends Component
  12234. */
  12235. class TimeDisplay extends Component$1 {
  12236. /**
  12237. * Creates an instance of this class.
  12238. *
  12239. * @param { import('../../player').default } player
  12240. * The `Player` that this class should be attached to.
  12241. *
  12242. * @param {Object} [options]
  12243. * The key/value store of player options.
  12244. */
  12245. constructor(player, options) {
  12246. super(player, options);
  12247. this.on(player, ['timeupdate', 'ended'], e => this.updateContent(e));
  12248. this.updateTextNode_();
  12249. }
  12250. /**
  12251. * Create the `Component`'s DOM element
  12252. *
  12253. * @return {Element}
  12254. * The element that was created.
  12255. */
  12256. createEl() {
  12257. const className = this.buildCSSClass();
  12258. const el = super.createEl('div', {
  12259. className: `${className} vjs-time-control vjs-control`
  12260. });
  12261. const span = createEl('span', {
  12262. className: 'vjs-control-text',
  12263. textContent: `${this.localize(this.labelText_)}\u00a0`
  12264. }, {
  12265. role: 'presentation'
  12266. });
  12267. el.appendChild(span);
  12268. this.contentEl_ = createEl('span', {
  12269. className: `${className}-display`
  12270. }, {
  12271. // span elements have no implicit role, but some screen readers (notably VoiceOver)
  12272. // treat them as a break between items in the DOM when using arrow keys
  12273. // (or left-to-right swipes on iOS) to read contents of a page. Using
  12274. // role='presentation' causes VoiceOver to NOT treat this span as a break.
  12275. role: 'presentation'
  12276. });
  12277. el.appendChild(this.contentEl_);
  12278. return el;
  12279. }
  12280. dispose() {
  12281. this.contentEl_ = null;
  12282. this.textNode_ = null;
  12283. super.dispose();
  12284. }
  12285. /**
  12286. * Updates the time display text node with a new time
  12287. *
  12288. * @param {number} [time=0] the time to update to
  12289. *
  12290. * @private
  12291. */
  12292. updateTextNode_(time = 0) {
  12293. time = formatTime(time);
  12294. if (this.formattedTime_ === time) {
  12295. return;
  12296. }
  12297. this.formattedTime_ = time;
  12298. this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_', () => {
  12299. if (!this.contentEl_) {
  12300. return;
  12301. }
  12302. let oldNode = this.textNode_;
  12303. if (oldNode && this.contentEl_.firstChild !== oldNode) {
  12304. oldNode = null;
  12305. 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.');
  12306. }
  12307. this.textNode_ = document.createTextNode(this.formattedTime_);
  12308. if (!this.textNode_) {
  12309. return;
  12310. }
  12311. if (oldNode) {
  12312. this.contentEl_.replaceChild(this.textNode_, oldNode);
  12313. } else {
  12314. this.contentEl_.appendChild(this.textNode_);
  12315. }
  12316. });
  12317. }
  12318. /**
  12319. * To be filled out in the child class, should update the displayed time
  12320. * in accordance with the fact that the current time has changed.
  12321. *
  12322. * @param {Event} [event]
  12323. * The `timeupdate` event that caused this to run.
  12324. *
  12325. * @listens Player#timeupdate
  12326. */
  12327. updateContent(event) {}
  12328. }
  12329. /**
  12330. * The text that is added to the `TimeDisplay` for screen reader users.
  12331. *
  12332. * @type {string}
  12333. * @private
  12334. */
  12335. TimeDisplay.prototype.labelText_ = 'Time';
  12336. /**
  12337. * The text that should display over the `TimeDisplay`s controls. Added to for localization.
  12338. *
  12339. * @type {string}
  12340. * @protected
  12341. *
  12342. * @deprecated in v7; controlText_ is not used in non-active display Components
  12343. */
  12344. TimeDisplay.prototype.controlText_ = 'Time';
  12345. Component$1.registerComponent('TimeDisplay', TimeDisplay);
  12346. /**
  12347. * @file current-time-display.js
  12348. */
  12349. /**
  12350. * Displays the current time
  12351. *
  12352. * @extends Component
  12353. */
  12354. class CurrentTimeDisplay extends TimeDisplay {
  12355. /**
  12356. * Builds the default DOM `className`.
  12357. *
  12358. * @return {string}
  12359. * The DOM `className` for this object.
  12360. */
  12361. buildCSSClass() {
  12362. return 'vjs-current-time';
  12363. }
  12364. /**
  12365. * Update current time display
  12366. *
  12367. * @param {Event} [event]
  12368. * The `timeupdate` event that caused this function to run.
  12369. *
  12370. * @listens Player#timeupdate
  12371. */
  12372. updateContent(event) {
  12373. // Allows for smooth scrubbing, when player can't keep up.
  12374. let time;
  12375. if (this.player_.ended()) {
  12376. time = this.player_.duration();
  12377. } else {
  12378. time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  12379. }
  12380. this.updateTextNode_(time);
  12381. }
  12382. }
  12383. /**
  12384. * The text that is added to the `CurrentTimeDisplay` for screen reader users.
  12385. *
  12386. * @type {string}
  12387. * @private
  12388. */
  12389. CurrentTimeDisplay.prototype.labelText_ = 'Current Time';
  12390. /**
  12391. * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
  12392. *
  12393. * @type {string}
  12394. * @protected
  12395. *
  12396. * @deprecated in v7; controlText_ is not used in non-active display Components
  12397. */
  12398. CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
  12399. Component$1.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
  12400. /**
  12401. * @file duration-display.js
  12402. */
  12403. /**
  12404. * Displays the duration
  12405. *
  12406. * @extends Component
  12407. */
  12408. class DurationDisplay extends TimeDisplay {
  12409. /**
  12410. * Creates an instance of this class.
  12411. *
  12412. * @param { import('../../player').default } player
  12413. * The `Player` that this class should be attached to.
  12414. *
  12415. * @param {Object} [options]
  12416. * The key/value store of player options.
  12417. */
  12418. constructor(player, options) {
  12419. super(player, options);
  12420. const updateContent = e => this.updateContent(e);
  12421. // we do not want to/need to throttle duration changes,
  12422. // as they should always display the changed duration as
  12423. // it has changed
  12424. this.on(player, 'durationchange', updateContent);
  12425. // Listen to loadstart because the player duration is reset when a new media element is loaded,
  12426. // but the durationchange on the user agent will not fire.
  12427. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  12428. this.on(player, 'loadstart', updateContent);
  12429. // Also listen for timeupdate (in the parent) and loadedmetadata because removing those
  12430. // listeners could have broken dependent applications/libraries. These
  12431. // can likely be removed for 7.0.
  12432. this.on(player, 'loadedmetadata', updateContent);
  12433. }
  12434. /**
  12435. * Builds the default DOM `className`.
  12436. *
  12437. * @return {string}
  12438. * The DOM `className` for this object.
  12439. */
  12440. buildCSSClass() {
  12441. return 'vjs-duration';
  12442. }
  12443. /**
  12444. * Update duration time display.
  12445. *
  12446. * @param {Event} [event]
  12447. * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
  12448. * this function to be called.
  12449. *
  12450. * @listens Player#durationchange
  12451. * @listens Player#timeupdate
  12452. * @listens Player#loadedmetadata
  12453. */
  12454. updateContent(event) {
  12455. const duration = this.player_.duration();
  12456. this.updateTextNode_(duration);
  12457. }
  12458. }
  12459. /**
  12460. * The text that is added to the `DurationDisplay` for screen reader users.
  12461. *
  12462. * @type {string}
  12463. * @private
  12464. */
  12465. DurationDisplay.prototype.labelText_ = 'Duration';
  12466. /**
  12467. * The text that should display over the `DurationDisplay`s controls. Added to for localization.
  12468. *
  12469. * @type {string}
  12470. * @protected
  12471. *
  12472. * @deprecated in v7; controlText_ is not used in non-active display Components
  12473. */
  12474. DurationDisplay.prototype.controlText_ = 'Duration';
  12475. Component$1.registerComponent('DurationDisplay', DurationDisplay);
  12476. /**
  12477. * @file time-divider.js
  12478. */
  12479. /**
  12480. * The separator between the current time and duration.
  12481. * Can be hidden if it's not needed in the design.
  12482. *
  12483. * @extends Component
  12484. */
  12485. class TimeDivider extends Component$1 {
  12486. /**
  12487. * Create the component's DOM element
  12488. *
  12489. * @return {Element}
  12490. * The element that was created.
  12491. */
  12492. createEl() {
  12493. const el = super.createEl('div', {
  12494. className: 'vjs-time-control vjs-time-divider'
  12495. }, {
  12496. // this element and its contents can be hidden from assistive techs since
  12497. // it is made extraneous by the announcement of the control text
  12498. // for the current time and duration displays
  12499. 'aria-hidden': true
  12500. });
  12501. const div = super.createEl('div');
  12502. const span = super.createEl('span', {
  12503. textContent: '/'
  12504. });
  12505. div.appendChild(span);
  12506. el.appendChild(div);
  12507. return el;
  12508. }
  12509. }
  12510. Component$1.registerComponent('TimeDivider', TimeDivider);
  12511. /**
  12512. * @file remaining-time-display.js
  12513. */
  12514. /**
  12515. * Displays the time left in the video
  12516. *
  12517. * @extends Component
  12518. */
  12519. class RemainingTimeDisplay extends TimeDisplay {
  12520. /**
  12521. * Creates an instance of this class.
  12522. *
  12523. * @param { import('../../player').default } player
  12524. * The `Player` that this class should be attached to.
  12525. *
  12526. * @param {Object} [options]
  12527. * The key/value store of player options.
  12528. */
  12529. constructor(player, options) {
  12530. super(player, options);
  12531. this.on(player, 'durationchange', e => this.updateContent(e));
  12532. }
  12533. /**
  12534. * Builds the default DOM `className`.
  12535. *
  12536. * @return {string}
  12537. * The DOM `className` for this object.
  12538. */
  12539. buildCSSClass() {
  12540. return 'vjs-remaining-time';
  12541. }
  12542. /**
  12543. * Create the `Component`'s DOM element with the "minus" character prepend to the time
  12544. *
  12545. * @return {Element}
  12546. * The element that was created.
  12547. */
  12548. createEl() {
  12549. const el = super.createEl();
  12550. if (this.options_.displayNegative !== false) {
  12551. el.insertBefore(createEl('span', {}, {
  12552. 'aria-hidden': true
  12553. }, '-'), this.contentEl_);
  12554. }
  12555. return el;
  12556. }
  12557. /**
  12558. * Update remaining time display.
  12559. *
  12560. * @param {Event} [event]
  12561. * The `timeupdate` or `durationchange` event that caused this to run.
  12562. *
  12563. * @listens Player#timeupdate
  12564. * @listens Player#durationchange
  12565. */
  12566. updateContent(event) {
  12567. if (typeof this.player_.duration() !== 'number') {
  12568. return;
  12569. }
  12570. let time;
  12571. // @deprecated We should only use remainingTimeDisplay
  12572. // as of video.js 7
  12573. if (this.player_.ended()) {
  12574. time = 0;
  12575. } else if (this.player_.remainingTimeDisplay) {
  12576. time = this.player_.remainingTimeDisplay();
  12577. } else {
  12578. time = this.player_.remainingTime();
  12579. }
  12580. this.updateTextNode_(time);
  12581. }
  12582. }
  12583. /**
  12584. * The text that is added to the `RemainingTimeDisplay` for screen reader users.
  12585. *
  12586. * @type {string}
  12587. * @private
  12588. */
  12589. RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';
  12590. /**
  12591. * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
  12592. *
  12593. * @type {string}
  12594. * @protected
  12595. *
  12596. * @deprecated in v7; controlText_ is not used in non-active display Components
  12597. */
  12598. RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
  12599. Component$1.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
  12600. /**
  12601. * @file live-display.js
  12602. */
  12603. // TODO - Future make it click to snap to live
  12604. /**
  12605. * Displays the live indicator when duration is Infinity.
  12606. *
  12607. * @extends Component
  12608. */
  12609. class LiveDisplay extends Component$1 {
  12610. /**
  12611. * Creates an instance of this class.
  12612. *
  12613. * @param { import('./player').default } player
  12614. * The `Player` that this class should be attached to.
  12615. *
  12616. * @param {Object} [options]
  12617. * The key/value store of player options.
  12618. */
  12619. constructor(player, options) {
  12620. super(player, options);
  12621. this.updateShowing();
  12622. this.on(this.player(), 'durationchange', e => this.updateShowing(e));
  12623. }
  12624. /**
  12625. * Create the `Component`'s DOM element
  12626. *
  12627. * @return {Element}
  12628. * The element that was created.
  12629. */
  12630. createEl() {
  12631. const el = super.createEl('div', {
  12632. className: 'vjs-live-control vjs-control'
  12633. });
  12634. this.contentEl_ = createEl('div', {
  12635. className: 'vjs-live-display'
  12636. }, {
  12637. 'aria-live': 'off'
  12638. });
  12639. this.contentEl_.appendChild(createEl('span', {
  12640. className: 'vjs-control-text',
  12641. textContent: `${this.localize('Stream Type')}\u00a0`
  12642. }));
  12643. this.contentEl_.appendChild(document.createTextNode(this.localize('LIVE')));
  12644. el.appendChild(this.contentEl_);
  12645. return el;
  12646. }
  12647. dispose() {
  12648. this.contentEl_ = null;
  12649. super.dispose();
  12650. }
  12651. /**
  12652. * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide
  12653. * it accordingly
  12654. *
  12655. * @param {Event} [event]
  12656. * The {@link Player#durationchange} event that caused this function to run.
  12657. *
  12658. * @listens Player#durationchange
  12659. */
  12660. updateShowing(event) {
  12661. if (this.player().duration() === Infinity) {
  12662. this.show();
  12663. } else {
  12664. this.hide();
  12665. }
  12666. }
  12667. }
  12668. Component$1.registerComponent('LiveDisplay', LiveDisplay);
  12669. /**
  12670. * @file seek-to-live.js
  12671. */
  12672. /**
  12673. * Displays the live indicator when duration is Infinity.
  12674. *
  12675. * @extends Component
  12676. */
  12677. class SeekToLive extends Button {
  12678. /**
  12679. * Creates an instance of this class.
  12680. *
  12681. * @param { import('./player').default } player
  12682. * The `Player` that this class should be attached to.
  12683. *
  12684. * @param {Object} [options]
  12685. * The key/value store of player options.
  12686. */
  12687. constructor(player, options) {
  12688. super(player, options);
  12689. this.updateLiveEdgeStatus();
  12690. if (this.player_.liveTracker) {
  12691. this.updateLiveEdgeStatusHandler_ = e => this.updateLiveEdgeStatus(e);
  12692. this.on(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  12693. }
  12694. }
  12695. /**
  12696. * Create the `Component`'s DOM element
  12697. *
  12698. * @return {Element}
  12699. * The element that was created.
  12700. */
  12701. createEl() {
  12702. const el = super.createEl('button', {
  12703. className: 'vjs-seek-to-live-control vjs-control'
  12704. });
  12705. this.textEl_ = createEl('span', {
  12706. className: 'vjs-seek-to-live-text',
  12707. textContent: this.localize('LIVE')
  12708. }, {
  12709. 'aria-hidden': 'true'
  12710. });
  12711. el.appendChild(this.textEl_);
  12712. return el;
  12713. }
  12714. /**
  12715. * Update the state of this button if we are at the live edge
  12716. * or not
  12717. */
  12718. updateLiveEdgeStatus() {
  12719. // default to live edge
  12720. if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {
  12721. this.setAttribute('aria-disabled', true);
  12722. this.addClass('vjs-at-live-edge');
  12723. this.controlText('Seek to live, currently playing live');
  12724. } else {
  12725. this.setAttribute('aria-disabled', false);
  12726. this.removeClass('vjs-at-live-edge');
  12727. this.controlText('Seek to live, currently behind live');
  12728. }
  12729. }
  12730. /**
  12731. * On click bring us as near to the live point as possible.
  12732. * This requires that we wait for the next `live-seekable-change`
  12733. * event which will happen every segment length seconds.
  12734. */
  12735. handleClick() {
  12736. this.player_.liveTracker.seekToLiveEdge();
  12737. }
  12738. /**
  12739. * Dispose of the element and stop tracking
  12740. */
  12741. dispose() {
  12742. if (this.player_.liveTracker) {
  12743. this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  12744. }
  12745. this.textEl_ = null;
  12746. super.dispose();
  12747. }
  12748. }
  12749. /**
  12750. * The text that should display over the `SeekToLive`s control. Added for localization.
  12751. *
  12752. * @type {string}
  12753. * @protected
  12754. */
  12755. SeekToLive.prototype.controlText_ = 'Seek to live, currently playing live';
  12756. Component$1.registerComponent('SeekToLive', SeekToLive);
  12757. /**
  12758. * @file num.js
  12759. * @module num
  12760. */
  12761. /**
  12762. * Keep a number between a min and a max value
  12763. *
  12764. * @param {number} number
  12765. * The number to clamp
  12766. *
  12767. * @param {number} min
  12768. * The minimum value
  12769. * @param {number} max
  12770. * The maximum value
  12771. *
  12772. * @return {number}
  12773. * the clamped number
  12774. */
  12775. function clamp(number, min, max) {
  12776. number = Number(number);
  12777. return Math.min(max, Math.max(min, isNaN(number) ? min : number));
  12778. }
  12779. var Num = /*#__PURE__*/Object.freeze({
  12780. __proto__: null,
  12781. clamp: clamp
  12782. });
  12783. /**
  12784. * @file slider.js
  12785. */
  12786. /**
  12787. * The base functionality for a slider. Can be vertical or horizontal.
  12788. * For instance the volume bar or the seek bar on a video is a slider.
  12789. *
  12790. * @extends Component
  12791. */
  12792. class Slider extends Component$1 {
  12793. /**
  12794. * Create an instance of this class
  12795. *
  12796. * @param { import('../player').default } player
  12797. * The `Player` that this class should be attached to.
  12798. *
  12799. * @param {Object} [options]
  12800. * The key/value store of player options.
  12801. */
  12802. constructor(player, options) {
  12803. super(player, options);
  12804. this.handleMouseDown_ = e => this.handleMouseDown(e);
  12805. this.handleMouseUp_ = e => this.handleMouseUp(e);
  12806. this.handleKeyDown_ = e => this.handleKeyDown(e);
  12807. this.handleClick_ = e => this.handleClick(e);
  12808. this.handleMouseMove_ = e => this.handleMouseMove(e);
  12809. this.update_ = e => this.update(e);
  12810. // Set property names to bar to match with the child Slider class is looking for
  12811. this.bar = this.getChild(this.options_.barName);
  12812. // Set a horizontal or vertical class on the slider depending on the slider type
  12813. this.vertical(!!this.options_.vertical);
  12814. this.enable();
  12815. }
  12816. /**
  12817. * Are controls are currently enabled for this slider or not.
  12818. *
  12819. * @return {boolean}
  12820. * true if controls are enabled, false otherwise
  12821. */
  12822. enabled() {
  12823. return this.enabled_;
  12824. }
  12825. /**
  12826. * Enable controls for this slider if they are disabled
  12827. */
  12828. enable() {
  12829. if (this.enabled()) {
  12830. return;
  12831. }
  12832. this.on('mousedown', this.handleMouseDown_);
  12833. this.on('touchstart', this.handleMouseDown_);
  12834. this.on('keydown', this.handleKeyDown_);
  12835. this.on('click', this.handleClick_);
  12836. // TODO: deprecated, controlsvisible does not seem to be fired
  12837. this.on(this.player_, 'controlsvisible', this.update);
  12838. if (this.playerEvent) {
  12839. this.on(this.player_, this.playerEvent, this.update);
  12840. }
  12841. this.removeClass('disabled');
  12842. this.setAttribute('tabindex', 0);
  12843. this.enabled_ = true;
  12844. }
  12845. /**
  12846. * Disable controls for this slider if they are enabled
  12847. */
  12848. disable() {
  12849. if (!this.enabled()) {
  12850. return;
  12851. }
  12852. const doc = this.bar.el_.ownerDocument;
  12853. this.off('mousedown', this.handleMouseDown_);
  12854. this.off('touchstart', this.handleMouseDown_);
  12855. this.off('keydown', this.handleKeyDown_);
  12856. this.off('click', this.handleClick_);
  12857. this.off(this.player_, 'controlsvisible', this.update_);
  12858. this.off(doc, 'mousemove', this.handleMouseMove_);
  12859. this.off(doc, 'mouseup', this.handleMouseUp_);
  12860. this.off(doc, 'touchmove', this.handleMouseMove_);
  12861. this.off(doc, 'touchend', this.handleMouseUp_);
  12862. this.removeAttribute('tabindex');
  12863. this.addClass('disabled');
  12864. if (this.playerEvent) {
  12865. this.off(this.player_, this.playerEvent, this.update);
  12866. }
  12867. this.enabled_ = false;
  12868. }
  12869. /**
  12870. * Create the `Slider`s DOM element.
  12871. *
  12872. * @param {string} type
  12873. * Type of element to create.
  12874. *
  12875. * @param {Object} [props={}]
  12876. * List of properties in Object form.
  12877. *
  12878. * @param {Object} [attributes={}]
  12879. * list of attributes in Object form.
  12880. *
  12881. * @return {Element}
  12882. * The element that gets created.
  12883. */
  12884. createEl(type, props = {}, attributes = {}) {
  12885. // Add the slider element class to all sub classes
  12886. props.className = props.className + ' vjs-slider';
  12887. props = Object.assign({
  12888. tabIndex: 0
  12889. }, props);
  12890. attributes = Object.assign({
  12891. 'role': 'slider',
  12892. 'aria-valuenow': 0,
  12893. 'aria-valuemin': 0,
  12894. 'aria-valuemax': 100
  12895. }, attributes);
  12896. return super.createEl(type, props, attributes);
  12897. }
  12898. /**
  12899. * Handle `mousedown` or `touchstart` events on the `Slider`.
  12900. *
  12901. * @param {MouseEvent} event
  12902. * `mousedown` or `touchstart` event that triggered this function
  12903. *
  12904. * @listens mousedown
  12905. * @listens touchstart
  12906. * @fires Slider#slideractive
  12907. */
  12908. handleMouseDown(event) {
  12909. const doc = this.bar.el_.ownerDocument;
  12910. if (event.type === 'mousedown') {
  12911. event.preventDefault();
  12912. }
  12913. // Do not call preventDefault() on touchstart in Chrome
  12914. // to avoid console warnings. Use a 'touch-action: none' style
  12915. // instead to prevent unintended scrolling.
  12916. // https://developers.google.com/web/updates/2017/01/scrolling-intervention
  12917. if (event.type === 'touchstart' && !IS_CHROME) {
  12918. event.preventDefault();
  12919. }
  12920. blockTextSelection();
  12921. this.addClass('vjs-sliding');
  12922. /**
  12923. * Triggered when the slider is in an active state
  12924. *
  12925. * @event Slider#slideractive
  12926. * @type {MouseEvent}
  12927. */
  12928. this.trigger('slideractive');
  12929. this.on(doc, 'mousemove', this.handleMouseMove_);
  12930. this.on(doc, 'mouseup', this.handleMouseUp_);
  12931. this.on(doc, 'touchmove', this.handleMouseMove_);
  12932. this.on(doc, 'touchend', this.handleMouseUp_);
  12933. this.handleMouseMove(event, true);
  12934. }
  12935. /**
  12936. * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.
  12937. * The `mousemove` and `touchmove` events will only only trigger this function during
  12938. * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and
  12939. * {@link Slider#handleMouseUp}.
  12940. *
  12941. * @param {MouseEvent} event
  12942. * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
  12943. * this function
  12944. * @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.
  12945. *
  12946. * @listens mousemove
  12947. * @listens touchmove
  12948. */
  12949. handleMouseMove(event) {}
  12950. /**
  12951. * Handle `mouseup` or `touchend` events on the `Slider`.
  12952. *
  12953. * @param {MouseEvent} event
  12954. * `mouseup` or `touchend` event that triggered this function.
  12955. *
  12956. * @listens touchend
  12957. * @listens mouseup
  12958. * @fires Slider#sliderinactive
  12959. */
  12960. handleMouseUp(event) {
  12961. const doc = this.bar.el_.ownerDocument;
  12962. unblockTextSelection();
  12963. this.removeClass('vjs-sliding');
  12964. /**
  12965. * Triggered when the slider is no longer in an active state.
  12966. *
  12967. * @event Slider#sliderinactive
  12968. * @type {Event}
  12969. */
  12970. this.trigger('sliderinactive');
  12971. this.off(doc, 'mousemove', this.handleMouseMove_);
  12972. this.off(doc, 'mouseup', this.handleMouseUp_);
  12973. this.off(doc, 'touchmove', this.handleMouseMove_);
  12974. this.off(doc, 'touchend', this.handleMouseUp_);
  12975. this.update();
  12976. }
  12977. /**
  12978. * Update the progress bar of the `Slider`.
  12979. *
  12980. * @return {number}
  12981. * The percentage of progress the progress bar represents as a
  12982. * number from 0 to 1.
  12983. */
  12984. update() {
  12985. // In VolumeBar init we have a setTimeout for update that pops and update
  12986. // to the end of the execution stack. The player is destroyed before then
  12987. // update will cause an error
  12988. // If there's no bar...
  12989. if (!this.el_ || !this.bar) {
  12990. return;
  12991. }
  12992. // clamp progress between 0 and 1
  12993. // and only round to four decimal places, as we round to two below
  12994. const progress = this.getProgress();
  12995. if (progress === this.progress_) {
  12996. return progress;
  12997. }
  12998. this.progress_ = progress;
  12999. this.requestNamedAnimationFrame('Slider#update', () => {
  13000. // Set the new bar width or height
  13001. const sizeKey = this.vertical() ? 'height' : 'width';
  13002. // Convert to a percentage for css value
  13003. this.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + '%';
  13004. });
  13005. return progress;
  13006. }
  13007. /**
  13008. * Get the percentage of the bar that should be filled
  13009. * but clamped and rounded.
  13010. *
  13011. * @return {number}
  13012. * percentage filled that the slider is
  13013. */
  13014. getProgress() {
  13015. return Number(clamp(this.getPercent(), 0, 1).toFixed(4));
  13016. }
  13017. /**
  13018. * Calculate distance for slider
  13019. *
  13020. * @param {Event} event
  13021. * The event that caused this function to run.
  13022. *
  13023. * @return {number}
  13024. * The current position of the Slider.
  13025. * - position.x for vertical `Slider`s
  13026. * - position.y for horizontal `Slider`s
  13027. */
  13028. calculateDistance(event) {
  13029. const position = getPointerPosition(this.el_, event);
  13030. if (this.vertical()) {
  13031. return position.y;
  13032. }
  13033. return position.x;
  13034. }
  13035. /**
  13036. * Handle a `keydown` event on the `Slider`. Watches for left, right, up, and down
  13037. * arrow keys. This function will only be called when the slider has focus. See
  13038. * {@link Slider#handleFocus} and {@link Slider#handleBlur}.
  13039. *
  13040. * @param {KeyboardEvent} event
  13041. * the `keydown` event that caused this function to run.
  13042. *
  13043. * @listens keydown
  13044. */
  13045. handleKeyDown(event) {
  13046. // Left and Down Arrows
  13047. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  13048. event.preventDefault();
  13049. event.stopPropagation();
  13050. this.stepBack();
  13051. // Up and Right Arrows
  13052. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  13053. event.preventDefault();
  13054. event.stopPropagation();
  13055. this.stepForward();
  13056. } else {
  13057. // Pass keydown handling up for unsupported keys
  13058. super.handleKeyDown(event);
  13059. }
  13060. }
  13061. /**
  13062. * Listener for click events on slider, used to prevent clicks
  13063. * from bubbling up to parent elements like button menus.
  13064. *
  13065. * @param {Object} event
  13066. * Event that caused this object to run
  13067. */
  13068. handleClick(event) {
  13069. event.stopPropagation();
  13070. event.preventDefault();
  13071. }
  13072. /**
  13073. * Get/set if slider is horizontal for vertical
  13074. *
  13075. * @param {boolean} [bool]
  13076. * - true if slider is vertical,
  13077. * - false is horizontal
  13078. *
  13079. * @return {boolean}
  13080. * - true if slider is vertical, and getting
  13081. * - false if the slider is horizontal, and getting
  13082. */
  13083. vertical(bool) {
  13084. if (bool === undefined) {
  13085. return this.vertical_ || false;
  13086. }
  13087. this.vertical_ = !!bool;
  13088. if (this.vertical_) {
  13089. this.addClass('vjs-slider-vertical');
  13090. } else {
  13091. this.addClass('vjs-slider-horizontal');
  13092. }
  13093. }
  13094. }
  13095. Component$1.registerComponent('Slider', Slider);
  13096. /**
  13097. * @file load-progress-bar.js
  13098. */
  13099. // get the percent width of a time compared to the total end
  13100. const percentify = (time, end) => clamp(time / end * 100, 0, 100).toFixed(2) + '%';
  13101. /**
  13102. * Shows loading progress
  13103. *
  13104. * @extends Component
  13105. */
  13106. class LoadProgressBar extends Component$1 {
  13107. /**
  13108. * Creates an instance of this class.
  13109. *
  13110. * @param { import('../../player').default } player
  13111. * The `Player` that this class should be attached to.
  13112. *
  13113. * @param {Object} [options]
  13114. * The key/value store of player options.
  13115. */
  13116. constructor(player, options) {
  13117. super(player, options);
  13118. this.partEls_ = [];
  13119. this.on(player, 'progress', e => this.update(e));
  13120. }
  13121. /**
  13122. * Create the `Component`'s DOM element
  13123. *
  13124. * @return {Element}
  13125. * The element that was created.
  13126. */
  13127. createEl() {
  13128. const el = super.createEl('div', {
  13129. className: 'vjs-load-progress'
  13130. });
  13131. const wrapper = createEl('span', {
  13132. className: 'vjs-control-text'
  13133. });
  13134. const loadedText = createEl('span', {
  13135. textContent: this.localize('Loaded')
  13136. });
  13137. const separator = document.createTextNode(': ');
  13138. this.percentageEl_ = createEl('span', {
  13139. className: 'vjs-control-text-loaded-percentage',
  13140. textContent: '0%'
  13141. });
  13142. el.appendChild(wrapper);
  13143. wrapper.appendChild(loadedText);
  13144. wrapper.appendChild(separator);
  13145. wrapper.appendChild(this.percentageEl_);
  13146. return el;
  13147. }
  13148. dispose() {
  13149. this.partEls_ = null;
  13150. this.percentageEl_ = null;
  13151. super.dispose();
  13152. }
  13153. /**
  13154. * Update progress bar
  13155. *
  13156. * @param {Event} [event]
  13157. * The `progress` event that caused this function to run.
  13158. *
  13159. * @listens Player#progress
  13160. */
  13161. update(event) {
  13162. this.requestNamedAnimationFrame('LoadProgressBar#update', () => {
  13163. const liveTracker = this.player_.liveTracker;
  13164. const buffered = this.player_.buffered();
  13165. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  13166. const bufferedEnd = this.player_.bufferedEnd();
  13167. const children = this.partEls_;
  13168. const percent = percentify(bufferedEnd, duration);
  13169. if (this.percent_ !== percent) {
  13170. // update the width of the progress bar
  13171. this.el_.style.width = percent;
  13172. // update the control-text
  13173. textContent(this.percentageEl_, percent);
  13174. this.percent_ = percent;
  13175. }
  13176. // add child elements to represent the individual buffered time ranges
  13177. for (let i = 0; i < buffered.length; i++) {
  13178. const start = buffered.start(i);
  13179. const end = buffered.end(i);
  13180. let part = children[i];
  13181. if (!part) {
  13182. part = this.el_.appendChild(createEl());
  13183. children[i] = part;
  13184. }
  13185. // only update if changed
  13186. if (part.dataset.start === start && part.dataset.end === end) {
  13187. continue;
  13188. }
  13189. part.dataset.start = start;
  13190. part.dataset.end = end;
  13191. // set the percent based on the width of the progress bar (bufferedEnd)
  13192. part.style.left = percentify(start, bufferedEnd);
  13193. part.style.width = percentify(end - start, bufferedEnd);
  13194. }
  13195. // remove unused buffered range elements
  13196. for (let i = children.length; i > buffered.length; i--) {
  13197. this.el_.removeChild(children[i - 1]);
  13198. }
  13199. children.length = buffered.length;
  13200. });
  13201. }
  13202. }
  13203. Component$1.registerComponent('LoadProgressBar', LoadProgressBar);
  13204. /**
  13205. * @file time-tooltip.js
  13206. */
  13207. /**
  13208. * Time tooltips display a time above the progress bar.
  13209. *
  13210. * @extends Component
  13211. */
  13212. class TimeTooltip extends Component$1 {
  13213. /**
  13214. * Creates an instance of this class.
  13215. *
  13216. * @param { import('../../player').default } player
  13217. * The {@link Player} that this class should be attached to.
  13218. *
  13219. * @param {Object} [options]
  13220. * The key/value store of player options.
  13221. */
  13222. constructor(player, options) {
  13223. super(player, options);
  13224. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  13225. }
  13226. /**
  13227. * Create the time tooltip DOM element
  13228. *
  13229. * @return {Element}
  13230. * The element that was created.
  13231. */
  13232. createEl() {
  13233. return super.createEl('div', {
  13234. className: 'vjs-time-tooltip'
  13235. }, {
  13236. 'aria-hidden': 'true'
  13237. });
  13238. }
  13239. /**
  13240. * Updates the position of the time tooltip relative to the `SeekBar`.
  13241. *
  13242. * @param {Object} seekBarRect
  13243. * The `ClientRect` for the {@link SeekBar} element.
  13244. *
  13245. * @param {number} seekBarPoint
  13246. * A number from 0 to 1, representing a horizontal reference point
  13247. * from the left edge of the {@link SeekBar}
  13248. */
  13249. update(seekBarRect, seekBarPoint, content) {
  13250. const tooltipRect = findPosition(this.el_);
  13251. const playerRect = getBoundingClientRect(this.player_.el());
  13252. const seekBarPointPx = seekBarRect.width * seekBarPoint;
  13253. // do nothing if either rect isn't available
  13254. // for example, if the player isn't in the DOM for testing
  13255. if (!playerRect || !tooltipRect) {
  13256. return;
  13257. }
  13258. // This is the space left of the `seekBarPoint` available within the bounds
  13259. // of the player. We calculate any gap between the left edge of the player
  13260. // and the left edge of the `SeekBar` and add the number of pixels in the
  13261. // `SeekBar` before hitting the `seekBarPoint`
  13262. const spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx;
  13263. // This is the space right of the `seekBarPoint` available within the bounds
  13264. // of the player. We calculate the number of pixels from the `seekBarPoint`
  13265. // to the right edge of the `SeekBar` and add to that any gap between the
  13266. // right edge of the `SeekBar` and the player.
  13267. const spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right);
  13268. // This is the number of pixels by which the tooltip will need to be pulled
  13269. // further to the right to center it over the `seekBarPoint`.
  13270. let pullTooltipBy = tooltipRect.width / 2;
  13271. // Adjust the `pullTooltipBy` distance to the left or right depending on
  13272. // the results of the space calculations above.
  13273. if (spaceLeftOfPoint < pullTooltipBy) {
  13274. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  13275. } else if (spaceRightOfPoint < pullTooltipBy) {
  13276. pullTooltipBy = spaceRightOfPoint;
  13277. }
  13278. // Due to the imprecision of decimal/ratio based calculations and varying
  13279. // rounding behaviors, there are cases where the spacing adjustment is off
  13280. // by a pixel or two. This adds insurance to these calculations.
  13281. if (pullTooltipBy < 0) {
  13282. pullTooltipBy = 0;
  13283. } else if (pullTooltipBy > tooltipRect.width) {
  13284. pullTooltipBy = tooltipRect.width;
  13285. }
  13286. // prevent small width fluctuations within 0.4px from
  13287. // changing the value below.
  13288. // This really helps for live to prevent the play
  13289. // progress time tooltip from jittering
  13290. pullTooltipBy = Math.round(pullTooltipBy);
  13291. this.el_.style.right = `-${pullTooltipBy}px`;
  13292. this.write(content);
  13293. }
  13294. /**
  13295. * Write the time to the tooltip DOM element.
  13296. *
  13297. * @param {string} content
  13298. * The formatted time for the tooltip.
  13299. */
  13300. write(content) {
  13301. textContent(this.el_, content);
  13302. }
  13303. /**
  13304. * Updates the position of the time tooltip relative to the `SeekBar`.
  13305. *
  13306. * @param {Object} seekBarRect
  13307. * The `ClientRect` for the {@link SeekBar} element.
  13308. *
  13309. * @param {number} seekBarPoint
  13310. * A number from 0 to 1, representing a horizontal reference point
  13311. * from the left edge of the {@link SeekBar}
  13312. *
  13313. * @param {number} time
  13314. * The time to update the tooltip to, not used during live playback
  13315. *
  13316. * @param {Function} cb
  13317. * A function that will be called during the request animation frame
  13318. * for tooltips that need to do additional animations from the default
  13319. */
  13320. updateTime(seekBarRect, seekBarPoint, time, cb) {
  13321. this.requestNamedAnimationFrame('TimeTooltip#updateTime', () => {
  13322. let content;
  13323. const duration = this.player_.duration();
  13324. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  13325. const liveWindow = this.player_.liveTracker.liveWindow();
  13326. const secondsBehind = liveWindow - seekBarPoint * liveWindow;
  13327. content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow);
  13328. } else {
  13329. content = formatTime(time, duration);
  13330. }
  13331. this.update(seekBarRect, seekBarPoint, content);
  13332. if (cb) {
  13333. cb();
  13334. }
  13335. });
  13336. }
  13337. }
  13338. Component$1.registerComponent('TimeTooltip', TimeTooltip);
  13339. /**
  13340. * @file play-progress-bar.js
  13341. */
  13342. /**
  13343. * Used by {@link SeekBar} to display media playback progress as part of the
  13344. * {@link ProgressControl}.
  13345. *
  13346. * @extends Component
  13347. */
  13348. class PlayProgressBar extends Component$1 {
  13349. /**
  13350. * Creates an instance of this class.
  13351. *
  13352. * @param { import('../../player').default } player
  13353. * The {@link Player} that this class should be attached to.
  13354. *
  13355. * @param {Object} [options]
  13356. * The key/value store of player options.
  13357. */
  13358. constructor(player, options) {
  13359. super(player, options);
  13360. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  13361. }
  13362. /**
  13363. * Create the the DOM element for this class.
  13364. *
  13365. * @return {Element}
  13366. * The element that was created.
  13367. */
  13368. createEl() {
  13369. return super.createEl('div', {
  13370. className: 'vjs-play-progress vjs-slider-bar'
  13371. }, {
  13372. 'aria-hidden': 'true'
  13373. });
  13374. }
  13375. /**
  13376. * Enqueues updates to its own DOM as well as the DOM of its
  13377. * {@link TimeTooltip} child.
  13378. *
  13379. * @param {Object} seekBarRect
  13380. * The `ClientRect` for the {@link SeekBar} element.
  13381. *
  13382. * @param {number} seekBarPoint
  13383. * A number from 0 to 1, representing a horizontal reference point
  13384. * from the left edge of the {@link SeekBar}
  13385. */
  13386. update(seekBarRect, seekBarPoint) {
  13387. const timeTooltip = this.getChild('timeTooltip');
  13388. if (!timeTooltip) {
  13389. return;
  13390. }
  13391. const time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  13392. timeTooltip.updateTime(seekBarRect, seekBarPoint, time);
  13393. }
  13394. }
  13395. /**
  13396. * Default options for {@link PlayProgressBar}.
  13397. *
  13398. * @type {Object}
  13399. * @private
  13400. */
  13401. PlayProgressBar.prototype.options_ = {
  13402. children: []
  13403. };
  13404. // Time tooltips should not be added to a player on mobile devices
  13405. if (!IS_IOS && !IS_ANDROID) {
  13406. PlayProgressBar.prototype.options_.children.push('timeTooltip');
  13407. }
  13408. Component$1.registerComponent('PlayProgressBar', PlayProgressBar);
  13409. /**
  13410. * @file mouse-time-display.js
  13411. */
  13412. /**
  13413. * The {@link MouseTimeDisplay} component tracks mouse movement over the
  13414. * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}
  13415. * indicating the time which is represented by a given point in the
  13416. * {@link ProgressControl}.
  13417. *
  13418. * @extends Component
  13419. */
  13420. class MouseTimeDisplay extends Component$1 {
  13421. /**
  13422. * Creates an instance of this class.
  13423. *
  13424. * @param { import('../../player').default } player
  13425. * The {@link Player} that this class should be attached to.
  13426. *
  13427. * @param {Object} [options]
  13428. * The key/value store of player options.
  13429. */
  13430. constructor(player, options) {
  13431. super(player, options);
  13432. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  13433. }
  13434. /**
  13435. * Create the DOM element for this class.
  13436. *
  13437. * @return {Element}
  13438. * The element that was created.
  13439. */
  13440. createEl() {
  13441. return super.createEl('div', {
  13442. className: 'vjs-mouse-display'
  13443. });
  13444. }
  13445. /**
  13446. * Enqueues updates to its own DOM as well as the DOM of its
  13447. * {@link TimeTooltip} child.
  13448. *
  13449. * @param {Object} seekBarRect
  13450. * The `ClientRect` for the {@link SeekBar} element.
  13451. *
  13452. * @param {number} seekBarPoint
  13453. * A number from 0 to 1, representing a horizontal reference point
  13454. * from the left edge of the {@link SeekBar}
  13455. */
  13456. update(seekBarRect, seekBarPoint) {
  13457. const time = seekBarPoint * this.player_.duration();
  13458. this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, () => {
  13459. this.el_.style.left = `${seekBarRect.width * seekBarPoint}px`;
  13460. });
  13461. }
  13462. }
  13463. /**
  13464. * Default options for `MouseTimeDisplay`
  13465. *
  13466. * @type {Object}
  13467. * @private
  13468. */
  13469. MouseTimeDisplay.prototype.options_ = {
  13470. children: ['timeTooltip']
  13471. };
  13472. Component$1.registerComponent('MouseTimeDisplay', MouseTimeDisplay);
  13473. /**
  13474. * @file seek-bar.js
  13475. */
  13476. // The number of seconds the `step*` functions move the timeline.
  13477. const STEP_SECONDS = 5;
  13478. // The multiplier of STEP_SECONDS that PgUp/PgDown move the timeline.
  13479. const PAGE_KEY_MULTIPLIER = 12;
  13480. /**
  13481. * Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
  13482. * as its `bar`.
  13483. *
  13484. * @extends Slider
  13485. */
  13486. class SeekBar extends Slider {
  13487. /**
  13488. * Creates an instance of this class.
  13489. *
  13490. * @param { import('../../player').default } player
  13491. * The `Player` that this class should be attached to.
  13492. *
  13493. * @param {Object} [options]
  13494. * The key/value store of player options.
  13495. */
  13496. constructor(player, options) {
  13497. super(player, options);
  13498. this.setEventHandlers_();
  13499. }
  13500. /**
  13501. * Sets the event handlers
  13502. *
  13503. * @private
  13504. */
  13505. setEventHandlers_() {
  13506. this.update_ = bind_(this, this.update);
  13507. this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);
  13508. this.on(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  13509. if (this.player_.liveTracker) {
  13510. this.on(this.player_.liveTracker, 'liveedgechange', this.update);
  13511. }
  13512. // when playing, let's ensure we smoothly update the play progress bar
  13513. // via an interval
  13514. this.updateInterval = null;
  13515. this.enableIntervalHandler_ = e => this.enableInterval_(e);
  13516. this.disableIntervalHandler_ = e => this.disableInterval_(e);
  13517. this.on(this.player_, ['playing'], this.enableIntervalHandler_);
  13518. this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  13519. // we don't need to update the play progress if the document is hidden,
  13520. // also, this causes the CPU to spike and eventually crash the page on IE11.
  13521. if ('hidden' in document && 'visibilityState' in document) {
  13522. this.on(document, 'visibilitychange', this.toggleVisibility_);
  13523. }
  13524. }
  13525. toggleVisibility_(e) {
  13526. if (document.visibilityState === 'hidden') {
  13527. this.cancelNamedAnimationFrame('SeekBar#update');
  13528. this.cancelNamedAnimationFrame('Slider#update');
  13529. this.disableInterval_(e);
  13530. } else {
  13531. if (!this.player_.ended() && !this.player_.paused()) {
  13532. this.enableInterval_();
  13533. }
  13534. // we just switched back to the page and someone may be looking, so, update ASAP
  13535. this.update();
  13536. }
  13537. }
  13538. enableInterval_() {
  13539. if (this.updateInterval) {
  13540. return;
  13541. }
  13542. this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);
  13543. }
  13544. disableInterval_(e) {
  13545. if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== 'ended') {
  13546. return;
  13547. }
  13548. if (!this.updateInterval) {
  13549. return;
  13550. }
  13551. this.clearInterval(this.updateInterval);
  13552. this.updateInterval = null;
  13553. }
  13554. /**
  13555. * Create the `Component`'s DOM element
  13556. *
  13557. * @return {Element}
  13558. * The element that was created.
  13559. */
  13560. createEl() {
  13561. return super.createEl('div', {
  13562. className: 'vjs-progress-holder'
  13563. }, {
  13564. 'aria-label': this.localize('Progress Bar')
  13565. });
  13566. }
  13567. /**
  13568. * This function updates the play progress bar and accessibility
  13569. * attributes to whatever is passed in.
  13570. *
  13571. * @param {Event} [event]
  13572. * The `timeupdate` or `ended` event that caused this to run.
  13573. *
  13574. * @listens Player#timeupdate
  13575. *
  13576. * @return {number}
  13577. * The current percent at a number from 0-1
  13578. */
  13579. update(event) {
  13580. // ignore updates while the tab is hidden
  13581. if (document.visibilityState === 'hidden') {
  13582. return;
  13583. }
  13584. const percent = super.update();
  13585. this.requestNamedAnimationFrame('SeekBar#update', () => {
  13586. const currentTime = this.player_.ended() ? this.player_.duration() : this.getCurrentTime_();
  13587. const liveTracker = this.player_.liveTracker;
  13588. let duration = this.player_.duration();
  13589. if (liveTracker && liveTracker.isLive()) {
  13590. duration = this.player_.liveTracker.liveCurrentTime();
  13591. }
  13592. if (this.percent_ !== percent) {
  13593. // machine readable value of progress bar (percentage complete)
  13594. this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
  13595. this.percent_ = percent;
  13596. }
  13597. if (this.currentTime_ !== currentTime || this.duration_ !== duration) {
  13598. // human readable value of progress bar (time complete)
  13599. this.el_.setAttribute('aria-valuetext', this.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));
  13600. this.currentTime_ = currentTime;
  13601. this.duration_ = duration;
  13602. }
  13603. // update the progress bar time tooltip with the current time
  13604. if (this.bar) {
  13605. this.bar.update(getBoundingClientRect(this.el()), this.getProgress());
  13606. }
  13607. });
  13608. return percent;
  13609. }
  13610. /**
  13611. * Prevent liveThreshold from causing seeks to seem like they
  13612. * are not happening from a user perspective.
  13613. *
  13614. * @param {number} ct
  13615. * current time to seek to
  13616. */
  13617. userSeek_(ct) {
  13618. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  13619. this.player_.liveTracker.nextSeekedFromUser();
  13620. }
  13621. this.player_.currentTime(ct);
  13622. }
  13623. /**
  13624. * Get the value of current time but allows for smooth scrubbing,
  13625. * when player can't keep up.
  13626. *
  13627. * @return {number}
  13628. * The current time value to display
  13629. *
  13630. * @private
  13631. */
  13632. getCurrentTime_() {
  13633. return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  13634. }
  13635. /**
  13636. * Get the percentage of media played so far.
  13637. *
  13638. * @return {number}
  13639. * The percentage of media played so far (0 to 1).
  13640. */
  13641. getPercent() {
  13642. const currentTime = this.getCurrentTime_();
  13643. let percent;
  13644. const liveTracker = this.player_.liveTracker;
  13645. if (liveTracker && liveTracker.isLive()) {
  13646. percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow();
  13647. // prevent the percent from changing at the live edge
  13648. if (liveTracker.atLiveEdge()) {
  13649. percent = 1;
  13650. }
  13651. } else {
  13652. percent = currentTime / this.player_.duration();
  13653. }
  13654. return percent;
  13655. }
  13656. /**
  13657. * Handle mouse down on seek bar
  13658. *
  13659. * @param {MouseEvent} event
  13660. * The `mousedown` event that caused this to run.
  13661. *
  13662. * @listens mousedown
  13663. */
  13664. handleMouseDown(event) {
  13665. if (!isSingleLeftClick(event)) {
  13666. return;
  13667. }
  13668. // Stop event propagation to prevent double fire in progress-control.js
  13669. event.stopPropagation();
  13670. this.videoWasPlaying = !this.player_.paused();
  13671. this.player_.pause();
  13672. super.handleMouseDown(event);
  13673. }
  13674. /**
  13675. * Handle mouse move on seek bar
  13676. *
  13677. * @param {MouseEvent} event
  13678. * The `mousemove` event that caused this to run.
  13679. * @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
  13680. *
  13681. * @listens mousemove
  13682. */
  13683. handleMouseMove(event, mouseDown = false) {
  13684. if (!isSingleLeftClick(event)) {
  13685. return;
  13686. }
  13687. if (!mouseDown && !this.player_.scrubbing()) {
  13688. this.player_.scrubbing(true);
  13689. }
  13690. let newTime;
  13691. const distance = this.calculateDistance(event);
  13692. const liveTracker = this.player_.liveTracker;
  13693. if (!liveTracker || !liveTracker.isLive()) {
  13694. newTime = distance * this.player_.duration();
  13695. // Don't let video end while scrubbing.
  13696. if (newTime === this.player_.duration()) {
  13697. newTime = newTime - 0.1;
  13698. }
  13699. } else {
  13700. if (distance >= 0.99) {
  13701. liveTracker.seekToLiveEdge();
  13702. return;
  13703. }
  13704. const seekableStart = liveTracker.seekableStart();
  13705. const seekableEnd = liveTracker.liveCurrentTime();
  13706. newTime = seekableStart + distance * liveTracker.liveWindow();
  13707. // Don't let video end while scrubbing.
  13708. if (newTime >= seekableEnd) {
  13709. newTime = seekableEnd;
  13710. }
  13711. // Compensate for precision differences so that currentTime is not less
  13712. // than seekable start
  13713. if (newTime <= seekableStart) {
  13714. newTime = seekableStart + 0.1;
  13715. }
  13716. // On android seekableEnd can be Infinity sometimes,
  13717. // this will cause newTime to be Infinity, which is
  13718. // not a valid currentTime.
  13719. if (newTime === Infinity) {
  13720. return;
  13721. }
  13722. }
  13723. // Set new time (tell player to seek to new time)
  13724. this.userSeek_(newTime);
  13725. }
  13726. enable() {
  13727. super.enable();
  13728. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  13729. if (!mouseTimeDisplay) {
  13730. return;
  13731. }
  13732. mouseTimeDisplay.show();
  13733. }
  13734. disable() {
  13735. super.disable();
  13736. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  13737. if (!mouseTimeDisplay) {
  13738. return;
  13739. }
  13740. mouseTimeDisplay.hide();
  13741. }
  13742. /**
  13743. * Handle mouse up on seek bar
  13744. *
  13745. * @param {MouseEvent} event
  13746. * The `mouseup` event that caused this to run.
  13747. *
  13748. * @listens mouseup
  13749. */
  13750. handleMouseUp(event) {
  13751. super.handleMouseUp(event);
  13752. // Stop event propagation to prevent double fire in progress-control.js
  13753. if (event) {
  13754. event.stopPropagation();
  13755. }
  13756. this.player_.scrubbing(false);
  13757. /**
  13758. * Trigger timeupdate because we're done seeking and the time has changed.
  13759. * This is particularly useful for if the player is paused to time the time displays.
  13760. *
  13761. * @event Tech#timeupdate
  13762. * @type {Event}
  13763. */
  13764. this.player_.trigger({
  13765. type: 'timeupdate',
  13766. target: this,
  13767. manuallyTriggered: true
  13768. });
  13769. if (this.videoWasPlaying) {
  13770. silencePromise(this.player_.play());
  13771. } else {
  13772. // We're done seeking and the time has changed.
  13773. // If the player is paused, make sure we display the correct time on the seek bar.
  13774. this.update_();
  13775. }
  13776. }
  13777. /**
  13778. * Move more quickly fast forward for keyboard-only users
  13779. */
  13780. stepForward() {
  13781. this.userSeek_(this.player_.currentTime() + STEP_SECONDS);
  13782. }
  13783. /**
  13784. * Move more quickly rewind for keyboard-only users
  13785. */
  13786. stepBack() {
  13787. this.userSeek_(this.player_.currentTime() - STEP_SECONDS);
  13788. }
  13789. /**
  13790. * Toggles the playback state of the player
  13791. * This gets called when enter or space is used on the seekbar
  13792. *
  13793. * @param {KeyboardEvent} event
  13794. * The `keydown` event that caused this function to be called
  13795. *
  13796. */
  13797. handleAction(event) {
  13798. if (this.player_.paused()) {
  13799. this.player_.play();
  13800. } else {
  13801. this.player_.pause();
  13802. }
  13803. }
  13804. /**
  13805. * Called when this SeekBar has focus and a key gets pressed down.
  13806. * Supports the following keys:
  13807. *
  13808. * Space or Enter key fire a click event
  13809. * Home key moves to start of the timeline
  13810. * End key moves to end of the timeline
  13811. * Digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline
  13812. * PageDown key moves back a larger step than ArrowDown
  13813. * PageUp key moves forward a large step
  13814. *
  13815. * @param {KeyboardEvent} event
  13816. * The `keydown` event that caused this function to be called.
  13817. *
  13818. * @listens keydown
  13819. */
  13820. handleKeyDown(event) {
  13821. const liveTracker = this.player_.liveTracker;
  13822. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  13823. event.preventDefault();
  13824. event.stopPropagation();
  13825. this.handleAction(event);
  13826. } else if (keycode.isEventKey(event, 'Home')) {
  13827. event.preventDefault();
  13828. event.stopPropagation();
  13829. this.userSeek_(0);
  13830. } else if (keycode.isEventKey(event, 'End')) {
  13831. event.preventDefault();
  13832. event.stopPropagation();
  13833. if (liveTracker && liveTracker.isLive()) {
  13834. this.userSeek_(liveTracker.liveCurrentTime());
  13835. } else {
  13836. this.userSeek_(this.player_.duration());
  13837. }
  13838. } else if (/^[0-9]$/.test(keycode(event))) {
  13839. event.preventDefault();
  13840. event.stopPropagation();
  13841. const gotoFraction = (keycode.codes[keycode(event)] - keycode.codes['0']) * 10.0 / 100.0;
  13842. if (liveTracker && liveTracker.isLive()) {
  13843. this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);
  13844. } else {
  13845. this.userSeek_(this.player_.duration() * gotoFraction);
  13846. }
  13847. } else if (keycode.isEventKey(event, 'PgDn')) {
  13848. event.preventDefault();
  13849. event.stopPropagation();
  13850. this.userSeek_(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  13851. } else if (keycode.isEventKey(event, 'PgUp')) {
  13852. event.preventDefault();
  13853. event.stopPropagation();
  13854. this.userSeek_(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  13855. } else {
  13856. // Pass keydown handling up for unsupported keys
  13857. super.handleKeyDown(event);
  13858. }
  13859. }
  13860. dispose() {
  13861. this.disableInterval_();
  13862. this.off(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  13863. if (this.player_.liveTracker) {
  13864. this.off(this.player_.liveTracker, 'liveedgechange', this.update);
  13865. }
  13866. this.off(this.player_, ['playing'], this.enableIntervalHandler_);
  13867. this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  13868. // we don't need to update the play progress if the document is hidden,
  13869. // also, this causes the CPU to spike and eventually crash the page on IE11.
  13870. if ('hidden' in document && 'visibilityState' in document) {
  13871. this.off(document, 'visibilitychange', this.toggleVisibility_);
  13872. }
  13873. super.dispose();
  13874. }
  13875. }
  13876. /**
  13877. * Default options for the `SeekBar`
  13878. *
  13879. * @type {Object}
  13880. * @private
  13881. */
  13882. SeekBar.prototype.options_ = {
  13883. children: ['loadProgressBar', 'playProgressBar'],
  13884. barName: 'playProgressBar'
  13885. };
  13886. // MouseTimeDisplay tooltips should not be added to a player on mobile devices
  13887. if (!IS_IOS && !IS_ANDROID) {
  13888. SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay');
  13889. }
  13890. Component$1.registerComponent('SeekBar', SeekBar);
  13891. /**
  13892. * @file progress-control.js
  13893. */
  13894. /**
  13895. * The Progress Control component contains the seek bar, load progress,
  13896. * and play progress.
  13897. *
  13898. * @extends Component
  13899. */
  13900. class ProgressControl extends Component$1 {
  13901. /**
  13902. * Creates an instance of this class.
  13903. *
  13904. * @param { import('../../player').default } player
  13905. * The `Player` that this class should be attached to.
  13906. *
  13907. * @param {Object} [options]
  13908. * The key/value store of player options.
  13909. */
  13910. constructor(player, options) {
  13911. super(player, options);
  13912. this.handleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  13913. this.throttledHandleMouseSeek = throttle(bind_(this, this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);
  13914. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  13915. this.handleMouseDownHandler_ = e => this.handleMouseDown(e);
  13916. this.enable();
  13917. }
  13918. /**
  13919. * Create the `Component`'s DOM element
  13920. *
  13921. * @return {Element}
  13922. * The element that was created.
  13923. */
  13924. createEl() {
  13925. return super.createEl('div', {
  13926. className: 'vjs-progress-control vjs-control'
  13927. });
  13928. }
  13929. /**
  13930. * When the mouse moves over the `ProgressControl`, the pointer position
  13931. * gets passed down to the `MouseTimeDisplay` component.
  13932. *
  13933. * @param {Event} event
  13934. * The `mousemove` event that caused this function to run.
  13935. *
  13936. * @listen mousemove
  13937. */
  13938. handleMouseMove(event) {
  13939. const seekBar = this.getChild('seekBar');
  13940. if (!seekBar) {
  13941. return;
  13942. }
  13943. const playProgressBar = seekBar.getChild('playProgressBar');
  13944. const mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');
  13945. if (!playProgressBar && !mouseTimeDisplay) {
  13946. return;
  13947. }
  13948. const seekBarEl = seekBar.el();
  13949. const seekBarRect = findPosition(seekBarEl);
  13950. let seekBarPoint = getPointerPosition(seekBarEl, event).x;
  13951. // The default skin has a gap on either side of the `SeekBar`. This means
  13952. // that it's possible to trigger this behavior outside the boundaries of
  13953. // the `SeekBar`. This ensures we stay within it at all times.
  13954. seekBarPoint = clamp(seekBarPoint, 0, 1);
  13955. if (mouseTimeDisplay) {
  13956. mouseTimeDisplay.update(seekBarRect, seekBarPoint);
  13957. }
  13958. if (playProgressBar) {
  13959. playProgressBar.update(seekBarRect, seekBar.getProgress());
  13960. }
  13961. }
  13962. /**
  13963. * A throttled version of the {@link ProgressControl#handleMouseSeek} listener.
  13964. *
  13965. * @method ProgressControl#throttledHandleMouseSeek
  13966. * @param {Event} event
  13967. * The `mousemove` event that caused this function to run.
  13968. *
  13969. * @listen mousemove
  13970. * @listen touchmove
  13971. */
  13972. /**
  13973. * Handle `mousemove` or `touchmove` events on the `ProgressControl`.
  13974. *
  13975. * @param {Event} event
  13976. * `mousedown` or `touchstart` event that triggered this function
  13977. *
  13978. * @listens mousemove
  13979. * @listens touchmove
  13980. */
  13981. handleMouseSeek(event) {
  13982. const seekBar = this.getChild('seekBar');
  13983. if (seekBar) {
  13984. seekBar.handleMouseMove(event);
  13985. }
  13986. }
  13987. /**
  13988. * Are controls are currently enabled for this progress control.
  13989. *
  13990. * @return {boolean}
  13991. * true if controls are enabled, false otherwise
  13992. */
  13993. enabled() {
  13994. return this.enabled_;
  13995. }
  13996. /**
  13997. * Disable all controls on the progress control and its children
  13998. */
  13999. disable() {
  14000. this.children().forEach(child => child.disable && child.disable());
  14001. if (!this.enabled()) {
  14002. return;
  14003. }
  14004. this.off(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  14005. this.off(this.el_, 'mousemove', this.handleMouseMove);
  14006. this.removeListenersAddedOnMousedownAndTouchstart();
  14007. this.addClass('disabled');
  14008. this.enabled_ = false;
  14009. // Restore normal playback state if controls are disabled while scrubbing
  14010. if (this.player_.scrubbing()) {
  14011. const seekBar = this.getChild('seekBar');
  14012. this.player_.scrubbing(false);
  14013. if (seekBar.videoWasPlaying) {
  14014. silencePromise(this.player_.play());
  14015. }
  14016. }
  14017. }
  14018. /**
  14019. * Enable all controls on the progress control and its children
  14020. */
  14021. enable() {
  14022. this.children().forEach(child => child.enable && child.enable());
  14023. if (this.enabled()) {
  14024. return;
  14025. }
  14026. this.on(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  14027. this.on(this.el_, 'mousemove', this.handleMouseMove);
  14028. this.removeClass('disabled');
  14029. this.enabled_ = true;
  14030. }
  14031. /**
  14032. * Cleanup listeners after the user finishes interacting with the progress controls
  14033. */
  14034. removeListenersAddedOnMousedownAndTouchstart() {
  14035. const doc = this.el_.ownerDocument;
  14036. this.off(doc, 'mousemove', this.throttledHandleMouseSeek);
  14037. this.off(doc, 'touchmove', this.throttledHandleMouseSeek);
  14038. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  14039. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  14040. }
  14041. /**
  14042. * Handle `mousedown` or `touchstart` events on the `ProgressControl`.
  14043. *
  14044. * @param {Event} event
  14045. * `mousedown` or `touchstart` event that triggered this function
  14046. *
  14047. * @listens mousedown
  14048. * @listens touchstart
  14049. */
  14050. handleMouseDown(event) {
  14051. const doc = this.el_.ownerDocument;
  14052. const seekBar = this.getChild('seekBar');
  14053. if (seekBar) {
  14054. seekBar.handleMouseDown(event);
  14055. }
  14056. this.on(doc, 'mousemove', this.throttledHandleMouseSeek);
  14057. this.on(doc, 'touchmove', this.throttledHandleMouseSeek);
  14058. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  14059. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  14060. }
  14061. /**
  14062. * Handle `mouseup` or `touchend` events on the `ProgressControl`.
  14063. *
  14064. * @param {Event} event
  14065. * `mouseup` or `touchend` event that triggered this function.
  14066. *
  14067. * @listens touchend
  14068. * @listens mouseup
  14069. */
  14070. handleMouseUp(event) {
  14071. const seekBar = this.getChild('seekBar');
  14072. if (seekBar) {
  14073. seekBar.handleMouseUp(event);
  14074. }
  14075. this.removeListenersAddedOnMousedownAndTouchstart();
  14076. }
  14077. }
  14078. /**
  14079. * Default options for `ProgressControl`
  14080. *
  14081. * @type {Object}
  14082. * @private
  14083. */
  14084. ProgressControl.prototype.options_ = {
  14085. children: ['seekBar']
  14086. };
  14087. Component$1.registerComponent('ProgressControl', ProgressControl);
  14088. /**
  14089. * @file picture-in-picture-toggle.js
  14090. */
  14091. /**
  14092. * Toggle Picture-in-Picture mode
  14093. *
  14094. * @extends Button
  14095. */
  14096. class PictureInPictureToggle extends Button {
  14097. /**
  14098. * Creates an instance of this class.
  14099. *
  14100. * @param { import('./player').default } player
  14101. * The `Player` that this class should be attached to.
  14102. *
  14103. * @param {Object} [options]
  14104. * The key/value store of player options.
  14105. *
  14106. * @listens Player#enterpictureinpicture
  14107. * @listens Player#leavepictureinpicture
  14108. */
  14109. constructor(player, options) {
  14110. super(player, options);
  14111. this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], e => this.handlePictureInPictureChange(e));
  14112. this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], e => this.handlePictureInPictureEnabledChange(e));
  14113. this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], () => {
  14114. // This audio detection will not detect HLS or DASH audio-only streams because there was no reliable way to detect them at the time
  14115. const isSourceAudio = player.currentType().substring(0, 5) === 'audio';
  14116. if (isSourceAudio || player.audioPosterMode() || player.audioOnlyMode()) {
  14117. if (player.isInPictureInPicture()) {
  14118. player.exitPictureInPicture();
  14119. }
  14120. this.hide();
  14121. } else {
  14122. this.show();
  14123. }
  14124. });
  14125. // TODO: Deactivate button on player emptied event.
  14126. this.disable();
  14127. }
  14128. /**
  14129. * Builds the default DOM `className`.
  14130. *
  14131. * @return {string}
  14132. * The DOM `className` for this object.
  14133. */
  14134. buildCSSClass() {
  14135. return `vjs-picture-in-picture-control ${super.buildCSSClass()}`;
  14136. }
  14137. /**
  14138. * Enables or disables button based on availability of a Picture-In-Picture mode.
  14139. *
  14140. * Enabled if
  14141. * - `player.options().enableDocumentPictureInPicture` is true and
  14142. * window.documentPictureInPicture is available; or
  14143. * - `player.disablePictureInPicture()` is false and
  14144. * element.requestPictureInPicture is available
  14145. */
  14146. handlePictureInPictureEnabledChange() {
  14147. if (document.pictureInPictureEnabled && this.player_.disablePictureInPicture() === false || this.player_.options_.enableDocumentPictureInPicture && 'documentPictureInPicture' in window) {
  14148. this.enable();
  14149. } else {
  14150. this.disable();
  14151. }
  14152. }
  14153. /**
  14154. * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.
  14155. *
  14156. * @param {Event} [event]
  14157. * The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be
  14158. * called.
  14159. *
  14160. * @listens Player#enterpictureinpicture
  14161. * @listens Player#leavepictureinpicture
  14162. */
  14163. handlePictureInPictureChange(event) {
  14164. if (this.player_.isInPictureInPicture()) {
  14165. this.controlText('Exit Picture-in-Picture');
  14166. } else {
  14167. this.controlText('Picture-in-Picture');
  14168. }
  14169. this.handlePictureInPictureEnabledChange();
  14170. }
  14171. /**
  14172. * This gets called when an `PictureInPictureToggle` is "clicked". See
  14173. * {@link ClickableComponent} for more detailed information on what a click can be.
  14174. *
  14175. * @param {Event} [event]
  14176. * The `keydown`, `tap`, or `click` event that caused this function to be
  14177. * called.
  14178. *
  14179. * @listens tap
  14180. * @listens click
  14181. */
  14182. handleClick(event) {
  14183. if (!this.player_.isInPictureInPicture()) {
  14184. this.player_.requestPictureInPicture();
  14185. } else {
  14186. this.player_.exitPictureInPicture();
  14187. }
  14188. }
  14189. }
  14190. /**
  14191. * The text that should display over the `PictureInPictureToggle`s controls. Added for localization.
  14192. *
  14193. * @type {string}
  14194. * @protected
  14195. */
  14196. PictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture';
  14197. Component$1.registerComponent('PictureInPictureToggle', PictureInPictureToggle);
  14198. /**
  14199. * @file fullscreen-toggle.js
  14200. */
  14201. /**
  14202. * Toggle fullscreen video
  14203. *
  14204. * @extends Button
  14205. */
  14206. class FullscreenToggle extends Button {
  14207. /**
  14208. * Creates an instance of this class.
  14209. *
  14210. * @param { import('./player').default } player
  14211. * The `Player` that this class should be attached to.
  14212. *
  14213. * @param {Object} [options]
  14214. * The key/value store of player options.
  14215. */
  14216. constructor(player, options) {
  14217. super(player, options);
  14218. this.on(player, 'fullscreenchange', e => this.handleFullscreenChange(e));
  14219. if (document[player.fsApi_.fullscreenEnabled] === false) {
  14220. this.disable();
  14221. }
  14222. }
  14223. /**
  14224. * Builds the default DOM `className`.
  14225. *
  14226. * @return {string}
  14227. * The DOM `className` for this object.
  14228. */
  14229. buildCSSClass() {
  14230. return `vjs-fullscreen-control ${super.buildCSSClass()}`;
  14231. }
  14232. /**
  14233. * Handles fullscreenchange on the player and change control text accordingly.
  14234. *
  14235. * @param {Event} [event]
  14236. * The {@link Player#fullscreenchange} event that caused this function to be
  14237. * called.
  14238. *
  14239. * @listens Player#fullscreenchange
  14240. */
  14241. handleFullscreenChange(event) {
  14242. if (this.player_.isFullscreen()) {
  14243. this.controlText('Exit Fullscreen');
  14244. } else {
  14245. this.controlText('Fullscreen');
  14246. }
  14247. }
  14248. /**
  14249. * This gets called when an `FullscreenToggle` is "clicked". See
  14250. * {@link ClickableComponent} for more detailed information on what a click can be.
  14251. *
  14252. * @param {Event} [event]
  14253. * The `keydown`, `tap`, or `click` event that caused this function to be
  14254. * called.
  14255. *
  14256. * @listens tap
  14257. * @listens click
  14258. */
  14259. handleClick(event) {
  14260. if (!this.player_.isFullscreen()) {
  14261. this.player_.requestFullscreen();
  14262. } else {
  14263. this.player_.exitFullscreen();
  14264. }
  14265. }
  14266. }
  14267. /**
  14268. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  14269. *
  14270. * @type {string}
  14271. * @protected
  14272. */
  14273. FullscreenToggle.prototype.controlText_ = 'Fullscreen';
  14274. Component$1.registerComponent('FullscreenToggle', FullscreenToggle);
  14275. /**
  14276. * Check if volume control is supported and if it isn't hide the
  14277. * `Component` that was passed using the `vjs-hidden` class.
  14278. *
  14279. * @param { import('../../component').default } self
  14280. * The component that should be hidden if volume is unsupported
  14281. *
  14282. * @param { import('../../player').default } player
  14283. * A reference to the player
  14284. *
  14285. * @private
  14286. */
  14287. const checkVolumeSupport = function (self, player) {
  14288. // hide volume controls when they're not supported by the current tech
  14289. if (player.tech_ && !player.tech_.featuresVolumeControl) {
  14290. self.addClass('vjs-hidden');
  14291. }
  14292. self.on(player, 'loadstart', function () {
  14293. if (!player.tech_.featuresVolumeControl) {
  14294. self.addClass('vjs-hidden');
  14295. } else {
  14296. self.removeClass('vjs-hidden');
  14297. }
  14298. });
  14299. };
  14300. /**
  14301. * @file volume-level.js
  14302. */
  14303. /**
  14304. * Shows volume level
  14305. *
  14306. * @extends Component
  14307. */
  14308. class VolumeLevel extends Component$1 {
  14309. /**
  14310. * Create the `Component`'s DOM element
  14311. *
  14312. * @return {Element}
  14313. * The element that was created.
  14314. */
  14315. createEl() {
  14316. const el = super.createEl('div', {
  14317. className: 'vjs-volume-level'
  14318. });
  14319. el.appendChild(super.createEl('span', {
  14320. className: 'vjs-control-text'
  14321. }));
  14322. return el;
  14323. }
  14324. }
  14325. Component$1.registerComponent('VolumeLevel', VolumeLevel);
  14326. /**
  14327. * @file volume-level-tooltip.js
  14328. */
  14329. /**
  14330. * Volume level tooltips display a volume above or side by side the volume bar.
  14331. *
  14332. * @extends Component
  14333. */
  14334. class VolumeLevelTooltip extends Component$1 {
  14335. /**
  14336. * Creates an instance of this class.
  14337. *
  14338. * @param { import('../../player').default } player
  14339. * The {@link Player} that this class should be attached to.
  14340. *
  14341. * @param {Object} [options]
  14342. * The key/value store of player options.
  14343. */
  14344. constructor(player, options) {
  14345. super(player, options);
  14346. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  14347. }
  14348. /**
  14349. * Create the volume tooltip DOM element
  14350. *
  14351. * @return {Element}
  14352. * The element that was created.
  14353. */
  14354. createEl() {
  14355. return super.createEl('div', {
  14356. className: 'vjs-volume-tooltip'
  14357. }, {
  14358. 'aria-hidden': 'true'
  14359. });
  14360. }
  14361. /**
  14362. * Updates the position of the tooltip relative to the `VolumeBar` and
  14363. * its content text.
  14364. *
  14365. * @param {Object} rangeBarRect
  14366. * The `ClientRect` for the {@link VolumeBar} element.
  14367. *
  14368. * @param {number} rangeBarPoint
  14369. * A number from 0 to 1, representing a horizontal/vertical reference point
  14370. * from the left edge of the {@link VolumeBar}
  14371. *
  14372. * @param {boolean} vertical
  14373. * Referees to the Volume control position
  14374. * in the control bar{@link VolumeControl}
  14375. *
  14376. */
  14377. update(rangeBarRect, rangeBarPoint, vertical, content) {
  14378. if (!vertical) {
  14379. const tooltipRect = getBoundingClientRect(this.el_);
  14380. const playerRect = getBoundingClientRect(this.player_.el());
  14381. const volumeBarPointPx = rangeBarRect.width * rangeBarPoint;
  14382. if (!playerRect || !tooltipRect) {
  14383. return;
  14384. }
  14385. const spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;
  14386. const spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);
  14387. let pullTooltipBy = tooltipRect.width / 2;
  14388. if (spaceLeftOfPoint < pullTooltipBy) {
  14389. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  14390. } else if (spaceRightOfPoint < pullTooltipBy) {
  14391. pullTooltipBy = spaceRightOfPoint;
  14392. }
  14393. if (pullTooltipBy < 0) {
  14394. pullTooltipBy = 0;
  14395. } else if (pullTooltipBy > tooltipRect.width) {
  14396. pullTooltipBy = tooltipRect.width;
  14397. }
  14398. this.el_.style.right = `-${pullTooltipBy}px`;
  14399. }
  14400. this.write(`${content}%`);
  14401. }
  14402. /**
  14403. * Write the volume to the tooltip DOM element.
  14404. *
  14405. * @param {string} content
  14406. * The formatted volume for the tooltip.
  14407. */
  14408. write(content) {
  14409. textContent(this.el_, content);
  14410. }
  14411. /**
  14412. * Updates the position of the volume tooltip relative to the `VolumeBar`.
  14413. *
  14414. * @param {Object} rangeBarRect
  14415. * The `ClientRect` for the {@link VolumeBar} element.
  14416. *
  14417. * @param {number} rangeBarPoint
  14418. * A number from 0 to 1, representing a horizontal/vertical reference point
  14419. * from the left edge of the {@link VolumeBar}
  14420. *
  14421. * @param {boolean} vertical
  14422. * Referees to the Volume control position
  14423. * in the control bar{@link VolumeControl}
  14424. *
  14425. * @param {number} volume
  14426. * The volume level to update the tooltip to
  14427. *
  14428. * @param {Function} cb
  14429. * A function that will be called during the request animation frame
  14430. * for tooltips that need to do additional animations from the default
  14431. */
  14432. updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {
  14433. this.requestNamedAnimationFrame('VolumeLevelTooltip#updateVolume', () => {
  14434. this.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));
  14435. if (cb) {
  14436. cb();
  14437. }
  14438. });
  14439. }
  14440. }
  14441. Component$1.registerComponent('VolumeLevelTooltip', VolumeLevelTooltip);
  14442. /**
  14443. * @file mouse-volume-level-display.js
  14444. */
  14445. /**
  14446. * The {@link MouseVolumeLevelDisplay} component tracks mouse movement over the
  14447. * {@link VolumeControl}. It displays an indicator and a {@link VolumeLevelTooltip}
  14448. * indicating the volume level which is represented by a given point in the
  14449. * {@link VolumeBar}.
  14450. *
  14451. * @extends Component
  14452. */
  14453. class MouseVolumeLevelDisplay extends Component$1 {
  14454. /**
  14455. * Creates an instance of this class.
  14456. *
  14457. * @param { import('../../player').default } player
  14458. * The {@link Player} that this class should be attached to.
  14459. *
  14460. * @param {Object} [options]
  14461. * The key/value store of player options.
  14462. */
  14463. constructor(player, options) {
  14464. super(player, options);
  14465. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  14466. }
  14467. /**
  14468. * Create the DOM element for this class.
  14469. *
  14470. * @return {Element}
  14471. * The element that was created.
  14472. */
  14473. createEl() {
  14474. return super.createEl('div', {
  14475. className: 'vjs-mouse-display'
  14476. });
  14477. }
  14478. /**
  14479. * Enquires updates to its own DOM as well as the DOM of its
  14480. * {@link VolumeLevelTooltip} child.
  14481. *
  14482. * @param {Object} rangeBarRect
  14483. * The `ClientRect` for the {@link VolumeBar} element.
  14484. *
  14485. * @param {number} rangeBarPoint
  14486. * A number from 0 to 1, representing a horizontal/vertical reference point
  14487. * from the left edge of the {@link VolumeBar}
  14488. *
  14489. * @param {boolean} vertical
  14490. * Referees to the Volume control position
  14491. * in the control bar{@link VolumeControl}
  14492. *
  14493. */
  14494. update(rangeBarRect, rangeBarPoint, vertical) {
  14495. const volume = 100 * rangeBarPoint;
  14496. this.getChild('volumeLevelTooltip').updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, () => {
  14497. if (vertical) {
  14498. this.el_.style.bottom = `${rangeBarRect.height * rangeBarPoint}px`;
  14499. } else {
  14500. this.el_.style.left = `${rangeBarRect.width * rangeBarPoint}px`;
  14501. }
  14502. });
  14503. }
  14504. }
  14505. /**
  14506. * Default options for `MouseVolumeLevelDisplay`
  14507. *
  14508. * @type {Object}
  14509. * @private
  14510. */
  14511. MouseVolumeLevelDisplay.prototype.options_ = {
  14512. children: ['volumeLevelTooltip']
  14513. };
  14514. Component$1.registerComponent('MouseVolumeLevelDisplay', MouseVolumeLevelDisplay);
  14515. /**
  14516. * @file volume-bar.js
  14517. */
  14518. /**
  14519. * The bar that contains the volume level and can be clicked on to adjust the level
  14520. *
  14521. * @extends Slider
  14522. */
  14523. class VolumeBar extends Slider {
  14524. /**
  14525. * Creates an instance of this class.
  14526. *
  14527. * @param { import('../../player').default } player
  14528. * The `Player` that this class should be attached to.
  14529. *
  14530. * @param {Object} [options]
  14531. * The key/value store of player options.
  14532. */
  14533. constructor(player, options) {
  14534. super(player, options);
  14535. this.on('slideractive', e => this.updateLastVolume_(e));
  14536. this.on(player, 'volumechange', e => this.updateARIAAttributes(e));
  14537. player.ready(() => this.updateARIAAttributes());
  14538. }
  14539. /**
  14540. * Create the `Component`'s DOM element
  14541. *
  14542. * @return {Element}
  14543. * The element that was created.
  14544. */
  14545. createEl() {
  14546. return super.createEl('div', {
  14547. className: 'vjs-volume-bar vjs-slider-bar'
  14548. }, {
  14549. 'aria-label': this.localize('Volume Level'),
  14550. 'aria-live': 'polite'
  14551. });
  14552. }
  14553. /**
  14554. * Handle mouse down on volume bar
  14555. *
  14556. * @param {Event} event
  14557. * The `mousedown` event that caused this to run.
  14558. *
  14559. * @listens mousedown
  14560. */
  14561. handleMouseDown(event) {
  14562. if (!isSingleLeftClick(event)) {
  14563. return;
  14564. }
  14565. super.handleMouseDown(event);
  14566. }
  14567. /**
  14568. * Handle movement events on the {@link VolumeMenuButton}.
  14569. *
  14570. * @param {Event} event
  14571. * The event that caused this function to run.
  14572. *
  14573. * @listens mousemove
  14574. */
  14575. handleMouseMove(event) {
  14576. const mouseVolumeLevelDisplay = this.getChild('mouseVolumeLevelDisplay');
  14577. if (mouseVolumeLevelDisplay) {
  14578. const volumeBarEl = this.el();
  14579. const volumeBarRect = getBoundingClientRect(volumeBarEl);
  14580. const vertical = this.vertical();
  14581. let volumeBarPoint = getPointerPosition(volumeBarEl, event);
  14582. volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x;
  14583. // The default skin has a gap on either side of the `VolumeBar`. This means
  14584. // that it's possible to trigger this behavior outside the boundaries of
  14585. // the `VolumeBar`. This ensures we stay within it at all times.
  14586. volumeBarPoint = clamp(volumeBarPoint, 0, 1);
  14587. mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);
  14588. }
  14589. if (!isSingleLeftClick(event)) {
  14590. return;
  14591. }
  14592. this.checkMuted();
  14593. this.player_.volume(this.calculateDistance(event));
  14594. }
  14595. /**
  14596. * If the player is muted unmute it.
  14597. */
  14598. checkMuted() {
  14599. if (this.player_.muted()) {
  14600. this.player_.muted(false);
  14601. }
  14602. }
  14603. /**
  14604. * Get percent of volume level
  14605. *
  14606. * @return {number}
  14607. * Volume level percent as a decimal number.
  14608. */
  14609. getPercent() {
  14610. if (this.player_.muted()) {
  14611. return 0;
  14612. }
  14613. return this.player_.volume();
  14614. }
  14615. /**
  14616. * Increase volume level for keyboard users
  14617. */
  14618. stepForward() {
  14619. this.checkMuted();
  14620. this.player_.volume(this.player_.volume() + 0.1);
  14621. }
  14622. /**
  14623. * Decrease volume level for keyboard users
  14624. */
  14625. stepBack() {
  14626. this.checkMuted();
  14627. this.player_.volume(this.player_.volume() - 0.1);
  14628. }
  14629. /**
  14630. * Update ARIA accessibility attributes
  14631. *
  14632. * @param {Event} [event]
  14633. * The `volumechange` event that caused this function to run.
  14634. *
  14635. * @listens Player#volumechange
  14636. */
  14637. updateARIAAttributes(event) {
  14638. const ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
  14639. this.el_.setAttribute('aria-valuenow', ariaValue);
  14640. this.el_.setAttribute('aria-valuetext', ariaValue + '%');
  14641. }
  14642. /**
  14643. * Returns the current value of the player volume as a percentage
  14644. *
  14645. * @private
  14646. */
  14647. volumeAsPercentage_() {
  14648. return Math.round(this.player_.volume() * 100);
  14649. }
  14650. /**
  14651. * When user starts dragging the VolumeBar, store the volume and listen for
  14652. * the end of the drag. When the drag ends, if the volume was set to zero,
  14653. * set lastVolume to the stored volume.
  14654. *
  14655. * @listens slideractive
  14656. * @private
  14657. */
  14658. updateLastVolume_() {
  14659. const volumeBeforeDrag = this.player_.volume();
  14660. this.one('sliderinactive', () => {
  14661. if (this.player_.volume() === 0) {
  14662. this.player_.lastVolume_(volumeBeforeDrag);
  14663. }
  14664. });
  14665. }
  14666. }
  14667. /**
  14668. * Default options for the `VolumeBar`
  14669. *
  14670. * @type {Object}
  14671. * @private
  14672. */
  14673. VolumeBar.prototype.options_ = {
  14674. children: ['volumeLevel'],
  14675. barName: 'volumeLevel'
  14676. };
  14677. // MouseVolumeLevelDisplay tooltip should not be added to a player on mobile devices
  14678. if (!IS_IOS && !IS_ANDROID) {
  14679. VolumeBar.prototype.options_.children.splice(0, 0, 'mouseVolumeLevelDisplay');
  14680. }
  14681. /**
  14682. * Call the update event for this Slider when this event happens on the player.
  14683. *
  14684. * @type {string}
  14685. */
  14686. VolumeBar.prototype.playerEvent = 'volumechange';
  14687. Component$1.registerComponent('VolumeBar', VolumeBar);
  14688. /**
  14689. * @file volume-control.js
  14690. */
  14691. /**
  14692. * The component for controlling the volume level
  14693. *
  14694. * @extends Component
  14695. */
  14696. class VolumeControl extends Component$1 {
  14697. /**
  14698. * Creates an instance of this class.
  14699. *
  14700. * @param { import('../../player').default } player
  14701. * The `Player` that this class should be attached to.
  14702. *
  14703. * @param {Object} [options={}]
  14704. * The key/value store of player options.
  14705. */
  14706. constructor(player, options = {}) {
  14707. options.vertical = options.vertical || false;
  14708. // Pass the vertical option down to the VolumeBar if
  14709. // the VolumeBar is turned on.
  14710. if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {
  14711. options.volumeBar = options.volumeBar || {};
  14712. options.volumeBar.vertical = options.vertical;
  14713. }
  14714. super(player, options);
  14715. // hide this control if volume support is missing
  14716. checkVolumeSupport(this, player);
  14717. this.throttledHandleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  14718. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  14719. this.on('mousedown', e => this.handleMouseDown(e));
  14720. this.on('touchstart', e => this.handleMouseDown(e));
  14721. this.on('mousemove', e => this.handleMouseMove(e));
  14722. // while the slider is active (the mouse has been pressed down and
  14723. // is dragging) or in focus we do not want to hide the VolumeBar
  14724. this.on(this.volumeBar, ['focus', 'slideractive'], () => {
  14725. this.volumeBar.addClass('vjs-slider-active');
  14726. this.addClass('vjs-slider-active');
  14727. this.trigger('slideractive');
  14728. });
  14729. this.on(this.volumeBar, ['blur', 'sliderinactive'], () => {
  14730. this.volumeBar.removeClass('vjs-slider-active');
  14731. this.removeClass('vjs-slider-active');
  14732. this.trigger('sliderinactive');
  14733. });
  14734. }
  14735. /**
  14736. * Create the `Component`'s DOM element
  14737. *
  14738. * @return {Element}
  14739. * The element that was created.
  14740. */
  14741. createEl() {
  14742. let orientationClass = 'vjs-volume-horizontal';
  14743. if (this.options_.vertical) {
  14744. orientationClass = 'vjs-volume-vertical';
  14745. }
  14746. return super.createEl('div', {
  14747. className: `vjs-volume-control vjs-control ${orientationClass}`
  14748. });
  14749. }
  14750. /**
  14751. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  14752. *
  14753. * @param {Event} event
  14754. * `mousedown` or `touchstart` event that triggered this function
  14755. *
  14756. * @listens mousedown
  14757. * @listens touchstart
  14758. */
  14759. handleMouseDown(event) {
  14760. const doc = this.el_.ownerDocument;
  14761. this.on(doc, 'mousemove', this.throttledHandleMouseMove);
  14762. this.on(doc, 'touchmove', this.throttledHandleMouseMove);
  14763. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  14764. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  14765. }
  14766. /**
  14767. * Handle `mouseup` or `touchend` events on the `VolumeControl`.
  14768. *
  14769. * @param {Event} event
  14770. * `mouseup` or `touchend` event that triggered this function.
  14771. *
  14772. * @listens touchend
  14773. * @listens mouseup
  14774. */
  14775. handleMouseUp(event) {
  14776. const doc = this.el_.ownerDocument;
  14777. this.off(doc, 'mousemove', this.throttledHandleMouseMove);
  14778. this.off(doc, 'touchmove', this.throttledHandleMouseMove);
  14779. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  14780. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  14781. }
  14782. /**
  14783. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  14784. *
  14785. * @param {Event} event
  14786. * `mousedown` or `touchstart` event that triggered this function
  14787. *
  14788. * @listens mousedown
  14789. * @listens touchstart
  14790. */
  14791. handleMouseMove(event) {
  14792. this.volumeBar.handleMouseMove(event);
  14793. }
  14794. }
  14795. /**
  14796. * Default options for the `VolumeControl`
  14797. *
  14798. * @type {Object}
  14799. * @private
  14800. */
  14801. VolumeControl.prototype.options_ = {
  14802. children: ['volumeBar']
  14803. };
  14804. Component$1.registerComponent('VolumeControl', VolumeControl);
  14805. /**
  14806. * Check if muting volume is supported and if it isn't hide the mute toggle
  14807. * button.
  14808. *
  14809. * @param { import('../../component').default } self
  14810. * A reference to the mute toggle button
  14811. *
  14812. * @param { import('../../player').default } player
  14813. * A reference to the player
  14814. *
  14815. * @private
  14816. */
  14817. const checkMuteSupport = function (self, player) {
  14818. // hide mute toggle button if it's not supported by the current tech
  14819. if (player.tech_ && !player.tech_.featuresMuteControl) {
  14820. self.addClass('vjs-hidden');
  14821. }
  14822. self.on(player, 'loadstart', function () {
  14823. if (!player.tech_.featuresMuteControl) {
  14824. self.addClass('vjs-hidden');
  14825. } else {
  14826. self.removeClass('vjs-hidden');
  14827. }
  14828. });
  14829. };
  14830. /**
  14831. * @file mute-toggle.js
  14832. */
  14833. /**
  14834. * A button component for muting the audio.
  14835. *
  14836. * @extends Button
  14837. */
  14838. class MuteToggle extends Button {
  14839. /**
  14840. * Creates an instance of this class.
  14841. *
  14842. * @param { import('./player').default } player
  14843. * The `Player` that this class should be attached to.
  14844. *
  14845. * @param {Object} [options]
  14846. * The key/value store of player options.
  14847. */
  14848. constructor(player, options) {
  14849. super(player, options);
  14850. // hide this control if volume support is missing
  14851. checkMuteSupport(this, player);
  14852. this.on(player, ['loadstart', 'volumechange'], e => this.update(e));
  14853. }
  14854. /**
  14855. * Builds the default DOM `className`.
  14856. *
  14857. * @return {string}
  14858. * The DOM `className` for this object.
  14859. */
  14860. buildCSSClass() {
  14861. return `vjs-mute-control ${super.buildCSSClass()}`;
  14862. }
  14863. /**
  14864. * This gets called when an `MuteToggle` is "clicked". See
  14865. * {@link ClickableComponent} for more detailed information on what a click can be.
  14866. *
  14867. * @param {Event} [event]
  14868. * The `keydown`, `tap`, or `click` event that caused this function to be
  14869. * called.
  14870. *
  14871. * @listens tap
  14872. * @listens click
  14873. */
  14874. handleClick(event) {
  14875. const vol = this.player_.volume();
  14876. const lastVolume = this.player_.lastVolume_();
  14877. if (vol === 0) {
  14878. const volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
  14879. this.player_.volume(volumeToSet);
  14880. this.player_.muted(false);
  14881. } else {
  14882. this.player_.muted(this.player_.muted() ? false : true);
  14883. }
  14884. }
  14885. /**
  14886. * Update the `MuteToggle` button based on the state of `volume` and `muted`
  14887. * on the player.
  14888. *
  14889. * @param {Event} [event]
  14890. * The {@link Player#loadstart} event if this function was called
  14891. * through an event.
  14892. *
  14893. * @listens Player#loadstart
  14894. * @listens Player#volumechange
  14895. */
  14896. update(event) {
  14897. this.updateIcon_();
  14898. this.updateControlText_();
  14899. }
  14900. /**
  14901. * Update the appearance of the `MuteToggle` icon.
  14902. *
  14903. * Possible states (given `level` variable below):
  14904. * - 0: crossed out
  14905. * - 1: zero bars of volume
  14906. * - 2: one bar of volume
  14907. * - 3: two bars of volume
  14908. *
  14909. * @private
  14910. */
  14911. updateIcon_() {
  14912. const vol = this.player_.volume();
  14913. let level = 3;
  14914. // in iOS when a player is loaded with muted attribute
  14915. // and volume is changed with a native mute button
  14916. // we want to make sure muted state is updated
  14917. if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {
  14918. this.player_.muted(this.player_.tech_.el_.muted);
  14919. }
  14920. if (vol === 0 || this.player_.muted()) {
  14921. level = 0;
  14922. } else if (vol < 0.33) {
  14923. level = 1;
  14924. } else if (vol < 0.67) {
  14925. level = 2;
  14926. }
  14927. removeClass(this.el_, [0, 1, 2, 3].reduce((str, i) => str + `${i ? ' ' : ''}vjs-vol-${i}`, ''));
  14928. addClass(this.el_, `vjs-vol-${level}`);
  14929. }
  14930. /**
  14931. * If `muted` has changed on the player, update the control text
  14932. * (`title` attribute on `vjs-mute-control` element and content of
  14933. * `vjs-control-text` element).
  14934. *
  14935. * @private
  14936. */
  14937. updateControlText_() {
  14938. const soundOff = this.player_.muted() || this.player_.volume() === 0;
  14939. const text = soundOff ? 'Unmute' : 'Mute';
  14940. if (this.controlText() !== text) {
  14941. this.controlText(text);
  14942. }
  14943. }
  14944. }
  14945. /**
  14946. * The text that should display over the `MuteToggle`s controls. Added for localization.
  14947. *
  14948. * @type {string}
  14949. * @protected
  14950. */
  14951. MuteToggle.prototype.controlText_ = 'Mute';
  14952. Component$1.registerComponent('MuteToggle', MuteToggle);
  14953. /**
  14954. * @file volume-control.js
  14955. */
  14956. /**
  14957. * A Component to contain the MuteToggle and VolumeControl so that
  14958. * they can work together.
  14959. *
  14960. * @extends Component
  14961. */
  14962. class VolumePanel extends Component$1 {
  14963. /**
  14964. * Creates an instance of this class.
  14965. *
  14966. * @param { import('./player').default } player
  14967. * The `Player` that this class should be attached to.
  14968. *
  14969. * @param {Object} [options={}]
  14970. * The key/value store of player options.
  14971. */
  14972. constructor(player, options = {}) {
  14973. if (typeof options.inline !== 'undefined') {
  14974. options.inline = options.inline;
  14975. } else {
  14976. options.inline = true;
  14977. }
  14978. // pass the inline option down to the VolumeControl as vertical if
  14979. // the VolumeControl is on.
  14980. if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {
  14981. options.volumeControl = options.volumeControl || {};
  14982. options.volumeControl.vertical = !options.inline;
  14983. }
  14984. super(player, options);
  14985. // this handler is used by mouse handler methods below
  14986. this.handleKeyPressHandler_ = e => this.handleKeyPress(e);
  14987. this.on(player, ['loadstart'], e => this.volumePanelState_(e));
  14988. this.on(this.muteToggle, 'keyup', e => this.handleKeyPress(e));
  14989. this.on(this.volumeControl, 'keyup', e => this.handleVolumeControlKeyUp(e));
  14990. this.on('keydown', e => this.handleKeyPress(e));
  14991. this.on('mouseover', e => this.handleMouseOver(e));
  14992. this.on('mouseout', e => this.handleMouseOut(e));
  14993. // while the slider is active (the mouse has been pressed down and
  14994. // is dragging) we do not want to hide the VolumeBar
  14995. this.on(this.volumeControl, ['slideractive'], this.sliderActive_);
  14996. this.on(this.volumeControl, ['sliderinactive'], this.sliderInactive_);
  14997. }
  14998. /**
  14999. * Add vjs-slider-active class to the VolumePanel
  15000. *
  15001. * @listens VolumeControl#slideractive
  15002. * @private
  15003. */
  15004. sliderActive_() {
  15005. this.addClass('vjs-slider-active');
  15006. }
  15007. /**
  15008. * Removes vjs-slider-active class to the VolumePanel
  15009. *
  15010. * @listens VolumeControl#sliderinactive
  15011. * @private
  15012. */
  15013. sliderInactive_() {
  15014. this.removeClass('vjs-slider-active');
  15015. }
  15016. /**
  15017. * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel
  15018. * depending on MuteToggle and VolumeControl state
  15019. *
  15020. * @listens Player#loadstart
  15021. * @private
  15022. */
  15023. volumePanelState_() {
  15024. // hide volume panel if neither volume control or mute toggle
  15025. // are displayed
  15026. if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {
  15027. this.addClass('vjs-hidden');
  15028. }
  15029. // if only mute toggle is visible we don't want
  15030. // volume panel expanding when hovered or active
  15031. if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {
  15032. this.addClass('vjs-mute-toggle-only');
  15033. }
  15034. }
  15035. /**
  15036. * Create the `Component`'s DOM element
  15037. *
  15038. * @return {Element}
  15039. * The element that was created.
  15040. */
  15041. createEl() {
  15042. let orientationClass = 'vjs-volume-panel-horizontal';
  15043. if (!this.options_.inline) {
  15044. orientationClass = 'vjs-volume-panel-vertical';
  15045. }
  15046. return super.createEl('div', {
  15047. className: `vjs-volume-panel vjs-control ${orientationClass}`
  15048. });
  15049. }
  15050. /**
  15051. * Dispose of the `volume-panel` and all child components.
  15052. */
  15053. dispose() {
  15054. this.handleMouseOut();
  15055. super.dispose();
  15056. }
  15057. /**
  15058. * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes
  15059. * the volume panel and sets focus on `MuteToggle`.
  15060. *
  15061. * @param {Event} event
  15062. * The `keyup` event that caused this function to be called.
  15063. *
  15064. * @listens keyup
  15065. */
  15066. handleVolumeControlKeyUp(event) {
  15067. if (keycode.isEventKey(event, 'Esc')) {
  15068. this.muteToggle.focus();
  15069. }
  15070. }
  15071. /**
  15072. * This gets called when a `VolumePanel` gains hover via a `mouseover` event.
  15073. * Turns on listening for `mouseover` event. When they happen it
  15074. * calls `this.handleMouseOver`.
  15075. *
  15076. * @param {Event} event
  15077. * The `mouseover` event that caused this function to be called.
  15078. *
  15079. * @listens mouseover
  15080. */
  15081. handleMouseOver(event) {
  15082. this.addClass('vjs-hover');
  15083. on(document, 'keyup', this.handleKeyPressHandler_);
  15084. }
  15085. /**
  15086. * This gets called when a `VolumePanel` gains hover via a `mouseout` event.
  15087. * Turns on listening for `mouseout` event. When they happen it
  15088. * calls `this.handleMouseOut`.
  15089. *
  15090. * @param {Event} event
  15091. * The `mouseout` event that caused this function to be called.
  15092. *
  15093. * @listens mouseout
  15094. */
  15095. handleMouseOut(event) {
  15096. this.removeClass('vjs-hover');
  15097. off(document, 'keyup', this.handleKeyPressHandler_);
  15098. }
  15099. /**
  15100. * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`,
  15101. * looking for ESC, which hides the `VolumeControl`.
  15102. *
  15103. * @param {Event} event
  15104. * The keypress that triggered this event.
  15105. *
  15106. * @listens keydown | keyup
  15107. */
  15108. handleKeyPress(event) {
  15109. if (keycode.isEventKey(event, 'Esc')) {
  15110. this.handleMouseOut();
  15111. }
  15112. }
  15113. }
  15114. /**
  15115. * Default options for the `VolumeControl`
  15116. *
  15117. * @type {Object}
  15118. * @private
  15119. */
  15120. VolumePanel.prototype.options_ = {
  15121. children: ['muteToggle', 'volumeControl']
  15122. };
  15123. Component$1.registerComponent('VolumePanel', VolumePanel);
  15124. /**
  15125. * Button to skip forward a configurable amount of time
  15126. * through a video. Renders in the control bar.
  15127. *
  15128. * e.g. options: {controlBar: {skipButtons: forward: 5}}
  15129. *
  15130. * @extends Button
  15131. */
  15132. class SkipForward extends Button {
  15133. constructor(player, options) {
  15134. super(player, options);
  15135. this.validOptions = [5, 10, 30];
  15136. this.skipTime = this.getSkipForwardTime();
  15137. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  15138. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  15139. this.show();
  15140. } else {
  15141. this.hide();
  15142. }
  15143. }
  15144. getSkipForwardTime() {
  15145. const playerOptions = this.options_.playerOptions;
  15146. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.forward;
  15147. }
  15148. buildCSSClass() {
  15149. return `vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`;
  15150. }
  15151. /**
  15152. * On click, skips forward in the duration/seekable range by a configurable amount of seconds.
  15153. * If the time left in the duration/seekable range is less than the configured 'skip forward' time,
  15154. * skips to end of duration/seekable range.
  15155. *
  15156. * Handle a click on a `SkipForward` button
  15157. *
  15158. * @param {EventTarget~Event} event
  15159. * The `click` event that caused this function
  15160. * to be called
  15161. */
  15162. handleClick(event) {
  15163. const currentVideoTime = this.player_.currentTime();
  15164. const liveTracker = this.player_.liveTracker;
  15165. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  15166. let newTime;
  15167. if (currentVideoTime + this.skipTime <= duration) {
  15168. newTime = currentVideoTime + this.skipTime;
  15169. } else {
  15170. newTime = duration;
  15171. }
  15172. this.player_.currentTime(newTime);
  15173. }
  15174. /**
  15175. * Update control text on languagechange
  15176. */
  15177. handleLanguagechange() {
  15178. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  15179. }
  15180. }
  15181. Component$1.registerComponent('SkipForward', SkipForward);
  15182. /**
  15183. * Button to skip backward a configurable amount of time
  15184. * through a video. Renders in the control bar.
  15185. *
  15186. * * e.g. options: {controlBar: {skipButtons: backward: 5}}
  15187. *
  15188. * @extends Button
  15189. */
  15190. class SkipBackward extends Button {
  15191. constructor(player, options) {
  15192. super(player, options);
  15193. this.validOptions = [5, 10, 30];
  15194. this.skipTime = this.getSkipBackwardTime();
  15195. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  15196. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  15197. this.show();
  15198. } else {
  15199. this.hide();
  15200. }
  15201. }
  15202. getSkipBackwardTime() {
  15203. const playerOptions = this.options_.playerOptions;
  15204. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.backward;
  15205. }
  15206. buildCSSClass() {
  15207. return `vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`;
  15208. }
  15209. /**
  15210. * On click, skips backward in the video by a configurable amount of seconds.
  15211. * If the current time in the video is less than the configured 'skip backward' time,
  15212. * skips to beginning of video or seekable range.
  15213. *
  15214. * Handle a click on a `SkipBackward` button
  15215. *
  15216. * @param {EventTarget~Event} event
  15217. * The `click` event that caused this function
  15218. * to be called
  15219. */
  15220. handleClick(event) {
  15221. const currentVideoTime = this.player_.currentTime();
  15222. const liveTracker = this.player_.liveTracker;
  15223. const seekableStart = liveTracker && liveTracker.isLive() && liveTracker.seekableStart();
  15224. let newTime;
  15225. if (seekableStart && currentVideoTime - this.skipTime <= seekableStart) {
  15226. newTime = seekableStart;
  15227. } else if (currentVideoTime >= this.skipTime) {
  15228. newTime = currentVideoTime - this.skipTime;
  15229. } else {
  15230. newTime = 0;
  15231. }
  15232. this.player_.currentTime(newTime);
  15233. }
  15234. /**
  15235. * Update control text on languagechange
  15236. */
  15237. handleLanguagechange() {
  15238. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  15239. }
  15240. }
  15241. SkipBackward.prototype.controlText_ = 'Skip Backward';
  15242. Component$1.registerComponent('SkipBackward', SkipBackward);
  15243. /**
  15244. * @file menu.js
  15245. */
  15246. /**
  15247. * The Menu component is used to build popup menus, including subtitle and
  15248. * captions selection menus.
  15249. *
  15250. * @extends Component
  15251. */
  15252. class Menu extends Component$1 {
  15253. /**
  15254. * Create an instance of this class.
  15255. *
  15256. * @param { import('../player').default } player
  15257. * the player that this component should attach to
  15258. *
  15259. * @param {Object} [options]
  15260. * Object of option names and values
  15261. *
  15262. */
  15263. constructor(player, options) {
  15264. super(player, options);
  15265. if (options) {
  15266. this.menuButton_ = options.menuButton;
  15267. }
  15268. this.focusedChild_ = -1;
  15269. this.on('keydown', e => this.handleKeyDown(e));
  15270. // All the menu item instances share the same blur handler provided by the menu container.
  15271. this.boundHandleBlur_ = e => this.handleBlur(e);
  15272. this.boundHandleTapClick_ = e => this.handleTapClick(e);
  15273. }
  15274. /**
  15275. * Add event listeners to the {@link MenuItem}.
  15276. *
  15277. * @param {Object} component
  15278. * The instance of the `MenuItem` to add listeners to.
  15279. *
  15280. */
  15281. addEventListenerForItem(component) {
  15282. if (!(component instanceof Component$1)) {
  15283. return;
  15284. }
  15285. this.on(component, 'blur', this.boundHandleBlur_);
  15286. this.on(component, ['tap', 'click'], this.boundHandleTapClick_);
  15287. }
  15288. /**
  15289. * Remove event listeners from the {@link MenuItem}.
  15290. *
  15291. * @param {Object} component
  15292. * The instance of the `MenuItem` to remove listeners.
  15293. *
  15294. */
  15295. removeEventListenerForItem(component) {
  15296. if (!(component instanceof Component$1)) {
  15297. return;
  15298. }
  15299. this.off(component, 'blur', this.boundHandleBlur_);
  15300. this.off(component, ['tap', 'click'], this.boundHandleTapClick_);
  15301. }
  15302. /**
  15303. * This method will be called indirectly when the component has been added
  15304. * before the component adds to the new menu instance by `addItem`.
  15305. * In this case, the original menu instance will remove the component
  15306. * by calling `removeChild`.
  15307. *
  15308. * @param {Object} component
  15309. * The instance of the `MenuItem`
  15310. */
  15311. removeChild(component) {
  15312. if (typeof component === 'string') {
  15313. component = this.getChild(component);
  15314. }
  15315. this.removeEventListenerForItem(component);
  15316. super.removeChild(component);
  15317. }
  15318. /**
  15319. * Add a {@link MenuItem} to the menu.
  15320. *
  15321. * @param {Object|string} component
  15322. * The name or instance of the `MenuItem` to add.
  15323. *
  15324. */
  15325. addItem(component) {
  15326. const childComponent = this.addChild(component);
  15327. if (childComponent) {
  15328. this.addEventListenerForItem(childComponent);
  15329. }
  15330. }
  15331. /**
  15332. * Create the `Menu`s DOM element.
  15333. *
  15334. * @return {Element}
  15335. * the element that was created
  15336. */
  15337. createEl() {
  15338. const contentElType = this.options_.contentElType || 'ul';
  15339. this.contentEl_ = createEl(contentElType, {
  15340. className: 'vjs-menu-content'
  15341. });
  15342. this.contentEl_.setAttribute('role', 'menu');
  15343. const el = super.createEl('div', {
  15344. append: this.contentEl_,
  15345. className: 'vjs-menu'
  15346. });
  15347. el.appendChild(this.contentEl_);
  15348. // Prevent clicks from bubbling up. Needed for Menu Buttons,
  15349. // where a click on the parent is significant
  15350. on(el, 'click', function (event) {
  15351. event.preventDefault();
  15352. event.stopImmediatePropagation();
  15353. });
  15354. return el;
  15355. }
  15356. dispose() {
  15357. this.contentEl_ = null;
  15358. this.boundHandleBlur_ = null;
  15359. this.boundHandleTapClick_ = null;
  15360. super.dispose();
  15361. }
  15362. /**
  15363. * Called when a `MenuItem` loses focus.
  15364. *
  15365. * @param {Event} event
  15366. * The `blur` event that caused this function to be called.
  15367. *
  15368. * @listens blur
  15369. */
  15370. handleBlur(event) {
  15371. const relatedTarget = event.relatedTarget || document.activeElement;
  15372. // Close menu popup when a user clicks outside the menu
  15373. if (!this.children().some(element => {
  15374. return element.el() === relatedTarget;
  15375. })) {
  15376. const btn = this.menuButton_;
  15377. if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {
  15378. btn.unpressButton();
  15379. }
  15380. }
  15381. }
  15382. /**
  15383. * Called when a `MenuItem` gets clicked or tapped.
  15384. *
  15385. * @param {Event} event
  15386. * The `click` or `tap` event that caused this function to be called.
  15387. *
  15388. * @listens click,tap
  15389. */
  15390. handleTapClick(event) {
  15391. // Unpress the associated MenuButton, and move focus back to it
  15392. if (this.menuButton_) {
  15393. this.menuButton_.unpressButton();
  15394. const childComponents = this.children();
  15395. if (!Array.isArray(childComponents)) {
  15396. return;
  15397. }
  15398. const foundComponent = childComponents.filter(component => component.el() === event.target)[0];
  15399. if (!foundComponent) {
  15400. return;
  15401. }
  15402. // don't focus menu button if item is a caption settings item
  15403. // because focus will move elsewhere
  15404. if (foundComponent.name() !== 'CaptionSettingsMenuItem') {
  15405. this.menuButton_.focus();
  15406. }
  15407. }
  15408. }
  15409. /**
  15410. * Handle a `keydown` event on this menu. This listener is added in the constructor.
  15411. *
  15412. * @param {Event} event
  15413. * A `keydown` event that happened on the menu.
  15414. *
  15415. * @listens keydown
  15416. */
  15417. handleKeyDown(event) {
  15418. // Left and Down Arrows
  15419. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  15420. event.preventDefault();
  15421. event.stopPropagation();
  15422. this.stepForward();
  15423. // Up and Right Arrows
  15424. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  15425. event.preventDefault();
  15426. event.stopPropagation();
  15427. this.stepBack();
  15428. }
  15429. }
  15430. /**
  15431. * Move to next (lower) menu item for keyboard users.
  15432. */
  15433. stepForward() {
  15434. let stepChild = 0;
  15435. if (this.focusedChild_ !== undefined) {
  15436. stepChild = this.focusedChild_ + 1;
  15437. }
  15438. this.focus(stepChild);
  15439. }
  15440. /**
  15441. * Move to previous (higher) menu item for keyboard users.
  15442. */
  15443. stepBack() {
  15444. let stepChild = 0;
  15445. if (this.focusedChild_ !== undefined) {
  15446. stepChild = this.focusedChild_ - 1;
  15447. }
  15448. this.focus(stepChild);
  15449. }
  15450. /**
  15451. * Set focus on a {@link MenuItem} in the `Menu`.
  15452. *
  15453. * @param {Object|string} [item=0]
  15454. * Index of child item set focus on.
  15455. */
  15456. focus(item = 0) {
  15457. const children = this.children().slice();
  15458. const haveTitle = children.length && children[0].hasClass('vjs-menu-title');
  15459. if (haveTitle) {
  15460. children.shift();
  15461. }
  15462. if (children.length > 0) {
  15463. if (item < 0) {
  15464. item = 0;
  15465. } else if (item >= children.length) {
  15466. item = children.length - 1;
  15467. }
  15468. this.focusedChild_ = item;
  15469. children[item].el_.focus();
  15470. }
  15471. }
  15472. }
  15473. Component$1.registerComponent('Menu', Menu);
  15474. /**
  15475. * @file menu-button.js
  15476. */
  15477. /**
  15478. * A `MenuButton` class for any popup {@link Menu}.
  15479. *
  15480. * @extends Component
  15481. */
  15482. class MenuButton extends Component$1 {
  15483. /**
  15484. * Creates an instance of this class.
  15485. *
  15486. * @param { import('../player').default } player
  15487. * The `Player` that this class should be attached to.
  15488. *
  15489. * @param {Object} [options={}]
  15490. * The key/value store of player options.
  15491. */
  15492. constructor(player, options = {}) {
  15493. super(player, options);
  15494. this.menuButton_ = new Button(player, options);
  15495. this.menuButton_.controlText(this.controlText_);
  15496. this.menuButton_.el_.setAttribute('aria-haspopup', 'true');
  15497. // Add buildCSSClass values to the button, not the wrapper
  15498. const buttonClass = Button.prototype.buildCSSClass();
  15499. this.menuButton_.el_.className = this.buildCSSClass() + ' ' + buttonClass;
  15500. this.menuButton_.removeClass('vjs-control');
  15501. this.addChild(this.menuButton_);
  15502. this.update();
  15503. this.enabled_ = true;
  15504. const handleClick = e => this.handleClick(e);
  15505. this.handleMenuKeyUp_ = e => this.handleMenuKeyUp(e);
  15506. this.on(this.menuButton_, 'tap', handleClick);
  15507. this.on(this.menuButton_, 'click', handleClick);
  15508. this.on(this.menuButton_, 'keydown', e => this.handleKeyDown(e));
  15509. this.on(this.menuButton_, 'mouseenter', () => {
  15510. this.addClass('vjs-hover');
  15511. this.menu.show();
  15512. on(document, 'keyup', this.handleMenuKeyUp_);
  15513. });
  15514. this.on('mouseleave', e => this.handleMouseLeave(e));
  15515. this.on('keydown', e => this.handleSubmenuKeyDown(e));
  15516. }
  15517. /**
  15518. * Update the menu based on the current state of its items.
  15519. */
  15520. update() {
  15521. const menu = this.createMenu();
  15522. if (this.menu) {
  15523. this.menu.dispose();
  15524. this.removeChild(this.menu);
  15525. }
  15526. this.menu = menu;
  15527. this.addChild(menu);
  15528. /**
  15529. * Track the state of the menu button
  15530. *
  15531. * @type {Boolean}
  15532. * @private
  15533. */
  15534. this.buttonPressed_ = false;
  15535. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  15536. if (this.items && this.items.length <= this.hideThreshold_) {
  15537. this.hide();
  15538. this.menu.contentEl_.removeAttribute('role');
  15539. } else {
  15540. this.show();
  15541. this.menu.contentEl_.setAttribute('role', 'menu');
  15542. }
  15543. }
  15544. /**
  15545. * Create the menu and add all items to it.
  15546. *
  15547. * @return {Menu}
  15548. * The constructed menu
  15549. */
  15550. createMenu() {
  15551. const menu = new Menu(this.player_, {
  15552. menuButton: this
  15553. });
  15554. /**
  15555. * Hide the menu if the number of items is less than or equal to this threshold. This defaults
  15556. * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list
  15557. * it here because every time we run `createMenu` we need to reset the value.
  15558. *
  15559. * @protected
  15560. * @type {Number}
  15561. */
  15562. this.hideThreshold_ = 0;
  15563. // Add a title list item to the top
  15564. if (this.options_.title) {
  15565. const titleEl = createEl('li', {
  15566. className: 'vjs-menu-title',
  15567. textContent: toTitleCase$1(this.options_.title),
  15568. tabIndex: -1
  15569. });
  15570. const titleComponent = new Component$1(this.player_, {
  15571. el: titleEl
  15572. });
  15573. menu.addItem(titleComponent);
  15574. }
  15575. this.items = this.createItems();
  15576. if (this.items) {
  15577. // Add menu items to the menu
  15578. for (let i = 0; i < this.items.length; i++) {
  15579. menu.addItem(this.items[i]);
  15580. }
  15581. }
  15582. return menu;
  15583. }
  15584. /**
  15585. * Create the list of menu items. Specific to each subclass.
  15586. *
  15587. * @abstract
  15588. */
  15589. createItems() {}
  15590. /**
  15591. * Create the `MenuButtons`s DOM element.
  15592. *
  15593. * @return {Element}
  15594. * The element that gets created.
  15595. */
  15596. createEl() {
  15597. return super.createEl('div', {
  15598. className: this.buildWrapperCSSClass()
  15599. }, {});
  15600. }
  15601. /**
  15602. * Allow sub components to stack CSS class names for the wrapper element
  15603. *
  15604. * @return {string}
  15605. * The constructed wrapper DOM `className`
  15606. */
  15607. buildWrapperCSSClass() {
  15608. let menuButtonClass = 'vjs-menu-button';
  15609. // If the inline option is passed, we want to use different styles altogether.
  15610. if (this.options_.inline === true) {
  15611. menuButtonClass += '-inline';
  15612. } else {
  15613. menuButtonClass += '-popup';
  15614. }
  15615. // TODO: Fix the CSS so that this isn't necessary
  15616. const buttonClass = Button.prototype.buildCSSClass();
  15617. return `vjs-menu-button ${menuButtonClass} ${buttonClass} ${super.buildCSSClass()}`;
  15618. }
  15619. /**
  15620. * Builds the default DOM `className`.
  15621. *
  15622. * @return {string}
  15623. * The DOM `className` for this object.
  15624. */
  15625. buildCSSClass() {
  15626. let menuButtonClass = 'vjs-menu-button';
  15627. // If the inline option is passed, we want to use different styles altogether.
  15628. if (this.options_.inline === true) {
  15629. menuButtonClass += '-inline';
  15630. } else {
  15631. menuButtonClass += '-popup';
  15632. }
  15633. return `vjs-menu-button ${menuButtonClass} ${super.buildCSSClass()}`;
  15634. }
  15635. /**
  15636. * Get or set the localized control text that will be used for accessibility.
  15637. *
  15638. * > NOTE: This will come from the internal `menuButton_` element.
  15639. *
  15640. * @param {string} [text]
  15641. * Control text for element.
  15642. *
  15643. * @param {Element} [el=this.menuButton_.el()]
  15644. * Element to set the title on.
  15645. *
  15646. * @return {string}
  15647. * - The control text when getting
  15648. */
  15649. controlText(text, el = this.menuButton_.el()) {
  15650. return this.menuButton_.controlText(text, el);
  15651. }
  15652. /**
  15653. * Dispose of the `menu-button` and all child components.
  15654. */
  15655. dispose() {
  15656. this.handleMouseLeave();
  15657. super.dispose();
  15658. }
  15659. /**
  15660. * Handle a click on a `MenuButton`.
  15661. * See {@link ClickableComponent#handleClick} for instances where this is called.
  15662. *
  15663. * @param {Event} event
  15664. * The `keydown`, `tap`, or `click` event that caused this function to be
  15665. * called.
  15666. *
  15667. * @listens tap
  15668. * @listens click
  15669. */
  15670. handleClick(event) {
  15671. if (this.buttonPressed_) {
  15672. this.unpressButton();
  15673. } else {
  15674. this.pressButton();
  15675. }
  15676. }
  15677. /**
  15678. * Handle `mouseleave` for `MenuButton`.
  15679. *
  15680. * @param {Event} event
  15681. * The `mouseleave` event that caused this function to be called.
  15682. *
  15683. * @listens mouseleave
  15684. */
  15685. handleMouseLeave(event) {
  15686. this.removeClass('vjs-hover');
  15687. off(document, 'keyup', this.handleMenuKeyUp_);
  15688. }
  15689. /**
  15690. * Set the focus to the actual button, not to this element
  15691. */
  15692. focus() {
  15693. this.menuButton_.focus();
  15694. }
  15695. /**
  15696. * Remove the focus from the actual button, not this element
  15697. */
  15698. blur() {
  15699. this.menuButton_.blur();
  15700. }
  15701. /**
  15702. * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See
  15703. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  15704. *
  15705. * @param {Event} event
  15706. * The `keydown` event that caused this function to be called.
  15707. *
  15708. * @listens keydown
  15709. */
  15710. handleKeyDown(event) {
  15711. // Escape or Tab unpress the 'button'
  15712. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  15713. if (this.buttonPressed_) {
  15714. this.unpressButton();
  15715. }
  15716. // Don't preventDefault for Tab key - we still want to lose focus
  15717. if (!keycode.isEventKey(event, 'Tab')) {
  15718. event.preventDefault();
  15719. // Set focus back to the menu button's button
  15720. this.menuButton_.focus();
  15721. }
  15722. // Up Arrow or Down Arrow also 'press' the button to open the menu
  15723. } else if (keycode.isEventKey(event, 'Up') || keycode.isEventKey(event, 'Down')) {
  15724. if (!this.buttonPressed_) {
  15725. event.preventDefault();
  15726. this.pressButton();
  15727. }
  15728. }
  15729. }
  15730. /**
  15731. * Handle a `keyup` event on a `MenuButton`. The listener for this is added in
  15732. * the constructor.
  15733. *
  15734. * @param {Event} event
  15735. * Key press event
  15736. *
  15737. * @listens keyup
  15738. */
  15739. handleMenuKeyUp(event) {
  15740. // Escape hides popup menu
  15741. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  15742. this.removeClass('vjs-hover');
  15743. }
  15744. }
  15745. /**
  15746. * This method name now delegates to `handleSubmenuKeyDown`. This means
  15747. * anyone calling `handleSubmenuKeyPress` will not see their method calls
  15748. * stop working.
  15749. *
  15750. * @param {Event} event
  15751. * The event that caused this function to be called.
  15752. */
  15753. handleSubmenuKeyPress(event) {
  15754. this.handleSubmenuKeyDown(event);
  15755. }
  15756. /**
  15757. * Handle a `keydown` event on a sub-menu. The listener for this is added in
  15758. * the constructor.
  15759. *
  15760. * @param {Event} event
  15761. * Key press event
  15762. *
  15763. * @listens keydown
  15764. */
  15765. handleSubmenuKeyDown(event) {
  15766. // Escape or Tab unpress the 'button'
  15767. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  15768. if (this.buttonPressed_) {
  15769. this.unpressButton();
  15770. }
  15771. // Don't preventDefault for Tab key - we still want to lose focus
  15772. if (!keycode.isEventKey(event, 'Tab')) {
  15773. event.preventDefault();
  15774. // Set focus back to the menu button's button
  15775. this.menuButton_.focus();
  15776. }
  15777. }
  15778. }
  15779. /**
  15780. * Put the current `MenuButton` into a pressed state.
  15781. */
  15782. pressButton() {
  15783. if (this.enabled_) {
  15784. this.buttonPressed_ = true;
  15785. this.menu.show();
  15786. this.menu.lockShowing();
  15787. this.menuButton_.el_.setAttribute('aria-expanded', 'true');
  15788. // set the focus into the submenu, except on iOS where it is resulting in
  15789. // undesired scrolling behavior when the player is in an iframe
  15790. if (IS_IOS && isInFrame()) {
  15791. // Return early so that the menu isn't focused
  15792. return;
  15793. }
  15794. this.menu.focus();
  15795. }
  15796. }
  15797. /**
  15798. * Take the current `MenuButton` out of a pressed state.
  15799. */
  15800. unpressButton() {
  15801. if (this.enabled_) {
  15802. this.buttonPressed_ = false;
  15803. this.menu.unlockShowing();
  15804. this.menu.hide();
  15805. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  15806. }
  15807. }
  15808. /**
  15809. * Disable the `MenuButton`. Don't allow it to be clicked.
  15810. */
  15811. disable() {
  15812. this.unpressButton();
  15813. this.enabled_ = false;
  15814. this.addClass('vjs-disabled');
  15815. this.menuButton_.disable();
  15816. }
  15817. /**
  15818. * Enable the `MenuButton`. Allow it to be clicked.
  15819. */
  15820. enable() {
  15821. this.enabled_ = true;
  15822. this.removeClass('vjs-disabled');
  15823. this.menuButton_.enable();
  15824. }
  15825. }
  15826. Component$1.registerComponent('MenuButton', MenuButton);
  15827. /**
  15828. * @file track-button.js
  15829. */
  15830. /**
  15831. * The base class for buttons that toggle specific track types (e.g. subtitles).
  15832. *
  15833. * @extends MenuButton
  15834. */
  15835. class TrackButton extends MenuButton {
  15836. /**
  15837. * Creates an instance of this class.
  15838. *
  15839. * @param { import('./player').default } player
  15840. * The `Player` that this class should be attached to.
  15841. *
  15842. * @param {Object} [options]
  15843. * The key/value store of player options.
  15844. */
  15845. constructor(player, options) {
  15846. const tracks = options.tracks;
  15847. super(player, options);
  15848. if (this.items.length <= 1) {
  15849. this.hide();
  15850. }
  15851. if (!tracks) {
  15852. return;
  15853. }
  15854. const updateHandler = bind_(this, this.update);
  15855. tracks.addEventListener('removetrack', updateHandler);
  15856. tracks.addEventListener('addtrack', updateHandler);
  15857. tracks.addEventListener('labelchange', updateHandler);
  15858. this.player_.on('ready', updateHandler);
  15859. this.player_.on('dispose', function () {
  15860. tracks.removeEventListener('removetrack', updateHandler);
  15861. tracks.removeEventListener('addtrack', updateHandler);
  15862. tracks.removeEventListener('labelchange', updateHandler);
  15863. });
  15864. }
  15865. }
  15866. Component$1.registerComponent('TrackButton', TrackButton);
  15867. /**
  15868. * @file menu-keys.js
  15869. */
  15870. /**
  15871. * All keys used for operation of a menu (`MenuButton`, `Menu`, and `MenuItem`)
  15872. * Note that 'Enter' and 'Space' are not included here (otherwise they would
  15873. * prevent the `MenuButton` and `MenuItem` from being keyboard-clickable)
  15874. *
  15875. * @typedef MenuKeys
  15876. * @array
  15877. */
  15878. const MenuKeys = ['Tab', 'Esc', 'Up', 'Down', 'Right', 'Left'];
  15879. /**
  15880. * @file menu-item.js
  15881. */
  15882. /**
  15883. * The component for a menu item. `<li>`
  15884. *
  15885. * @extends ClickableComponent
  15886. */
  15887. class MenuItem extends ClickableComponent {
  15888. /**
  15889. * Creates an instance of the this class.
  15890. *
  15891. * @param { import('../player').default } player
  15892. * The `Player` that this class should be attached to.
  15893. *
  15894. * @param {Object} [options={}]
  15895. * The key/value store of player options.
  15896. *
  15897. */
  15898. constructor(player, options) {
  15899. super(player, options);
  15900. this.selectable = options.selectable;
  15901. this.isSelected_ = options.selected || false;
  15902. this.multiSelectable = options.multiSelectable;
  15903. this.selected(this.isSelected_);
  15904. if (this.selectable) {
  15905. if (this.multiSelectable) {
  15906. this.el_.setAttribute('role', 'menuitemcheckbox');
  15907. } else {
  15908. this.el_.setAttribute('role', 'menuitemradio');
  15909. }
  15910. } else {
  15911. this.el_.setAttribute('role', 'menuitem');
  15912. }
  15913. }
  15914. /**
  15915. * Create the `MenuItem's DOM element
  15916. *
  15917. * @param {string} [type=li]
  15918. * Element's node type, not actually used, always set to `li`.
  15919. *
  15920. * @param {Object} [props={}]
  15921. * An object of properties that should be set on the element
  15922. *
  15923. * @param {Object} [attrs={}]
  15924. * An object of attributes that should be set on the element
  15925. *
  15926. * @return {Element}
  15927. * The element that gets created.
  15928. */
  15929. createEl(type, props, attrs) {
  15930. // The control is textual, not just an icon
  15931. this.nonIconControl = true;
  15932. const el = super.createEl('li', Object.assign({
  15933. className: 'vjs-menu-item',
  15934. tabIndex: -1
  15935. }, props), attrs);
  15936. // swap icon with menu item text.
  15937. el.replaceChild(createEl('span', {
  15938. className: 'vjs-menu-item-text',
  15939. textContent: this.localize(this.options_.label)
  15940. }), el.querySelector('.vjs-icon-placeholder'));
  15941. return el;
  15942. }
  15943. /**
  15944. * Ignore keys which are used by the menu, but pass any other ones up. See
  15945. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  15946. *
  15947. * @param {Event} event
  15948. * The `keydown` event that caused this function to be called.
  15949. *
  15950. * @listens keydown
  15951. */
  15952. handleKeyDown(event) {
  15953. if (!MenuKeys.some(key => keycode.isEventKey(event, key))) {
  15954. // Pass keydown handling up for unused keys
  15955. super.handleKeyDown(event);
  15956. }
  15957. }
  15958. /**
  15959. * Any click on a `MenuItem` puts it into the selected state.
  15960. * See {@link ClickableComponent#handleClick} for instances where this is called.
  15961. *
  15962. * @param {Event} event
  15963. * The `keydown`, `tap`, or `click` event that caused this function to be
  15964. * called.
  15965. *
  15966. * @listens tap
  15967. * @listens click
  15968. */
  15969. handleClick(event) {
  15970. this.selected(true);
  15971. }
  15972. /**
  15973. * Set the state for this menu item as selected or not.
  15974. *
  15975. * @param {boolean} selected
  15976. * if the menu item is selected or not
  15977. */
  15978. selected(selected) {
  15979. if (this.selectable) {
  15980. if (selected) {
  15981. this.addClass('vjs-selected');
  15982. this.el_.setAttribute('aria-checked', 'true');
  15983. // aria-checked isn't fully supported by browsers/screen readers,
  15984. // so indicate selected state to screen reader in the control text.
  15985. this.controlText(', selected');
  15986. this.isSelected_ = true;
  15987. } else {
  15988. this.removeClass('vjs-selected');
  15989. this.el_.setAttribute('aria-checked', 'false');
  15990. // Indicate un-selected state to screen reader
  15991. this.controlText('');
  15992. this.isSelected_ = false;
  15993. }
  15994. }
  15995. }
  15996. }
  15997. Component$1.registerComponent('MenuItem', MenuItem);
  15998. /**
  15999. * @file text-track-menu-item.js
  16000. */
  16001. /**
  16002. * The specific menu item type for selecting a language within a text track kind
  16003. *
  16004. * @extends MenuItem
  16005. */
  16006. class TextTrackMenuItem extends MenuItem {
  16007. /**
  16008. * Creates an instance of this class.
  16009. *
  16010. * @param { import('../../player').default } player
  16011. * The `Player` that this class should be attached to.
  16012. *
  16013. * @param {Object} [options]
  16014. * The key/value store of player options.
  16015. */
  16016. constructor(player, options) {
  16017. const track = options.track;
  16018. const tracks = player.textTracks();
  16019. // Modify options for parent MenuItem class's init.
  16020. options.label = track.label || track.language || 'Unknown';
  16021. options.selected = track.mode === 'showing';
  16022. super(player, options);
  16023. this.track = track;
  16024. // Determine the relevant kind(s) of tracks for this component and filter
  16025. // out empty kinds.
  16026. this.kinds = (options.kinds || [options.kind || this.track.kind]).filter(Boolean);
  16027. const changeHandler = (...args) => {
  16028. this.handleTracksChange.apply(this, args);
  16029. };
  16030. const selectedLanguageChangeHandler = (...args) => {
  16031. this.handleSelectedLanguageChange.apply(this, args);
  16032. };
  16033. player.on(['loadstart', 'texttrackchange'], changeHandler);
  16034. tracks.addEventListener('change', changeHandler);
  16035. tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  16036. this.on('dispose', function () {
  16037. player.off(['loadstart', 'texttrackchange'], changeHandler);
  16038. tracks.removeEventListener('change', changeHandler);
  16039. tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  16040. });
  16041. // iOS7 doesn't dispatch change events to TextTrackLists when an
  16042. // associated track's mode changes. Without something like
  16043. // Object.observe() (also not present on iOS7), it's not
  16044. // possible to detect changes to the mode attribute and polyfill
  16045. // the change event. As a poor substitute, we manually dispatch
  16046. // change events whenever the controls modify the mode.
  16047. if (tracks.onchange === undefined) {
  16048. let event;
  16049. this.on(['tap', 'click'], function () {
  16050. if (typeof window.Event !== 'object') {
  16051. // Android 2.3 throws an Illegal Constructor error for window.Event
  16052. try {
  16053. event = new window.Event('change');
  16054. } catch (err) {
  16055. // continue regardless of error
  16056. }
  16057. }
  16058. if (!event) {
  16059. event = document.createEvent('Event');
  16060. event.initEvent('change', true, true);
  16061. }
  16062. tracks.dispatchEvent(event);
  16063. });
  16064. }
  16065. // set the default state based on current tracks
  16066. this.handleTracksChange();
  16067. }
  16068. /**
  16069. * This gets called when an `TextTrackMenuItem` is "clicked". See
  16070. * {@link ClickableComponent} for more detailed information on what a click can be.
  16071. *
  16072. * @param {Event} event
  16073. * The `keydown`, `tap`, or `click` event that caused this function to be
  16074. * called.
  16075. *
  16076. * @listens tap
  16077. * @listens click
  16078. */
  16079. handleClick(event) {
  16080. const referenceTrack = this.track;
  16081. const tracks = this.player_.textTracks();
  16082. super.handleClick(event);
  16083. if (!tracks) {
  16084. return;
  16085. }
  16086. for (let i = 0; i < tracks.length; i++) {
  16087. const track = tracks[i];
  16088. // If the track from the text tracks list is not of the right kind,
  16089. // skip it. We do not want to affect tracks of incompatible kind(s).
  16090. if (this.kinds.indexOf(track.kind) === -1) {
  16091. continue;
  16092. }
  16093. // If this text track is the component's track and it is not showing,
  16094. // set it to showing.
  16095. if (track === referenceTrack) {
  16096. if (track.mode !== 'showing') {
  16097. track.mode = 'showing';
  16098. }
  16099. // If this text track is not the component's track and it is not
  16100. // disabled, set it to disabled.
  16101. } else if (track.mode !== 'disabled') {
  16102. track.mode = 'disabled';
  16103. }
  16104. }
  16105. }
  16106. /**
  16107. * Handle text track list change
  16108. *
  16109. * @param {Event} event
  16110. * The `change` event that caused this function to be called.
  16111. *
  16112. * @listens TextTrackList#change
  16113. */
  16114. handleTracksChange(event) {
  16115. const shouldBeSelected = this.track.mode === 'showing';
  16116. // Prevent redundant selected() calls because they may cause
  16117. // screen readers to read the appended control text unnecessarily
  16118. if (shouldBeSelected !== this.isSelected_) {
  16119. this.selected(shouldBeSelected);
  16120. }
  16121. }
  16122. handleSelectedLanguageChange(event) {
  16123. if (this.track.mode === 'showing') {
  16124. const selectedLanguage = this.player_.cache_.selectedLanguage;
  16125. // Don't replace the kind of track across the same language
  16126. if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
  16127. return;
  16128. }
  16129. this.player_.cache_.selectedLanguage = {
  16130. enabled: true,
  16131. language: this.track.language,
  16132. kind: this.track.kind
  16133. };
  16134. }
  16135. }
  16136. dispose() {
  16137. // remove reference to track object on dispose
  16138. this.track = null;
  16139. super.dispose();
  16140. }
  16141. }
  16142. Component$1.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
  16143. /**
  16144. * @file off-text-track-menu-item.js
  16145. */
  16146. /**
  16147. * A special menu item for turning of a specific type of text track
  16148. *
  16149. * @extends TextTrackMenuItem
  16150. */
  16151. class OffTextTrackMenuItem extends TextTrackMenuItem {
  16152. /**
  16153. * Creates an instance of this class.
  16154. *
  16155. * @param { import('../../player').default } player
  16156. * The `Player` that this class should be attached to.
  16157. *
  16158. * @param {Object} [options]
  16159. * The key/value store of player options.
  16160. */
  16161. constructor(player, options) {
  16162. // Create pseudo track info
  16163. // Requires options['kind']
  16164. options.track = {
  16165. player,
  16166. // it is no longer necessary to store `kind` or `kinds` on the track itself
  16167. // since they are now stored in the `kinds` property of all instances of
  16168. // TextTrackMenuItem, but this will remain for backwards compatibility
  16169. kind: options.kind,
  16170. kinds: options.kinds,
  16171. default: false,
  16172. mode: 'disabled'
  16173. };
  16174. if (!options.kinds) {
  16175. options.kinds = [options.kind];
  16176. }
  16177. if (options.label) {
  16178. options.track.label = options.label;
  16179. } else {
  16180. options.track.label = options.kinds.join(' and ') + ' off';
  16181. }
  16182. // MenuItem is selectable
  16183. options.selectable = true;
  16184. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  16185. options.multiSelectable = false;
  16186. super(player, options);
  16187. }
  16188. /**
  16189. * Handle text track change
  16190. *
  16191. * @param {Event} event
  16192. * The event that caused this function to run
  16193. */
  16194. handleTracksChange(event) {
  16195. const tracks = this.player().textTracks();
  16196. let shouldBeSelected = true;
  16197. for (let i = 0, l = tracks.length; i < l; i++) {
  16198. const track = tracks[i];
  16199. if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {
  16200. shouldBeSelected = false;
  16201. break;
  16202. }
  16203. }
  16204. // Prevent redundant selected() calls because they may cause
  16205. // screen readers to read the appended control text unnecessarily
  16206. if (shouldBeSelected !== this.isSelected_) {
  16207. this.selected(shouldBeSelected);
  16208. }
  16209. }
  16210. handleSelectedLanguageChange(event) {
  16211. const tracks = this.player().textTracks();
  16212. let allHidden = true;
  16213. for (let i = 0, l = tracks.length; i < l; i++) {
  16214. const track = tracks[i];
  16215. if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {
  16216. allHidden = false;
  16217. break;
  16218. }
  16219. }
  16220. if (allHidden) {
  16221. this.player_.cache_.selectedLanguage = {
  16222. enabled: false
  16223. };
  16224. }
  16225. }
  16226. /**
  16227. * Update control text and label on languagechange
  16228. */
  16229. handleLanguagechange() {
  16230. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.label);
  16231. super.handleLanguagechange();
  16232. }
  16233. }
  16234. Component$1.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
  16235. /**
  16236. * @file text-track-button.js
  16237. */
  16238. /**
  16239. * The base class for buttons that toggle specific text track types (e.g. subtitles)
  16240. *
  16241. * @extends MenuButton
  16242. */
  16243. class TextTrackButton extends TrackButton {
  16244. /**
  16245. * Creates an instance of this class.
  16246. *
  16247. * @param { import('../../player').default } player
  16248. * The `Player` that this class should be attached to.
  16249. *
  16250. * @param {Object} [options={}]
  16251. * The key/value store of player options.
  16252. */
  16253. constructor(player, options = {}) {
  16254. options.tracks = player.textTracks();
  16255. super(player, options);
  16256. }
  16257. /**
  16258. * Create a menu item for each text track
  16259. *
  16260. * @param {TextTrackMenuItem[]} [items=[]]
  16261. * Existing array of items to use during creation
  16262. *
  16263. * @return {TextTrackMenuItem[]}
  16264. * Array of menu items that were created
  16265. */
  16266. createItems(items = [], TrackMenuItem = TextTrackMenuItem) {
  16267. // Label is an override for the [track] off label
  16268. // USed to localise captions/subtitles
  16269. let label;
  16270. if (this.label_) {
  16271. label = `${this.label_} off`;
  16272. }
  16273. // Add an OFF menu item to turn all tracks off
  16274. items.push(new OffTextTrackMenuItem(this.player_, {
  16275. kinds: this.kinds_,
  16276. kind: this.kind_,
  16277. label
  16278. }));
  16279. this.hideThreshold_ += 1;
  16280. const tracks = this.player_.textTracks();
  16281. if (!Array.isArray(this.kinds_)) {
  16282. this.kinds_ = [this.kind_];
  16283. }
  16284. for (let i = 0; i < tracks.length; i++) {
  16285. const track = tracks[i];
  16286. // only add tracks that are of an appropriate kind and have a label
  16287. if (this.kinds_.indexOf(track.kind) > -1) {
  16288. const item = new TrackMenuItem(this.player_, {
  16289. track,
  16290. kinds: this.kinds_,
  16291. kind: this.kind_,
  16292. // MenuItem is selectable
  16293. selectable: true,
  16294. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  16295. multiSelectable: false
  16296. });
  16297. item.addClass(`vjs-${track.kind}-menu-item`);
  16298. items.push(item);
  16299. }
  16300. }
  16301. return items;
  16302. }
  16303. }
  16304. Component$1.registerComponent('TextTrackButton', TextTrackButton);
  16305. /**
  16306. * @file chapters-track-menu-item.js
  16307. */
  16308. /**
  16309. * The chapter track menu item
  16310. *
  16311. * @extends MenuItem
  16312. */
  16313. class ChaptersTrackMenuItem extends MenuItem {
  16314. /**
  16315. * Creates an instance of this class.
  16316. *
  16317. * @param { import('../../player').default } player
  16318. * The `Player` that this class should be attached to.
  16319. *
  16320. * @param {Object} [options]
  16321. * The key/value store of player options.
  16322. */
  16323. constructor(player, options) {
  16324. const track = options.track;
  16325. const cue = options.cue;
  16326. const currentTime = player.currentTime();
  16327. // Modify options for parent MenuItem class's init.
  16328. options.selectable = true;
  16329. options.multiSelectable = false;
  16330. options.label = cue.text;
  16331. options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
  16332. super(player, options);
  16333. this.track = track;
  16334. this.cue = cue;
  16335. }
  16336. /**
  16337. * This gets called when an `ChaptersTrackMenuItem` is "clicked". See
  16338. * {@link ClickableComponent} for more detailed information on what a click can be.
  16339. *
  16340. * @param {Event} [event]
  16341. * The `keydown`, `tap`, or `click` event that caused this function to be
  16342. * called.
  16343. *
  16344. * @listens tap
  16345. * @listens click
  16346. */
  16347. handleClick(event) {
  16348. super.handleClick();
  16349. this.player_.currentTime(this.cue.startTime);
  16350. }
  16351. }
  16352. Component$1.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
  16353. /**
  16354. * @file chapters-button.js
  16355. */
  16356. /**
  16357. * The button component for toggling and selecting chapters
  16358. * Chapters act much differently than other text tracks
  16359. * Cues are navigation vs. other tracks of alternative languages
  16360. *
  16361. * @extends TextTrackButton
  16362. */
  16363. class ChaptersButton extends TextTrackButton {
  16364. /**
  16365. * Creates an instance of this class.
  16366. *
  16367. * @param { import('../../player').default } player
  16368. * The `Player` that this class should be attached to.
  16369. *
  16370. * @param {Object} [options]
  16371. * The key/value store of player options.
  16372. *
  16373. * @param {Function} [ready]
  16374. * The function to call when this function is ready.
  16375. */
  16376. constructor(player, options, ready) {
  16377. super(player, options, ready);
  16378. this.selectCurrentItem_ = () => {
  16379. this.items.forEach(item => {
  16380. item.selected(this.track_.activeCues[0] === item.cue);
  16381. });
  16382. };
  16383. }
  16384. /**
  16385. * Builds the default DOM `className`.
  16386. *
  16387. * @return {string}
  16388. * The DOM `className` for this object.
  16389. */
  16390. buildCSSClass() {
  16391. return `vjs-chapters-button ${super.buildCSSClass()}`;
  16392. }
  16393. buildWrapperCSSClass() {
  16394. return `vjs-chapters-button ${super.buildWrapperCSSClass()}`;
  16395. }
  16396. /**
  16397. * Update the menu based on the current state of its items.
  16398. *
  16399. * @param {Event} [event]
  16400. * An event that triggered this function to run.
  16401. *
  16402. * @listens TextTrackList#addtrack
  16403. * @listens TextTrackList#removetrack
  16404. * @listens TextTrackList#change
  16405. */
  16406. update(event) {
  16407. if (event && event.track && event.track.kind !== 'chapters') {
  16408. return;
  16409. }
  16410. const track = this.findChaptersTrack();
  16411. if (track !== this.track_) {
  16412. this.setTrack(track);
  16413. super.update();
  16414. } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
  16415. // Update the menu initially or if the number of cues has changed since set
  16416. super.update();
  16417. }
  16418. }
  16419. /**
  16420. * Set the currently selected track for the chapters button.
  16421. *
  16422. * @param {TextTrack} track
  16423. * The new track to select. Nothing will change if this is the currently selected
  16424. * track.
  16425. */
  16426. setTrack(track) {
  16427. if (this.track_ === track) {
  16428. return;
  16429. }
  16430. if (!this.updateHandler_) {
  16431. this.updateHandler_ = this.update.bind(this);
  16432. }
  16433. // here this.track_ refers to the old track instance
  16434. if (this.track_) {
  16435. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  16436. if (remoteTextTrackEl) {
  16437. remoteTextTrackEl.removeEventListener('load', this.updateHandler_);
  16438. }
  16439. this.track_.removeEventListener('cuechange', this.selectCurrentItem_);
  16440. this.track_ = null;
  16441. }
  16442. this.track_ = track;
  16443. // here this.track_ refers to the new track instance
  16444. if (this.track_) {
  16445. this.track_.mode = 'hidden';
  16446. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  16447. if (remoteTextTrackEl) {
  16448. remoteTextTrackEl.addEventListener('load', this.updateHandler_);
  16449. }
  16450. this.track_.addEventListener('cuechange', this.selectCurrentItem_);
  16451. }
  16452. }
  16453. /**
  16454. * Find the track object that is currently in use by this ChaptersButton
  16455. *
  16456. * @return {TextTrack|undefined}
  16457. * The current track or undefined if none was found.
  16458. */
  16459. findChaptersTrack() {
  16460. const tracks = this.player_.textTracks() || [];
  16461. for (let i = tracks.length - 1; i >= 0; i--) {
  16462. // We will always choose the last track as our chaptersTrack
  16463. const track = tracks[i];
  16464. if (track.kind === this.kind_) {
  16465. return track;
  16466. }
  16467. }
  16468. }
  16469. /**
  16470. * Get the caption for the ChaptersButton based on the track label. This will also
  16471. * use the current tracks localized kind as a fallback if a label does not exist.
  16472. *
  16473. * @return {string}
  16474. * The tracks current label or the localized track kind.
  16475. */
  16476. getMenuCaption() {
  16477. if (this.track_ && this.track_.label) {
  16478. return this.track_.label;
  16479. }
  16480. return this.localize(toTitleCase$1(this.kind_));
  16481. }
  16482. /**
  16483. * Create menu from chapter track
  16484. *
  16485. * @return { import('../../menu/menu').default }
  16486. * New menu for the chapter buttons
  16487. */
  16488. createMenu() {
  16489. this.options_.title = this.getMenuCaption();
  16490. return super.createMenu();
  16491. }
  16492. /**
  16493. * Create a menu item for each text track
  16494. *
  16495. * @return { import('./text-track-menu-item').default[] }
  16496. * Array of menu items
  16497. */
  16498. createItems() {
  16499. const items = [];
  16500. if (!this.track_) {
  16501. return items;
  16502. }
  16503. const cues = this.track_.cues;
  16504. if (!cues) {
  16505. return items;
  16506. }
  16507. for (let i = 0, l = cues.length; i < l; i++) {
  16508. const cue = cues[i];
  16509. const mi = new ChaptersTrackMenuItem(this.player_, {
  16510. track: this.track_,
  16511. cue
  16512. });
  16513. items.push(mi);
  16514. }
  16515. return items;
  16516. }
  16517. }
  16518. /**
  16519. * `kind` of TextTrack to look for to associate it with this menu.
  16520. *
  16521. * @type {string}
  16522. * @private
  16523. */
  16524. ChaptersButton.prototype.kind_ = 'chapters';
  16525. /**
  16526. * The text that should display over the `ChaptersButton`s controls. Added for localization.
  16527. *
  16528. * @type {string}
  16529. * @protected
  16530. */
  16531. ChaptersButton.prototype.controlText_ = 'Chapters';
  16532. Component$1.registerComponent('ChaptersButton', ChaptersButton);
  16533. /**
  16534. * @file descriptions-button.js
  16535. */
  16536. /**
  16537. * The button component for toggling and selecting descriptions
  16538. *
  16539. * @extends TextTrackButton
  16540. */
  16541. class DescriptionsButton extends TextTrackButton {
  16542. /**
  16543. * Creates an instance of this class.
  16544. *
  16545. * @param { import('../../player').default } player
  16546. * The `Player` that this class should be attached to.
  16547. *
  16548. * @param {Object} [options]
  16549. * The key/value store of player options.
  16550. *
  16551. * @param {Function} [ready]
  16552. * The function to call when this component is ready.
  16553. */
  16554. constructor(player, options, ready) {
  16555. super(player, options, ready);
  16556. const tracks = player.textTracks();
  16557. const changeHandler = bind_(this, this.handleTracksChange);
  16558. tracks.addEventListener('change', changeHandler);
  16559. this.on('dispose', function () {
  16560. tracks.removeEventListener('change', changeHandler);
  16561. });
  16562. }
  16563. /**
  16564. * Handle text track change
  16565. *
  16566. * @param {Event} event
  16567. * The event that caused this function to run
  16568. *
  16569. * @listens TextTrackList#change
  16570. */
  16571. handleTracksChange(event) {
  16572. const tracks = this.player().textTracks();
  16573. let disabled = false;
  16574. // Check whether a track of a different kind is showing
  16575. for (let i = 0, l = tracks.length; i < l; i++) {
  16576. const track = tracks[i];
  16577. if (track.kind !== this.kind_ && track.mode === 'showing') {
  16578. disabled = true;
  16579. break;
  16580. }
  16581. }
  16582. // If another track is showing, disable this menu button
  16583. if (disabled) {
  16584. this.disable();
  16585. } else {
  16586. this.enable();
  16587. }
  16588. }
  16589. /**
  16590. * Builds the default DOM `className`.
  16591. *
  16592. * @return {string}
  16593. * The DOM `className` for this object.
  16594. */
  16595. buildCSSClass() {
  16596. return `vjs-descriptions-button ${super.buildCSSClass()}`;
  16597. }
  16598. buildWrapperCSSClass() {
  16599. return `vjs-descriptions-button ${super.buildWrapperCSSClass()}`;
  16600. }
  16601. }
  16602. /**
  16603. * `kind` of TextTrack to look for to associate it with this menu.
  16604. *
  16605. * @type {string}
  16606. * @private
  16607. */
  16608. DescriptionsButton.prototype.kind_ = 'descriptions';
  16609. /**
  16610. * The text that should display over the `DescriptionsButton`s controls. Added for localization.
  16611. *
  16612. * @type {string}
  16613. * @protected
  16614. */
  16615. DescriptionsButton.prototype.controlText_ = 'Descriptions';
  16616. Component$1.registerComponent('DescriptionsButton', DescriptionsButton);
  16617. /**
  16618. * @file subtitles-button.js
  16619. */
  16620. /**
  16621. * The button component for toggling and selecting subtitles
  16622. *
  16623. * @extends TextTrackButton
  16624. */
  16625. class SubtitlesButton extends TextTrackButton {
  16626. /**
  16627. * Creates an instance of this class.
  16628. *
  16629. * @param { import('../../player').default } player
  16630. * The `Player` that this class should be attached to.
  16631. *
  16632. * @param {Object} [options]
  16633. * The key/value store of player options.
  16634. *
  16635. * @param {Function} [ready]
  16636. * The function to call when this component is ready.
  16637. */
  16638. constructor(player, options, ready) {
  16639. super(player, options, ready);
  16640. }
  16641. /**
  16642. * Builds the default DOM `className`.
  16643. *
  16644. * @return {string}
  16645. * The DOM `className` for this object.
  16646. */
  16647. buildCSSClass() {
  16648. return `vjs-subtitles-button ${super.buildCSSClass()}`;
  16649. }
  16650. buildWrapperCSSClass() {
  16651. return `vjs-subtitles-button ${super.buildWrapperCSSClass()}`;
  16652. }
  16653. }
  16654. /**
  16655. * `kind` of TextTrack to look for to associate it with this menu.
  16656. *
  16657. * @type {string}
  16658. * @private
  16659. */
  16660. SubtitlesButton.prototype.kind_ = 'subtitles';
  16661. /**
  16662. * The text that should display over the `SubtitlesButton`s controls. Added for localization.
  16663. *
  16664. * @type {string}
  16665. * @protected
  16666. */
  16667. SubtitlesButton.prototype.controlText_ = 'Subtitles';
  16668. Component$1.registerComponent('SubtitlesButton', SubtitlesButton);
  16669. /**
  16670. * @file caption-settings-menu-item.js
  16671. */
  16672. /**
  16673. * The menu item for caption track settings menu
  16674. *
  16675. * @extends TextTrackMenuItem
  16676. */
  16677. class CaptionSettingsMenuItem extends TextTrackMenuItem {
  16678. /**
  16679. * Creates an instance of this class.
  16680. *
  16681. * @param { import('../../player').default } player
  16682. * The `Player` that this class should be attached to.
  16683. *
  16684. * @param {Object} [options]
  16685. * The key/value store of player options.
  16686. */
  16687. constructor(player, options) {
  16688. options.track = {
  16689. player,
  16690. kind: options.kind,
  16691. label: options.kind + ' settings',
  16692. selectable: false,
  16693. default: false,
  16694. mode: 'disabled'
  16695. };
  16696. // CaptionSettingsMenuItem has no concept of 'selected'
  16697. options.selectable = false;
  16698. options.name = 'CaptionSettingsMenuItem';
  16699. super(player, options);
  16700. this.addClass('vjs-texttrack-settings');
  16701. this.controlText(', opens ' + options.kind + ' settings dialog');
  16702. }
  16703. /**
  16704. * This gets called when an `CaptionSettingsMenuItem` is "clicked". See
  16705. * {@link ClickableComponent} for more detailed information on what a click can be.
  16706. *
  16707. * @param {Event} [event]
  16708. * The `keydown`, `tap`, or `click` event that caused this function to be
  16709. * called.
  16710. *
  16711. * @listens tap
  16712. * @listens click
  16713. */
  16714. handleClick(event) {
  16715. this.player().getChild('textTrackSettings').open();
  16716. }
  16717. /**
  16718. * Update control text and label on languagechange
  16719. */
  16720. handleLanguagechange() {
  16721. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.kind + ' settings');
  16722. super.handleLanguagechange();
  16723. }
  16724. }
  16725. Component$1.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
  16726. /**
  16727. * @file captions-button.js
  16728. */
  16729. /**
  16730. * The button component for toggling and selecting captions
  16731. *
  16732. * @extends TextTrackButton
  16733. */
  16734. class CaptionsButton extends TextTrackButton {
  16735. /**
  16736. * Creates an instance of this class.
  16737. *
  16738. * @param { import('../../player').default } player
  16739. * The `Player` that this class should be attached to.
  16740. *
  16741. * @param {Object} [options]
  16742. * The key/value store of player options.
  16743. *
  16744. * @param {Function} [ready]
  16745. * The function to call when this component is ready.
  16746. */
  16747. constructor(player, options, ready) {
  16748. super(player, options, ready);
  16749. }
  16750. /**
  16751. * Builds the default DOM `className`.
  16752. *
  16753. * @return {string}
  16754. * The DOM `className` for this object.
  16755. */
  16756. buildCSSClass() {
  16757. return `vjs-captions-button ${super.buildCSSClass()}`;
  16758. }
  16759. buildWrapperCSSClass() {
  16760. return `vjs-captions-button ${super.buildWrapperCSSClass()}`;
  16761. }
  16762. /**
  16763. * Create caption menu items
  16764. *
  16765. * @return {CaptionSettingsMenuItem[]}
  16766. * The array of current menu items.
  16767. */
  16768. createItems() {
  16769. const items = [];
  16770. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  16771. items.push(new CaptionSettingsMenuItem(this.player_, {
  16772. kind: this.kind_
  16773. }));
  16774. this.hideThreshold_ += 1;
  16775. }
  16776. return super.createItems(items);
  16777. }
  16778. }
  16779. /**
  16780. * `kind` of TextTrack to look for to associate it with this menu.
  16781. *
  16782. * @type {string}
  16783. * @private
  16784. */
  16785. CaptionsButton.prototype.kind_ = 'captions';
  16786. /**
  16787. * The text that should display over the `CaptionsButton`s controls. Added for localization.
  16788. *
  16789. * @type {string}
  16790. * @protected
  16791. */
  16792. CaptionsButton.prototype.controlText_ = 'Captions';
  16793. Component$1.registerComponent('CaptionsButton', CaptionsButton);
  16794. /**
  16795. * @file subs-caps-menu-item.js
  16796. */
  16797. /**
  16798. * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
  16799. * in the SubsCapsMenu.
  16800. *
  16801. * @extends TextTrackMenuItem
  16802. */
  16803. class SubsCapsMenuItem extends TextTrackMenuItem {
  16804. createEl(type, props, attrs) {
  16805. const el = super.createEl(type, props, attrs);
  16806. const parentSpan = el.querySelector('.vjs-menu-item-text');
  16807. if (this.options_.track.kind === 'captions') {
  16808. parentSpan.appendChild(createEl('span', {
  16809. className: 'vjs-icon-placeholder'
  16810. }, {
  16811. 'aria-hidden': true
  16812. }));
  16813. parentSpan.appendChild(createEl('span', {
  16814. className: 'vjs-control-text',
  16815. // space added as the text will visually flow with the
  16816. // label
  16817. textContent: ` ${this.localize('Captions')}`
  16818. }));
  16819. }
  16820. return el;
  16821. }
  16822. }
  16823. Component$1.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);
  16824. /**
  16825. * @file sub-caps-button.js
  16826. */
  16827. /**
  16828. * The button component for toggling and selecting captions and/or subtitles
  16829. *
  16830. * @extends TextTrackButton
  16831. */
  16832. class SubsCapsButton extends TextTrackButton {
  16833. /**
  16834. * Creates an instance of this class.
  16835. *
  16836. * @param { import('../../player').default } player
  16837. * The `Player` that this class should be attached to.
  16838. *
  16839. * @param {Object} [options]
  16840. * The key/value store of player options.
  16841. *
  16842. * @param {Function} [ready]
  16843. * The function to call when this component is ready.
  16844. */
  16845. constructor(player, options = {}) {
  16846. super(player, options);
  16847. // Although North America uses "captions" in most cases for
  16848. // "captions and subtitles" other locales use "subtitles"
  16849. this.label_ = 'subtitles';
  16850. if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(this.player_.language_) > -1) {
  16851. this.label_ = 'captions';
  16852. }
  16853. this.menuButton_.controlText(toTitleCase$1(this.label_));
  16854. }
  16855. /**
  16856. * Builds the default DOM `className`.
  16857. *
  16858. * @return {string}
  16859. * The DOM `className` for this object.
  16860. */
  16861. buildCSSClass() {
  16862. return `vjs-subs-caps-button ${super.buildCSSClass()}`;
  16863. }
  16864. buildWrapperCSSClass() {
  16865. return `vjs-subs-caps-button ${super.buildWrapperCSSClass()}`;
  16866. }
  16867. /**
  16868. * Create caption/subtitles menu items
  16869. *
  16870. * @return {CaptionSettingsMenuItem[]}
  16871. * The array of current menu items.
  16872. */
  16873. createItems() {
  16874. let items = [];
  16875. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  16876. items.push(new CaptionSettingsMenuItem(this.player_, {
  16877. kind: this.label_
  16878. }));
  16879. this.hideThreshold_ += 1;
  16880. }
  16881. items = super.createItems(items, SubsCapsMenuItem);
  16882. return items;
  16883. }
  16884. }
  16885. /**
  16886. * `kind`s of TextTrack to look for to associate it with this menu.
  16887. *
  16888. * @type {array}
  16889. * @private
  16890. */
  16891. SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];
  16892. /**
  16893. * The text that should display over the `SubsCapsButton`s controls.
  16894. *
  16895. *
  16896. * @type {string}
  16897. * @protected
  16898. */
  16899. SubsCapsButton.prototype.controlText_ = 'Subtitles';
  16900. Component$1.registerComponent('SubsCapsButton', SubsCapsButton);
  16901. /**
  16902. * @file audio-track-menu-item.js
  16903. */
  16904. /**
  16905. * An {@link AudioTrack} {@link MenuItem}
  16906. *
  16907. * @extends MenuItem
  16908. */
  16909. class AudioTrackMenuItem extends MenuItem {
  16910. /**
  16911. * Creates an instance of this class.
  16912. *
  16913. * @param { import('../../player').default } player
  16914. * The `Player` that this class should be attached to.
  16915. *
  16916. * @param {Object} [options]
  16917. * The key/value store of player options.
  16918. */
  16919. constructor(player, options) {
  16920. const track = options.track;
  16921. const tracks = player.audioTracks();
  16922. // Modify options for parent MenuItem class's init.
  16923. options.label = track.label || track.language || 'Unknown';
  16924. options.selected = track.enabled;
  16925. super(player, options);
  16926. this.track = track;
  16927. this.addClass(`vjs-${track.kind}-menu-item`);
  16928. const changeHandler = (...args) => {
  16929. this.handleTracksChange.apply(this, args);
  16930. };
  16931. tracks.addEventListener('change', changeHandler);
  16932. this.on('dispose', () => {
  16933. tracks.removeEventListener('change', changeHandler);
  16934. });
  16935. }
  16936. createEl(type, props, attrs) {
  16937. const el = super.createEl(type, props, attrs);
  16938. const parentSpan = el.querySelector('.vjs-menu-item-text');
  16939. if (this.options_.track.kind === 'main-desc') {
  16940. parentSpan.appendChild(createEl('span', {
  16941. className: 'vjs-icon-placeholder'
  16942. }, {
  16943. 'aria-hidden': true
  16944. }));
  16945. parentSpan.appendChild(createEl('span', {
  16946. className: 'vjs-control-text',
  16947. textContent: ' ' + this.localize('Descriptions')
  16948. }));
  16949. }
  16950. return el;
  16951. }
  16952. /**
  16953. * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent}
  16954. * for more detailed information on what a click can be.
  16955. *
  16956. * @param {Event} [event]
  16957. * The `keydown`, `tap`, or `click` event that caused this function to be
  16958. * called.
  16959. *
  16960. * @listens tap
  16961. * @listens click
  16962. */
  16963. handleClick(event) {
  16964. super.handleClick(event);
  16965. // the audio track list will automatically toggle other tracks
  16966. // off for us.
  16967. this.track.enabled = true;
  16968. // when native audio tracks are used, we want to make sure that other tracks are turned off
  16969. if (this.player_.tech_.featuresNativeAudioTracks) {
  16970. const tracks = this.player_.audioTracks();
  16971. for (let i = 0; i < tracks.length; i++) {
  16972. const track = tracks[i];
  16973. // skip the current track since we enabled it above
  16974. if (track === this.track) {
  16975. continue;
  16976. }
  16977. track.enabled = track === this.track;
  16978. }
  16979. }
  16980. }
  16981. /**
  16982. * Handle any {@link AudioTrack} change.
  16983. *
  16984. * @param {Event} [event]
  16985. * The {@link AudioTrackList#change} event that caused this to run.
  16986. *
  16987. * @listens AudioTrackList#change
  16988. */
  16989. handleTracksChange(event) {
  16990. this.selected(this.track.enabled);
  16991. }
  16992. }
  16993. Component$1.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);
  16994. /**
  16995. * @file audio-track-button.js
  16996. */
  16997. /**
  16998. * The base class for buttons that toggle specific {@link AudioTrack} types.
  16999. *
  17000. * @extends TrackButton
  17001. */
  17002. class AudioTrackButton extends TrackButton {
  17003. /**
  17004. * Creates an instance of this class.
  17005. *
  17006. * @param {Player} player
  17007. * The `Player` that this class should be attached to.
  17008. *
  17009. * @param {Object} [options={}]
  17010. * The key/value store of player options.
  17011. */
  17012. constructor(player, options = {}) {
  17013. options.tracks = player.audioTracks();
  17014. super(player, options);
  17015. }
  17016. /**
  17017. * Builds the default DOM `className`.
  17018. *
  17019. * @return {string}
  17020. * The DOM `className` for this object.
  17021. */
  17022. buildCSSClass() {
  17023. return `vjs-audio-button ${super.buildCSSClass()}`;
  17024. }
  17025. buildWrapperCSSClass() {
  17026. return `vjs-audio-button ${super.buildWrapperCSSClass()}`;
  17027. }
  17028. /**
  17029. * Create a menu item for each audio track
  17030. *
  17031. * @param {AudioTrackMenuItem[]} [items=[]]
  17032. * An array of existing menu items to use.
  17033. *
  17034. * @return {AudioTrackMenuItem[]}
  17035. * An array of menu items
  17036. */
  17037. createItems(items = []) {
  17038. // if there's only one audio track, there no point in showing it
  17039. this.hideThreshold_ = 1;
  17040. const tracks = this.player_.audioTracks();
  17041. for (let i = 0; i < tracks.length; i++) {
  17042. const track = tracks[i];
  17043. items.push(new AudioTrackMenuItem(this.player_, {
  17044. track,
  17045. // MenuItem is selectable
  17046. selectable: true,
  17047. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  17048. multiSelectable: false
  17049. }));
  17050. }
  17051. return items;
  17052. }
  17053. }
  17054. /**
  17055. * The text that should display over the `AudioTrackButton`s controls. Added for localization.
  17056. *
  17057. * @type {string}
  17058. * @protected
  17059. */
  17060. AudioTrackButton.prototype.controlText_ = 'Audio Track';
  17061. Component$1.registerComponent('AudioTrackButton', AudioTrackButton);
  17062. /**
  17063. * @file playback-rate-menu-item.js
  17064. */
  17065. /**
  17066. * The specific menu item type for selecting a playback rate.
  17067. *
  17068. * @extends MenuItem
  17069. */
  17070. class PlaybackRateMenuItem extends MenuItem {
  17071. /**
  17072. * Creates an instance of this class.
  17073. *
  17074. * @param { import('../../player').default } player
  17075. * The `Player` that this class should be attached to.
  17076. *
  17077. * @param {Object} [options]
  17078. * The key/value store of player options.
  17079. */
  17080. constructor(player, options) {
  17081. const label = options.rate;
  17082. const rate = parseFloat(label, 10);
  17083. // Modify options for parent MenuItem class's init.
  17084. options.label = label;
  17085. options.selected = rate === player.playbackRate();
  17086. options.selectable = true;
  17087. options.multiSelectable = false;
  17088. super(player, options);
  17089. this.label = label;
  17090. this.rate = rate;
  17091. this.on(player, 'ratechange', e => this.update(e));
  17092. }
  17093. /**
  17094. * This gets called when an `PlaybackRateMenuItem` is "clicked". See
  17095. * {@link ClickableComponent} for more detailed information on what a click can be.
  17096. *
  17097. * @param {Event} [event]
  17098. * The `keydown`, `tap`, or `click` event that caused this function to be
  17099. * called.
  17100. *
  17101. * @listens tap
  17102. * @listens click
  17103. */
  17104. handleClick(event) {
  17105. super.handleClick();
  17106. this.player().playbackRate(this.rate);
  17107. }
  17108. /**
  17109. * Update the PlaybackRateMenuItem when the playbackrate changes.
  17110. *
  17111. * @param {Event} [event]
  17112. * The `ratechange` event that caused this function to run.
  17113. *
  17114. * @listens Player#ratechange
  17115. */
  17116. update(event) {
  17117. this.selected(this.player().playbackRate() === this.rate);
  17118. }
  17119. }
  17120. /**
  17121. * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.
  17122. *
  17123. * @type {string}
  17124. * @private
  17125. */
  17126. PlaybackRateMenuItem.prototype.contentElType = 'button';
  17127. Component$1.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
  17128. /**
  17129. * @file playback-rate-menu-button.js
  17130. */
  17131. /**
  17132. * The component for controlling the playback rate.
  17133. *
  17134. * @extends MenuButton
  17135. */
  17136. class PlaybackRateMenuButton extends MenuButton {
  17137. /**
  17138. * Creates an instance of this class.
  17139. *
  17140. * @param { import('../../player').default } player
  17141. * The `Player` that this class should be attached to.
  17142. *
  17143. * @param {Object} [options]
  17144. * The key/value store of player options.
  17145. */
  17146. constructor(player, options) {
  17147. super(player, options);
  17148. this.menuButton_.el_.setAttribute('aria-describedby', this.labelElId_);
  17149. this.updateVisibility();
  17150. this.updateLabel();
  17151. this.on(player, 'loadstart', e => this.updateVisibility(e));
  17152. this.on(player, 'ratechange', e => this.updateLabel(e));
  17153. this.on(player, 'playbackrateschange', e => this.handlePlaybackRateschange(e));
  17154. }
  17155. /**
  17156. * Create the `Component`'s DOM element
  17157. *
  17158. * @return {Element}
  17159. * The element that was created.
  17160. */
  17161. createEl() {
  17162. const el = super.createEl();
  17163. this.labelElId_ = 'vjs-playback-rate-value-label-' + this.id_;
  17164. this.labelEl_ = createEl('div', {
  17165. className: 'vjs-playback-rate-value',
  17166. id: this.labelElId_,
  17167. textContent: '1x'
  17168. });
  17169. el.appendChild(this.labelEl_);
  17170. return el;
  17171. }
  17172. dispose() {
  17173. this.labelEl_ = null;
  17174. super.dispose();
  17175. }
  17176. /**
  17177. * Builds the default DOM `className`.
  17178. *
  17179. * @return {string}
  17180. * The DOM `className` for this object.
  17181. */
  17182. buildCSSClass() {
  17183. return `vjs-playback-rate ${super.buildCSSClass()}`;
  17184. }
  17185. buildWrapperCSSClass() {
  17186. return `vjs-playback-rate ${super.buildWrapperCSSClass()}`;
  17187. }
  17188. /**
  17189. * Create the list of menu items. Specific to each subclass.
  17190. *
  17191. */
  17192. createItems() {
  17193. const rates = this.playbackRates();
  17194. const items = [];
  17195. for (let i = rates.length - 1; i >= 0; i--) {
  17196. items.push(new PlaybackRateMenuItem(this.player(), {
  17197. rate: rates[i] + 'x'
  17198. }));
  17199. }
  17200. return items;
  17201. }
  17202. /**
  17203. * On playbackrateschange, update the menu to account for the new items.
  17204. *
  17205. * @listens Player#playbackrateschange
  17206. */
  17207. handlePlaybackRateschange(event) {
  17208. this.update();
  17209. }
  17210. /**
  17211. * Get possible playback rates
  17212. *
  17213. * @return {Array}
  17214. * All possible playback rates
  17215. */
  17216. playbackRates() {
  17217. const player = this.player();
  17218. return player.playbackRates && player.playbackRates() || [];
  17219. }
  17220. /**
  17221. * Get whether playback rates is supported by the tech
  17222. * and an array of playback rates exists
  17223. *
  17224. * @return {boolean}
  17225. * Whether changing playback rate is supported
  17226. */
  17227. playbackRateSupported() {
  17228. return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
  17229. }
  17230. /**
  17231. * Hide playback rate controls when they're no playback rate options to select
  17232. *
  17233. * @param {Event} [event]
  17234. * The event that caused this function to run.
  17235. *
  17236. * @listens Player#loadstart
  17237. */
  17238. updateVisibility(event) {
  17239. if (this.playbackRateSupported()) {
  17240. this.removeClass('vjs-hidden');
  17241. } else {
  17242. this.addClass('vjs-hidden');
  17243. }
  17244. }
  17245. /**
  17246. * Update button label when rate changed
  17247. *
  17248. * @param {Event} [event]
  17249. * The event that caused this function to run.
  17250. *
  17251. * @listens Player#ratechange
  17252. */
  17253. updateLabel(event) {
  17254. if (this.playbackRateSupported()) {
  17255. this.labelEl_.textContent = this.player().playbackRate() + 'x';
  17256. }
  17257. }
  17258. }
  17259. /**
  17260. * The text that should display over the `PlaybackRateMenuButton`s controls.
  17261. *
  17262. * Added for localization.
  17263. *
  17264. * @type {string}
  17265. * @protected
  17266. */
  17267. PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
  17268. Component$1.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
  17269. /**
  17270. * @file spacer.js
  17271. */
  17272. /**
  17273. * Just an empty spacer element that can be used as an append point for plugins, etc.
  17274. * Also can be used to create space between elements when necessary.
  17275. *
  17276. * @extends Component
  17277. */
  17278. class Spacer extends Component$1 {
  17279. /**
  17280. * Builds the default DOM `className`.
  17281. *
  17282. * @return {string}
  17283. * The DOM `className` for this object.
  17284. */
  17285. buildCSSClass() {
  17286. return `vjs-spacer ${super.buildCSSClass()}`;
  17287. }
  17288. /**
  17289. * Create the `Component`'s DOM element
  17290. *
  17291. * @return {Element}
  17292. * The element that was created.
  17293. */
  17294. createEl(tag = 'div', props = {}, attributes = {}) {
  17295. if (!props.className) {
  17296. props.className = this.buildCSSClass();
  17297. }
  17298. return super.createEl(tag, props, attributes);
  17299. }
  17300. }
  17301. Component$1.registerComponent('Spacer', Spacer);
  17302. /**
  17303. * @file custom-control-spacer.js
  17304. */
  17305. /**
  17306. * Spacer specifically meant to be used as an insertion point for new plugins, etc.
  17307. *
  17308. * @extends Spacer
  17309. */
  17310. class CustomControlSpacer extends Spacer {
  17311. /**
  17312. * Builds the default DOM `className`.
  17313. *
  17314. * @return {string}
  17315. * The DOM `className` for this object.
  17316. */
  17317. buildCSSClass() {
  17318. return `vjs-custom-control-spacer ${super.buildCSSClass()}`;
  17319. }
  17320. /**
  17321. * Create the `Component`'s DOM element
  17322. *
  17323. * @return {Element}
  17324. * The element that was created.
  17325. */
  17326. createEl() {
  17327. return super.createEl('div', {
  17328. className: this.buildCSSClass(),
  17329. // No-flex/table-cell mode requires there be some content
  17330. // in the cell to fill the remaining space of the table.
  17331. textContent: '\u00a0'
  17332. });
  17333. }
  17334. }
  17335. Component$1.registerComponent('CustomControlSpacer', CustomControlSpacer);
  17336. /**
  17337. * @file control-bar.js
  17338. */
  17339. /**
  17340. * Container of main controls.
  17341. *
  17342. * @extends Component
  17343. */
  17344. class ControlBar extends Component$1 {
  17345. /**
  17346. * Create the `Component`'s DOM element
  17347. *
  17348. * @return {Element}
  17349. * The element that was created.
  17350. */
  17351. createEl() {
  17352. return super.createEl('div', {
  17353. className: 'vjs-control-bar',
  17354. dir: 'ltr'
  17355. });
  17356. }
  17357. }
  17358. /**
  17359. * Default options for `ControlBar`
  17360. *
  17361. * @type {Object}
  17362. * @private
  17363. */
  17364. ControlBar.prototype.options_ = {
  17365. children: ['playToggle', 'skipBackward', 'skipForward', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'fullscreenToggle']
  17366. };
  17367. if ('exitPictureInPicture' in document) {
  17368. ControlBar.prototype.options_.children.splice(ControlBar.prototype.options_.children.length - 1, 0, 'pictureInPictureToggle');
  17369. }
  17370. Component$1.registerComponent('ControlBar', ControlBar);
  17371. /**
  17372. * @file error-display.js
  17373. */
  17374. /**
  17375. * A display that indicates an error has occurred. This means that the video
  17376. * is unplayable.
  17377. *
  17378. * @extends ModalDialog
  17379. */
  17380. class ErrorDisplay extends ModalDialog {
  17381. /**
  17382. * Creates an instance of this class.
  17383. *
  17384. * @param { import('./player').default } player
  17385. * The `Player` that this class should be attached to.
  17386. *
  17387. * @param {Object} [options]
  17388. * The key/value store of player options.
  17389. */
  17390. constructor(player, options) {
  17391. super(player, options);
  17392. this.on(player, 'error', e => this.open(e));
  17393. }
  17394. /**
  17395. * Builds the default DOM `className`.
  17396. *
  17397. * @return {string}
  17398. * The DOM `className` for this object.
  17399. *
  17400. * @deprecated Since version 5.
  17401. */
  17402. buildCSSClass() {
  17403. return `vjs-error-display ${super.buildCSSClass()}`;
  17404. }
  17405. /**
  17406. * Gets the localized error message based on the `Player`s error.
  17407. *
  17408. * @return {string}
  17409. * The `Player`s error message localized or an empty string.
  17410. */
  17411. content() {
  17412. const error = this.player().error();
  17413. return error ? this.localize(error.message) : '';
  17414. }
  17415. }
  17416. /**
  17417. * The default options for an `ErrorDisplay`.
  17418. *
  17419. * @private
  17420. */
  17421. ErrorDisplay.prototype.options_ = Object.assign({}, ModalDialog.prototype.options_, {
  17422. pauseOnOpen: false,
  17423. fillAlways: true,
  17424. temporary: false,
  17425. uncloseable: true
  17426. });
  17427. Component$1.registerComponent('ErrorDisplay', ErrorDisplay);
  17428. /**
  17429. * @file text-track-settings.js
  17430. */
  17431. const LOCAL_STORAGE_KEY$1 = 'vjs-text-track-settings';
  17432. const COLOR_BLACK = ['#000', 'Black'];
  17433. const COLOR_BLUE = ['#00F', 'Blue'];
  17434. const COLOR_CYAN = ['#0FF', 'Cyan'];
  17435. const COLOR_GREEN = ['#0F0', 'Green'];
  17436. const COLOR_MAGENTA = ['#F0F', 'Magenta'];
  17437. const COLOR_RED = ['#F00', 'Red'];
  17438. const COLOR_WHITE = ['#FFF', 'White'];
  17439. const COLOR_YELLOW = ['#FF0', 'Yellow'];
  17440. const OPACITY_OPAQUE = ['1', 'Opaque'];
  17441. const OPACITY_SEMI = ['0.5', 'Semi-Transparent'];
  17442. const OPACITY_TRANS = ['0', 'Transparent'];
  17443. // Configuration for the various <select> elements in the DOM of this component.
  17444. //
  17445. // Possible keys include:
  17446. //
  17447. // `default`:
  17448. // The default option index. Only needs to be provided if not zero.
  17449. // `parser`:
  17450. // A function which is used to parse the value from the selected option in
  17451. // a customized way.
  17452. // `selector`:
  17453. // The selector used to find the associated <select> element.
  17454. const selectConfigs = {
  17455. backgroundColor: {
  17456. selector: '.vjs-bg-color > select',
  17457. id: 'captions-background-color-%s',
  17458. label: 'Color',
  17459. options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  17460. },
  17461. backgroundOpacity: {
  17462. selector: '.vjs-bg-opacity > select',
  17463. id: 'captions-background-opacity-%s',
  17464. label: 'Opacity',
  17465. options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS]
  17466. },
  17467. color: {
  17468. selector: '.vjs-text-color > select',
  17469. id: 'captions-foreground-color-%s',
  17470. label: 'Color',
  17471. options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  17472. },
  17473. edgeStyle: {
  17474. selector: '.vjs-edge-style > select',
  17475. id: '%s',
  17476. label: 'Text Edge Style',
  17477. options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']]
  17478. },
  17479. fontFamily: {
  17480. selector: '.vjs-font-family > select',
  17481. id: 'captions-font-family-%s',
  17482. label: 'Font Family',
  17483. options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]
  17484. },
  17485. fontPercent: {
  17486. selector: '.vjs-font-percent > select',
  17487. id: 'captions-font-size-%s',
  17488. label: 'Font Size',
  17489. 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%']],
  17490. default: 2,
  17491. parser: v => v === '1.00' ? null : Number(v)
  17492. },
  17493. textOpacity: {
  17494. selector: '.vjs-text-opacity > select',
  17495. id: 'captions-foreground-opacity-%s',
  17496. label: 'Opacity',
  17497. options: [OPACITY_OPAQUE, OPACITY_SEMI]
  17498. },
  17499. // Options for this object are defined below.
  17500. windowColor: {
  17501. selector: '.vjs-window-color > select',
  17502. id: 'captions-window-color-%s',
  17503. label: 'Color'
  17504. },
  17505. // Options for this object are defined below.
  17506. windowOpacity: {
  17507. selector: '.vjs-window-opacity > select',
  17508. id: 'captions-window-opacity-%s',
  17509. label: 'Opacity',
  17510. options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE]
  17511. }
  17512. };
  17513. selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
  17514. /**
  17515. * Get the actual value of an option.
  17516. *
  17517. * @param {string} value
  17518. * The value to get
  17519. *
  17520. * @param {Function} [parser]
  17521. * Optional function to adjust the value.
  17522. *
  17523. * @return {*}
  17524. * - Will be `undefined` if no value exists
  17525. * - Will be `undefined` if the given value is "none".
  17526. * - Will be the actual value otherwise.
  17527. *
  17528. * @private
  17529. */
  17530. function parseOptionValue(value, parser) {
  17531. if (parser) {
  17532. value = parser(value);
  17533. }
  17534. if (value && value !== 'none') {
  17535. return value;
  17536. }
  17537. }
  17538. /**
  17539. * Gets the value of the selected <option> element within a <select> element.
  17540. *
  17541. * @param {Element} el
  17542. * the element to look in
  17543. *
  17544. * @param {Function} [parser]
  17545. * Optional function to adjust the value.
  17546. *
  17547. * @return {*}
  17548. * - Will be `undefined` if no value exists
  17549. * - Will be `undefined` if the given value is "none".
  17550. * - Will be the actual value otherwise.
  17551. *
  17552. * @private
  17553. */
  17554. function getSelectedOptionValue(el, parser) {
  17555. const value = el.options[el.options.selectedIndex].value;
  17556. return parseOptionValue(value, parser);
  17557. }
  17558. /**
  17559. * Sets the selected <option> element within a <select> element based on a
  17560. * given value.
  17561. *
  17562. * @param {Element} el
  17563. * The element to look in.
  17564. *
  17565. * @param {string} value
  17566. * the property to look on.
  17567. *
  17568. * @param {Function} [parser]
  17569. * Optional function to adjust the value before comparing.
  17570. *
  17571. * @private
  17572. */
  17573. function setSelectedOption(el, value, parser) {
  17574. if (!value) {
  17575. return;
  17576. }
  17577. for (let i = 0; i < el.options.length; i++) {
  17578. if (parseOptionValue(el.options[i].value, parser) === value) {
  17579. el.selectedIndex = i;
  17580. break;
  17581. }
  17582. }
  17583. }
  17584. /**
  17585. * Manipulate Text Tracks settings.
  17586. *
  17587. * @extends ModalDialog
  17588. */
  17589. class TextTrackSettings extends ModalDialog {
  17590. /**
  17591. * Creates an instance of this class.
  17592. *
  17593. * @param { import('../player').default } player
  17594. * The `Player` that this class should be attached to.
  17595. *
  17596. * @param {Object} [options]
  17597. * The key/value store of player options.
  17598. */
  17599. constructor(player, options) {
  17600. options.temporary = false;
  17601. super(player, options);
  17602. this.updateDisplay = this.updateDisplay.bind(this);
  17603. // fill the modal and pretend we have opened it
  17604. this.fill();
  17605. this.hasBeenOpened_ = this.hasBeenFilled_ = true;
  17606. this.endDialog = createEl('p', {
  17607. className: 'vjs-control-text',
  17608. textContent: this.localize('End of dialog window.')
  17609. });
  17610. this.el().appendChild(this.endDialog);
  17611. this.setDefaults();
  17612. // Grab `persistTextTrackSettings` from the player options if not passed in child options
  17613. if (options.persistTextTrackSettings === undefined) {
  17614. this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings;
  17615. }
  17616. this.on(this.$('.vjs-done-button'), 'click', () => {
  17617. this.saveSettings();
  17618. this.close();
  17619. });
  17620. this.on(this.$('.vjs-default-button'), 'click', () => {
  17621. this.setDefaults();
  17622. this.updateDisplay();
  17623. });
  17624. each(selectConfigs, config => {
  17625. this.on(this.$(config.selector), 'change', this.updateDisplay);
  17626. });
  17627. if (this.options_.persistTextTrackSettings) {
  17628. this.restoreSettings();
  17629. }
  17630. }
  17631. dispose() {
  17632. this.endDialog = null;
  17633. super.dispose();
  17634. }
  17635. /**
  17636. * Create a <select> element with configured options.
  17637. *
  17638. * @param {string} key
  17639. * Configuration key to use during creation.
  17640. *
  17641. * @return {string}
  17642. * An HTML string.
  17643. *
  17644. * @private
  17645. */
  17646. createElSelect_(key, legendId = '', type = 'label') {
  17647. const config = selectConfigs[key];
  17648. const id = config.id.replace('%s', this.id_);
  17649. const selectLabelledbyIds = [legendId, id].join(' ').trim();
  17650. return [`<${type} id="${id}" class="${type === 'label' ? 'vjs-label' : ''}">`, this.localize(config.label), `</${type}>`, `<select aria-labelledby="${selectLabelledbyIds}">`].concat(config.options.map(o => {
  17651. const optionId = id + '-' + o[1].replace(/\W+/g, '');
  17652. return [`<option id="${optionId}" value="${o[0]}" `, `aria-labelledby="${selectLabelledbyIds} ${optionId}">`, this.localize(o[1]), '</option>'].join('');
  17653. })).concat('</select>').join('');
  17654. }
  17655. /**
  17656. * Create foreground color element for the component
  17657. *
  17658. * @return {string}
  17659. * An HTML string.
  17660. *
  17661. * @private
  17662. */
  17663. createElFgColor_() {
  17664. const legendId = `captions-text-legend-${this.id_}`;
  17665. 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('');
  17666. }
  17667. /**
  17668. * Create background color element for the component
  17669. *
  17670. * @return {string}
  17671. * An HTML string.
  17672. *
  17673. * @private
  17674. */
  17675. createElBgColor_() {
  17676. const legendId = `captions-background-${this.id_}`;
  17677. 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('');
  17678. }
  17679. /**
  17680. * Create window color element for the component
  17681. *
  17682. * @return {string}
  17683. * An HTML string.
  17684. *
  17685. * @private
  17686. */
  17687. createElWinColor_() {
  17688. const legendId = `captions-window-${this.id_}`;
  17689. 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('');
  17690. }
  17691. /**
  17692. * Create color elements for the component
  17693. *
  17694. * @return {Element}
  17695. * The element that was created
  17696. *
  17697. * @private
  17698. */
  17699. createElColors_() {
  17700. return createEl('div', {
  17701. className: 'vjs-track-settings-colors',
  17702. innerHTML: [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()].join('')
  17703. });
  17704. }
  17705. /**
  17706. * Create font elements for the component
  17707. *
  17708. * @return {Element}
  17709. * The element that was created.
  17710. *
  17711. * @private
  17712. */
  17713. createElFont_() {
  17714. return createEl('div', {
  17715. className: 'vjs-track-settings-font',
  17716. 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('')
  17717. });
  17718. }
  17719. /**
  17720. * Create controls for the component
  17721. *
  17722. * @return {Element}
  17723. * The element that was created.
  17724. *
  17725. * @private
  17726. */
  17727. createElControls_() {
  17728. const defaultsDescription = this.localize('restore all settings to the default values');
  17729. return createEl('div', {
  17730. className: 'vjs-track-settings-controls',
  17731. 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('')
  17732. });
  17733. }
  17734. content() {
  17735. return [this.createElColors_(), this.createElFont_(), this.createElControls_()];
  17736. }
  17737. label() {
  17738. return this.localize('Caption Settings Dialog');
  17739. }
  17740. description() {
  17741. return this.localize('Beginning of dialog window. Escape will cancel and close the window.');
  17742. }
  17743. buildCSSClass() {
  17744. return super.buildCSSClass() + ' vjs-text-track-settings';
  17745. }
  17746. /**
  17747. * Gets an object of text track settings (or null).
  17748. *
  17749. * @return {Object}
  17750. * An object with config values parsed from the DOM or localStorage.
  17751. */
  17752. getValues() {
  17753. return reduce(selectConfigs, (accum, config, key) => {
  17754. const value = getSelectedOptionValue(this.$(config.selector), config.parser);
  17755. if (value !== undefined) {
  17756. accum[key] = value;
  17757. }
  17758. return accum;
  17759. }, {});
  17760. }
  17761. /**
  17762. * Sets text track settings from an object of values.
  17763. *
  17764. * @param {Object} values
  17765. * An object with config values parsed from the DOM or localStorage.
  17766. */
  17767. setValues(values) {
  17768. each(selectConfigs, (config, key) => {
  17769. setSelectedOption(this.$(config.selector), values[key], config.parser);
  17770. });
  17771. }
  17772. /**
  17773. * Sets all `<select>` elements to their default values.
  17774. */
  17775. setDefaults() {
  17776. each(selectConfigs, config => {
  17777. const index = config.hasOwnProperty('default') ? config.default : 0;
  17778. this.$(config.selector).selectedIndex = index;
  17779. });
  17780. }
  17781. /**
  17782. * Restore texttrack settings from localStorage
  17783. */
  17784. restoreSettings() {
  17785. let values;
  17786. try {
  17787. values = JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_KEY$1));
  17788. } catch (err) {
  17789. log$1.warn(err);
  17790. }
  17791. if (values) {
  17792. this.setValues(values);
  17793. }
  17794. }
  17795. /**
  17796. * Save text track settings to localStorage
  17797. */
  17798. saveSettings() {
  17799. if (!this.options_.persistTextTrackSettings) {
  17800. return;
  17801. }
  17802. const values = this.getValues();
  17803. try {
  17804. if (Object.keys(values).length) {
  17805. window.localStorage.setItem(LOCAL_STORAGE_KEY$1, JSON.stringify(values));
  17806. } else {
  17807. window.localStorage.removeItem(LOCAL_STORAGE_KEY$1);
  17808. }
  17809. } catch (err) {
  17810. log$1.warn(err);
  17811. }
  17812. }
  17813. /**
  17814. * Update display of text track settings
  17815. */
  17816. updateDisplay() {
  17817. const ttDisplay = this.player_.getChild('textTrackDisplay');
  17818. if (ttDisplay) {
  17819. ttDisplay.updateDisplay();
  17820. }
  17821. }
  17822. /**
  17823. * conditionally blur the element and refocus the captions button
  17824. *
  17825. * @private
  17826. */
  17827. conditionalBlur_() {
  17828. this.previouslyActiveEl_ = null;
  17829. const cb = this.player_.controlBar;
  17830. const subsCapsBtn = cb && cb.subsCapsButton;
  17831. const ccBtn = cb && cb.captionsButton;
  17832. if (subsCapsBtn) {
  17833. subsCapsBtn.focus();
  17834. } else if (ccBtn) {
  17835. ccBtn.focus();
  17836. }
  17837. }
  17838. /**
  17839. * Repopulate dialog with new localizations on languagechange
  17840. */
  17841. handleLanguagechange() {
  17842. this.fill();
  17843. }
  17844. }
  17845. Component$1.registerComponent('TextTrackSettings', TextTrackSettings);
  17846. /**
  17847. * @file resize-manager.js
  17848. */
  17849. /**
  17850. * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
  17851. *
  17852. * 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}.
  17853. *
  17854. * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
  17855. * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
  17856. *
  17857. * @example <caption>How to disable the resize manager</caption>
  17858. * const player = videojs('#vid', {
  17859. * resizeManager: false
  17860. * });
  17861. *
  17862. * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
  17863. *
  17864. * @extends Component
  17865. */
  17866. class ResizeManager extends Component$1 {
  17867. /**
  17868. * Create the ResizeManager.
  17869. *
  17870. * @param {Object} player
  17871. * The `Player` that this class should be attached to.
  17872. *
  17873. * @param {Object} [options]
  17874. * The key/value store of ResizeManager options.
  17875. *
  17876. * @param {Object} [options.ResizeObserver]
  17877. * A polyfill for ResizeObserver can be passed in here.
  17878. * If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
  17879. */
  17880. constructor(player, options) {
  17881. let RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window.ResizeObserver;
  17882. // if `null` was passed, we want to disable the ResizeObserver
  17883. if (options.ResizeObserver === null) {
  17884. RESIZE_OBSERVER_AVAILABLE = false;
  17885. }
  17886. // Only create an element when ResizeObserver isn't available
  17887. const options_ = merge$2({
  17888. createEl: !RESIZE_OBSERVER_AVAILABLE,
  17889. reportTouchActivity: false
  17890. }, options);
  17891. super(player, options_);
  17892. this.ResizeObserver = options.ResizeObserver || window.ResizeObserver;
  17893. this.loadListener_ = null;
  17894. this.resizeObserver_ = null;
  17895. this.debouncedHandler_ = debounce(() => {
  17896. this.resizeHandler();
  17897. }, 100, false, this);
  17898. if (RESIZE_OBSERVER_AVAILABLE) {
  17899. this.resizeObserver_ = new this.ResizeObserver(this.debouncedHandler_);
  17900. this.resizeObserver_.observe(player.el());
  17901. } else {
  17902. this.loadListener_ = () => {
  17903. if (!this.el_ || !this.el_.contentWindow) {
  17904. return;
  17905. }
  17906. const debouncedHandler_ = this.debouncedHandler_;
  17907. let unloadListener_ = this.unloadListener_ = function () {
  17908. off(this, 'resize', debouncedHandler_);
  17909. off(this, 'unload', unloadListener_);
  17910. unloadListener_ = null;
  17911. };
  17912. // safari and edge can unload the iframe before resizemanager dispose
  17913. // we have to dispose of event handlers correctly before that happens
  17914. on(this.el_.contentWindow, 'unload', unloadListener_);
  17915. on(this.el_.contentWindow, 'resize', debouncedHandler_);
  17916. };
  17917. this.one('load', this.loadListener_);
  17918. }
  17919. }
  17920. createEl() {
  17921. return super.createEl('iframe', {
  17922. className: 'vjs-resize-manager',
  17923. tabIndex: -1,
  17924. title: this.localize('No content')
  17925. }, {
  17926. 'aria-hidden': 'true'
  17927. });
  17928. }
  17929. /**
  17930. * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
  17931. *
  17932. * @fires Player#playerresize
  17933. */
  17934. resizeHandler() {
  17935. /**
  17936. * Called when the player size has changed
  17937. *
  17938. * @event Player#playerresize
  17939. * @type {Event}
  17940. */
  17941. // make sure player is still around to trigger
  17942. // prevents this from causing an error after dispose
  17943. if (!this.player_ || !this.player_.trigger) {
  17944. return;
  17945. }
  17946. this.player_.trigger('playerresize');
  17947. }
  17948. dispose() {
  17949. if (this.debouncedHandler_) {
  17950. this.debouncedHandler_.cancel();
  17951. }
  17952. if (this.resizeObserver_) {
  17953. if (this.player_.el()) {
  17954. this.resizeObserver_.unobserve(this.player_.el());
  17955. }
  17956. this.resizeObserver_.disconnect();
  17957. }
  17958. if (this.loadListener_) {
  17959. this.off('load', this.loadListener_);
  17960. }
  17961. if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
  17962. this.unloadListener_.call(this.el_.contentWindow);
  17963. }
  17964. this.ResizeObserver = null;
  17965. this.resizeObserver = null;
  17966. this.debouncedHandler_ = null;
  17967. this.loadListener_ = null;
  17968. super.dispose();
  17969. }
  17970. }
  17971. Component$1.registerComponent('ResizeManager', ResizeManager);
  17972. const defaults = {
  17973. trackingThreshold: 20,
  17974. liveTolerance: 15
  17975. };
  17976. /*
  17977. track when we are at the live edge, and other helpers for live playback */
  17978. /**
  17979. * A class for checking live current time and determining when the player
  17980. * is at or behind the live edge.
  17981. */
  17982. class LiveTracker extends Component$1 {
  17983. /**
  17984. * Creates an instance of this class.
  17985. *
  17986. * @param { import('./player').default } player
  17987. * The `Player` that this class should be attached to.
  17988. *
  17989. * @param {Object} [options]
  17990. * The key/value store of player options.
  17991. *
  17992. * @param {number} [options.trackingThreshold=20]
  17993. * Number of seconds of live window (seekableEnd - seekableStart) that
  17994. * media needs to have before the liveui will be shown.
  17995. *
  17996. * @param {number} [options.liveTolerance=15]
  17997. * Number of seconds behind live that we have to be
  17998. * before we will be considered non-live. Note that this will only
  17999. * be used when playing at the live edge. This allows large seekable end
  18000. * changes to not effect whether we are live or not.
  18001. */
  18002. constructor(player, options) {
  18003. // LiveTracker does not need an element
  18004. const options_ = merge$2(defaults, options, {
  18005. createEl: false
  18006. });
  18007. super(player, options_);
  18008. this.trackLiveHandler_ = () => this.trackLive_();
  18009. this.handlePlay_ = e => this.handlePlay(e);
  18010. this.handleFirstTimeupdate_ = e => this.handleFirstTimeupdate(e);
  18011. this.handleSeeked_ = e => this.handleSeeked(e);
  18012. this.seekToLiveEdge_ = e => this.seekToLiveEdge(e);
  18013. this.reset_();
  18014. this.on(this.player_, 'durationchange', e => this.handleDurationchange(e));
  18015. // we should try to toggle tracking on canplay as native playback engines, like Safari
  18016. // may not have the proper values for things like seekableEnd until then
  18017. this.on(this.player_, 'canplay', () => this.toggleTracking());
  18018. }
  18019. /**
  18020. * all the functionality for tracking when seek end changes
  18021. * and for tracking how far past seek end we should be
  18022. */
  18023. trackLive_() {
  18024. const seekable = this.player_.seekable();
  18025. // skip undefined seekable
  18026. if (!seekable || !seekable.length) {
  18027. return;
  18028. }
  18029. const newTime = Number(window.performance.now().toFixed(4));
  18030. const deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1000;
  18031. this.lastTime_ = newTime;
  18032. this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;
  18033. const liveCurrentTime = this.liveCurrentTime();
  18034. const currentTime = this.player_.currentTime();
  18035. // we are behind live if any are true
  18036. // 1. the player is paused
  18037. // 2. the user seeked to a location 2 seconds away from live
  18038. // 3. the difference between live and current time is greater
  18039. // liveTolerance which defaults to 15s
  18040. let isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance;
  18041. // we cannot be behind if
  18042. // 1. until we have not seen a timeupdate yet
  18043. // 2. liveCurrentTime is Infinity, which happens on Android and Native Safari
  18044. if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {
  18045. isBehind = false;
  18046. }
  18047. if (isBehind !== this.behindLiveEdge_) {
  18048. this.behindLiveEdge_ = isBehind;
  18049. this.trigger('liveedgechange');
  18050. }
  18051. }
  18052. /**
  18053. * handle a durationchange event on the player
  18054. * and start/stop tracking accordingly.
  18055. */
  18056. handleDurationchange() {
  18057. this.toggleTracking();
  18058. }
  18059. /**
  18060. * start/stop tracking
  18061. */
  18062. toggleTracking() {
  18063. if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {
  18064. if (this.player_.options_.liveui) {
  18065. this.player_.addClass('vjs-liveui');
  18066. }
  18067. this.startTracking();
  18068. } else {
  18069. this.player_.removeClass('vjs-liveui');
  18070. this.stopTracking();
  18071. }
  18072. }
  18073. /**
  18074. * start tracking live playback
  18075. */
  18076. startTracking() {
  18077. if (this.isTracking()) {
  18078. return;
  18079. }
  18080. // If we haven't seen a timeupdate, we need to check whether playback
  18081. // began before this component started tracking. This can happen commonly
  18082. // when using autoplay.
  18083. if (!this.timeupdateSeen_) {
  18084. this.timeupdateSeen_ = this.player_.hasStarted();
  18085. }
  18086. this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);
  18087. this.trackLive_();
  18088. this.on(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  18089. if (!this.timeupdateSeen_) {
  18090. this.one(this.player_, 'play', this.handlePlay_);
  18091. this.one(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  18092. } else {
  18093. this.on(this.player_, 'seeked', this.handleSeeked_);
  18094. }
  18095. }
  18096. /**
  18097. * handle the first timeupdate on the player if it wasn't already playing
  18098. * when live tracker started tracking.
  18099. */
  18100. handleFirstTimeupdate() {
  18101. this.timeupdateSeen_ = true;
  18102. this.on(this.player_, 'seeked', this.handleSeeked_);
  18103. }
  18104. /**
  18105. * Keep track of what time a seek starts, and listen for seeked
  18106. * to find where a seek ends.
  18107. */
  18108. handleSeeked() {
  18109. const timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());
  18110. this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;
  18111. this.nextSeekedFromUser_ = false;
  18112. this.trackLive_();
  18113. }
  18114. /**
  18115. * handle the first play on the player, and make sure that we seek
  18116. * right to the live edge.
  18117. */
  18118. handlePlay() {
  18119. this.one(this.player_, 'timeupdate', this.seekToLiveEdge_);
  18120. }
  18121. /**
  18122. * Stop tracking, and set all internal variables to
  18123. * their initial value.
  18124. */
  18125. reset_() {
  18126. this.lastTime_ = -1;
  18127. this.pastSeekEnd_ = 0;
  18128. this.lastSeekEnd_ = -1;
  18129. this.behindLiveEdge_ = true;
  18130. this.timeupdateSeen_ = false;
  18131. this.seekedBehindLive_ = false;
  18132. this.nextSeekedFromUser_ = false;
  18133. this.clearInterval(this.trackingInterval_);
  18134. this.trackingInterval_ = null;
  18135. this.off(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  18136. this.off(this.player_, 'seeked', this.handleSeeked_);
  18137. this.off(this.player_, 'play', this.handlePlay_);
  18138. this.off(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  18139. this.off(this.player_, 'timeupdate', this.seekToLiveEdge_);
  18140. }
  18141. /**
  18142. * The next seeked event is from the user. Meaning that any seek
  18143. * > 2s behind live will be considered behind live for real and
  18144. * liveTolerance will be ignored.
  18145. */
  18146. nextSeekedFromUser() {
  18147. this.nextSeekedFromUser_ = true;
  18148. }
  18149. /**
  18150. * stop tracking live playback
  18151. */
  18152. stopTracking() {
  18153. if (!this.isTracking()) {
  18154. return;
  18155. }
  18156. this.reset_();
  18157. this.trigger('liveedgechange');
  18158. }
  18159. /**
  18160. * A helper to get the player seekable end
  18161. * so that we don't have to null check everywhere
  18162. *
  18163. * @return {number}
  18164. * The furthest seekable end or Infinity.
  18165. */
  18166. seekableEnd() {
  18167. const seekable = this.player_.seekable();
  18168. const seekableEnds = [];
  18169. let i = seekable ? seekable.length : 0;
  18170. while (i--) {
  18171. seekableEnds.push(seekable.end(i));
  18172. }
  18173. // grab the furthest seekable end after sorting, or if there are none
  18174. // default to Infinity
  18175. return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;
  18176. }
  18177. /**
  18178. * A helper to get the player seekable start
  18179. * so that we don't have to null check everywhere
  18180. *
  18181. * @return {number}
  18182. * The earliest seekable start or 0.
  18183. */
  18184. seekableStart() {
  18185. const seekable = this.player_.seekable();
  18186. const seekableStarts = [];
  18187. let i = seekable ? seekable.length : 0;
  18188. while (i--) {
  18189. seekableStarts.push(seekable.start(i));
  18190. }
  18191. // grab the first seekable start after sorting, or if there are none
  18192. // default to 0
  18193. return seekableStarts.length ? seekableStarts.sort()[0] : 0;
  18194. }
  18195. /**
  18196. * Get the live time window aka
  18197. * the amount of time between seekable start and
  18198. * live current time.
  18199. *
  18200. * @return {number}
  18201. * The amount of seconds that are seekable in
  18202. * the live video.
  18203. */
  18204. liveWindow() {
  18205. const liveCurrentTime = this.liveCurrentTime();
  18206. // if liveCurrenTime is Infinity then we don't have a liveWindow at all
  18207. if (liveCurrentTime === Infinity) {
  18208. return 0;
  18209. }
  18210. return liveCurrentTime - this.seekableStart();
  18211. }
  18212. /**
  18213. * Determines if the player is live, only checks if this component
  18214. * is tracking live playback or not
  18215. *
  18216. * @return {boolean}
  18217. * Whether liveTracker is tracking
  18218. */
  18219. isLive() {
  18220. return this.isTracking();
  18221. }
  18222. /**
  18223. * Determines if currentTime is at the live edge and won't fall behind
  18224. * on each seekableendchange
  18225. *
  18226. * @return {boolean}
  18227. * Whether playback is at the live edge
  18228. */
  18229. atLiveEdge() {
  18230. return !this.behindLiveEdge();
  18231. }
  18232. /**
  18233. * get what we expect the live current time to be
  18234. *
  18235. * @return {number}
  18236. * The expected live current time
  18237. */
  18238. liveCurrentTime() {
  18239. return this.pastSeekEnd() + this.seekableEnd();
  18240. }
  18241. /**
  18242. * The number of seconds that have occurred after seekable end
  18243. * changed. This will be reset to 0 once seekable end changes.
  18244. *
  18245. * @return {number}
  18246. * Seconds past the current seekable end
  18247. */
  18248. pastSeekEnd() {
  18249. const seekableEnd = this.seekableEnd();
  18250. if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {
  18251. this.pastSeekEnd_ = 0;
  18252. }
  18253. this.lastSeekEnd_ = seekableEnd;
  18254. return this.pastSeekEnd_;
  18255. }
  18256. /**
  18257. * If we are currently behind the live edge, aka currentTime will be
  18258. * behind on a seekableendchange
  18259. *
  18260. * @return {boolean}
  18261. * If we are behind the live edge
  18262. */
  18263. behindLiveEdge() {
  18264. return this.behindLiveEdge_;
  18265. }
  18266. /**
  18267. * Whether live tracker is currently tracking or not.
  18268. */
  18269. isTracking() {
  18270. return typeof this.trackingInterval_ === 'number';
  18271. }
  18272. /**
  18273. * Seek to the live edge if we are behind the live edge
  18274. */
  18275. seekToLiveEdge() {
  18276. this.seekedBehindLive_ = false;
  18277. if (this.atLiveEdge()) {
  18278. return;
  18279. }
  18280. this.nextSeekedFromUser_ = false;
  18281. this.player_.currentTime(this.liveCurrentTime());
  18282. }
  18283. /**
  18284. * Dispose of liveTracker
  18285. */
  18286. dispose() {
  18287. this.stopTracking();
  18288. super.dispose();
  18289. }
  18290. }
  18291. Component$1.registerComponent('LiveTracker', LiveTracker);
  18292. /**
  18293. * Displays an element over the player which contains an optional title and
  18294. * description for the current content.
  18295. *
  18296. * Much of the code for this component originated in the now obsolete
  18297. * videojs-dock plugin: https://github.com/brightcove/videojs-dock/
  18298. *
  18299. * @extends Component
  18300. */
  18301. class TitleBar extends Component$1 {
  18302. constructor(player, options) {
  18303. super(player, options);
  18304. this.on('statechanged', e => this.updateDom_());
  18305. this.updateDom_();
  18306. }
  18307. /**
  18308. * Create the `TitleBar`'s DOM element
  18309. *
  18310. * @return {Element}
  18311. * The element that was created.
  18312. */
  18313. createEl() {
  18314. this.els = {
  18315. title: createEl('div', {
  18316. className: 'vjs-title-bar-title',
  18317. id: `vjs-title-bar-title-${newGUID()}`
  18318. }),
  18319. description: createEl('div', {
  18320. className: 'vjs-title-bar-description',
  18321. id: `vjs-title-bar-description-${newGUID()}`
  18322. })
  18323. };
  18324. return createEl('div', {
  18325. className: 'vjs-title-bar'
  18326. }, {}, Object.values(this.els));
  18327. }
  18328. /**
  18329. * Updates the DOM based on the component's state object.
  18330. */
  18331. updateDom_() {
  18332. const tech = this.player_.tech_;
  18333. const techEl = tech && tech.el_;
  18334. const techAriaAttrs = {
  18335. title: 'aria-labelledby',
  18336. description: 'aria-describedby'
  18337. };
  18338. ['title', 'description'].forEach(k => {
  18339. const value = this.state[k];
  18340. const el = this.els[k];
  18341. const techAriaAttr = techAriaAttrs[k];
  18342. emptyEl(el);
  18343. if (value) {
  18344. textContent(el, value);
  18345. }
  18346. // If there is a tech element available, update its ARIA attributes
  18347. // according to whether a title and/or description have been provided.
  18348. if (techEl) {
  18349. techEl.removeAttribute(techAriaAttr);
  18350. if (value) {
  18351. techEl.setAttribute(techAriaAttr, el.id);
  18352. }
  18353. }
  18354. });
  18355. if (this.state.title || this.state.description) {
  18356. this.show();
  18357. } else {
  18358. this.hide();
  18359. }
  18360. }
  18361. /**
  18362. * Update the contents of the title bar component with new title and
  18363. * description text.
  18364. *
  18365. * If both title and description are missing, the title bar will be hidden.
  18366. *
  18367. * If either title or description are present, the title bar will be visible.
  18368. *
  18369. * NOTE: Any previously set value will be preserved. To unset a previously
  18370. * set value, you must pass an empty string or null.
  18371. *
  18372. * For example:
  18373. *
  18374. * ```
  18375. * update({title: 'foo', description: 'bar'}) // title: 'foo', description: 'bar'
  18376. * update({description: 'bar2'}) // title: 'foo', description: 'bar2'
  18377. * update({title: ''}) // title: '', description: 'bar2'
  18378. * update({title: 'foo', description: null}) // title: 'foo', description: null
  18379. * ```
  18380. *
  18381. * @param {Object} [options={}]
  18382. * An options object. When empty, the title bar will be hidden.
  18383. *
  18384. * @param {string} [options.title]
  18385. * A title to display in the title bar.
  18386. *
  18387. * @param {string} [options.description]
  18388. * A description to display in the title bar.
  18389. */
  18390. update(options) {
  18391. this.setState(options);
  18392. }
  18393. /**
  18394. * Dispose the component.
  18395. */
  18396. dispose() {
  18397. const tech = this.player_.tech_;
  18398. const techEl = tech && tech.el_;
  18399. if (techEl) {
  18400. techEl.removeAttribute('aria-labelledby');
  18401. techEl.removeAttribute('aria-describedby');
  18402. }
  18403. super.dispose();
  18404. this.els = null;
  18405. }
  18406. }
  18407. Component$1.registerComponent('TitleBar', TitleBar);
  18408. /**
  18409. * This function is used to fire a sourceset when there is something
  18410. * similar to `mediaEl.load()` being called. It will try to find the source via
  18411. * the `src` attribute and then the `<source>` elements. It will then fire `sourceset`
  18412. * with the source that was found or empty string if we cannot know. If it cannot
  18413. * find a source then `sourceset` will not be fired.
  18414. *
  18415. * @param { import('./html5').default } tech
  18416. * The tech object that sourceset was setup on
  18417. *
  18418. * @return {boolean}
  18419. * returns false if the sourceset was not fired and true otherwise.
  18420. */
  18421. const sourcesetLoad = tech => {
  18422. const el = tech.el();
  18423. // if `el.src` is set, that source will be loaded.
  18424. if (el.hasAttribute('src')) {
  18425. tech.triggerSourceset(el.src);
  18426. return true;
  18427. }
  18428. /**
  18429. * Since there isn't a src property on the media element, source elements will be used for
  18430. * implementing the source selection algorithm. This happens asynchronously and
  18431. * for most cases were there is more than one source we cannot tell what source will
  18432. * be loaded, without re-implementing the source selection algorithm. At this time we are not
  18433. * going to do that. There are three special cases that we do handle here though:
  18434. *
  18435. * 1. If there are no sources, do not fire `sourceset`.
  18436. * 2. If there is only one `<source>` with a `src` property/attribute that is our `src`
  18437. * 3. If there is more than one `<source>` but all of them have the same `src` url.
  18438. * That will be our src.
  18439. */
  18440. const sources = tech.$$('source');
  18441. const srcUrls = [];
  18442. let src = '';
  18443. // if there are no sources, do not fire sourceset
  18444. if (!sources.length) {
  18445. return false;
  18446. }
  18447. // only count valid/non-duplicate source elements
  18448. for (let i = 0; i < sources.length; i++) {
  18449. const url = sources[i].src;
  18450. if (url && srcUrls.indexOf(url) === -1) {
  18451. srcUrls.push(url);
  18452. }
  18453. }
  18454. // there were no valid sources
  18455. if (!srcUrls.length) {
  18456. return false;
  18457. }
  18458. // there is only one valid source element url
  18459. // use that
  18460. if (srcUrls.length === 1) {
  18461. src = srcUrls[0];
  18462. }
  18463. tech.triggerSourceset(src);
  18464. return true;
  18465. };
  18466. /**
  18467. * our implementation of an `innerHTML` descriptor for browsers
  18468. * that do not have one.
  18469. */
  18470. const innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {
  18471. get() {
  18472. return this.cloneNode(true).innerHTML;
  18473. },
  18474. set(v) {
  18475. // make a dummy node to use innerHTML on
  18476. const dummy = document.createElement(this.nodeName.toLowerCase());
  18477. // set innerHTML to the value provided
  18478. dummy.innerHTML = v;
  18479. // make a document fragment to hold the nodes from dummy
  18480. const docFrag = document.createDocumentFragment();
  18481. // copy all of the nodes created by the innerHTML on dummy
  18482. // to the document fragment
  18483. while (dummy.childNodes.length) {
  18484. docFrag.appendChild(dummy.childNodes[0]);
  18485. }
  18486. // remove content
  18487. this.innerText = '';
  18488. // now we add all of that html in one by appending the
  18489. // document fragment. This is how innerHTML does it.
  18490. window.Element.prototype.appendChild.call(this, docFrag);
  18491. // then return the result that innerHTML's setter would
  18492. return this.innerHTML;
  18493. }
  18494. });
  18495. /**
  18496. * Get a property descriptor given a list of priorities and the
  18497. * property to get.
  18498. */
  18499. const getDescriptor = (priority, prop) => {
  18500. let descriptor = {};
  18501. for (let i = 0; i < priority.length; i++) {
  18502. descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
  18503. if (descriptor && descriptor.set && descriptor.get) {
  18504. break;
  18505. }
  18506. }
  18507. descriptor.enumerable = true;
  18508. descriptor.configurable = true;
  18509. return descriptor;
  18510. };
  18511. const getInnerHTMLDescriptor = tech => getDescriptor([tech.el(), window.HTMLMediaElement.prototype, window.Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');
  18512. /**
  18513. * Patches browser internal functions so that we can tell synchronously
  18514. * if a `<source>` was appended to the media element. For some reason this
  18515. * causes a `sourceset` if the the media element is ready and has no source.
  18516. * This happens when:
  18517. * - The page has just loaded and the media element does not have a source.
  18518. * - The media element was emptied of all sources, then `load()` was called.
  18519. *
  18520. * It does this by patching the following functions/properties when they are supported:
  18521. *
  18522. * - `append()` - can be used to add a `<source>` element to the media element
  18523. * - `appendChild()` - can be used to add a `<source>` element to the media element
  18524. * - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element
  18525. * - `innerHTML` - can be used to add a `<source>` element to the media element
  18526. *
  18527. * @param {Html5} tech
  18528. * The tech object that sourceset is being setup on.
  18529. */
  18530. const firstSourceWatch = function (tech) {
  18531. const el = tech.el();
  18532. // make sure firstSourceWatch isn't setup twice.
  18533. if (el.resetSourceWatch_) {
  18534. return;
  18535. }
  18536. const old = {};
  18537. const innerDescriptor = getInnerHTMLDescriptor(tech);
  18538. const appendWrapper = appendFn => (...args) => {
  18539. const retval = appendFn.apply(el, args);
  18540. sourcesetLoad(tech);
  18541. return retval;
  18542. };
  18543. ['append', 'appendChild', 'insertAdjacentHTML'].forEach(k => {
  18544. if (!el[k]) {
  18545. return;
  18546. }
  18547. // store the old function
  18548. old[k] = el[k];
  18549. // call the old function with a sourceset if a source
  18550. // was loaded
  18551. el[k] = appendWrapper(old[k]);
  18552. });
  18553. Object.defineProperty(el, 'innerHTML', merge$2(innerDescriptor, {
  18554. set: appendWrapper(innerDescriptor.set)
  18555. }));
  18556. el.resetSourceWatch_ = () => {
  18557. el.resetSourceWatch_ = null;
  18558. Object.keys(old).forEach(k => {
  18559. el[k] = old[k];
  18560. });
  18561. Object.defineProperty(el, 'innerHTML', innerDescriptor);
  18562. };
  18563. // on the first sourceset, we need to revert our changes
  18564. tech.one('sourceset', el.resetSourceWatch_);
  18565. };
  18566. /**
  18567. * our implementation of a `src` descriptor for browsers
  18568. * that do not have one
  18569. */
  18570. const srcDescriptorPolyfill = Object.defineProperty({}, 'src', {
  18571. get() {
  18572. if (this.hasAttribute('src')) {
  18573. return getAbsoluteURL(window.Element.prototype.getAttribute.call(this, 'src'));
  18574. }
  18575. return '';
  18576. },
  18577. set(v) {
  18578. window.Element.prototype.setAttribute.call(this, 'src', v);
  18579. return v;
  18580. }
  18581. });
  18582. const getSrcDescriptor = tech => getDescriptor([tech.el(), window.HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');
  18583. /**
  18584. * setup `sourceset` handling on the `Html5` tech. This function
  18585. * patches the following element properties/functions:
  18586. *
  18587. * - `src` - to determine when `src` is set
  18588. * - `setAttribute()` - to determine when `src` is set
  18589. * - `load()` - this re-triggers the source selection algorithm, and can
  18590. * cause a sourceset.
  18591. *
  18592. * If there is no source when we are adding `sourceset` support or during a `load()`
  18593. * we also patch the functions listed in `firstSourceWatch`.
  18594. *
  18595. * @param {Html5} tech
  18596. * The tech to patch
  18597. */
  18598. const setupSourceset = function (tech) {
  18599. if (!tech.featuresSourceset) {
  18600. return;
  18601. }
  18602. const el = tech.el();
  18603. // make sure sourceset isn't setup twice.
  18604. if (el.resetSourceset_) {
  18605. return;
  18606. }
  18607. const srcDescriptor = getSrcDescriptor(tech);
  18608. const oldSetAttribute = el.setAttribute;
  18609. const oldLoad = el.load;
  18610. Object.defineProperty(el, 'src', merge$2(srcDescriptor, {
  18611. set: v => {
  18612. const retval = srcDescriptor.set.call(el, v);
  18613. // we use the getter here to get the actual value set on src
  18614. tech.triggerSourceset(el.src);
  18615. return retval;
  18616. }
  18617. }));
  18618. el.setAttribute = (n, v) => {
  18619. const retval = oldSetAttribute.call(el, n, v);
  18620. if (/src/i.test(n)) {
  18621. tech.triggerSourceset(el.src);
  18622. }
  18623. return retval;
  18624. };
  18625. el.load = () => {
  18626. const retval = oldLoad.call(el);
  18627. // if load was called, but there was no source to fire
  18628. // sourceset on. We have to watch for a source append
  18629. // as that can trigger a `sourceset` when the media element
  18630. // has no source
  18631. if (!sourcesetLoad(tech)) {
  18632. tech.triggerSourceset('');
  18633. firstSourceWatch(tech);
  18634. }
  18635. return retval;
  18636. };
  18637. if (el.currentSrc) {
  18638. tech.triggerSourceset(el.currentSrc);
  18639. } else if (!sourcesetLoad(tech)) {
  18640. firstSourceWatch(tech);
  18641. }
  18642. el.resetSourceset_ = () => {
  18643. el.resetSourceset_ = null;
  18644. el.load = oldLoad;
  18645. el.setAttribute = oldSetAttribute;
  18646. Object.defineProperty(el, 'src', srcDescriptor);
  18647. if (el.resetSourceWatch_) {
  18648. el.resetSourceWatch_();
  18649. }
  18650. };
  18651. };
  18652. /**
  18653. * @file html5.js
  18654. */
  18655. /**
  18656. * HTML5 Media Controller - Wrapper for HTML5 Media API
  18657. *
  18658. * @mixes Tech~SourceHandlerAdditions
  18659. * @extends Tech
  18660. */
  18661. class Html5 extends Tech {
  18662. /**
  18663. * Create an instance of this Tech.
  18664. *
  18665. * @param {Object} [options]
  18666. * The key/value store of player options.
  18667. *
  18668. * @param {Function} [ready]
  18669. * Callback function to call when the `HTML5` Tech is ready.
  18670. */
  18671. constructor(options, ready) {
  18672. super(options, ready);
  18673. const source = options.source;
  18674. let crossoriginTracks = false;
  18675. this.featuresVideoFrameCallback = this.featuresVideoFrameCallback && this.el_.tagName === 'VIDEO';
  18676. // Set the source if one is provided
  18677. // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
  18678. // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
  18679. // anyway so the error gets fired.
  18680. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
  18681. this.setSource(source);
  18682. } else {
  18683. this.handleLateInit_(this.el_);
  18684. }
  18685. // setup sourceset after late sourceset/init
  18686. if (options.enableSourceset) {
  18687. this.setupSourcesetHandling_();
  18688. }
  18689. this.isScrubbing_ = false;
  18690. if (this.el_.hasChildNodes()) {
  18691. const nodes = this.el_.childNodes;
  18692. let nodesLength = nodes.length;
  18693. const removeNodes = [];
  18694. while (nodesLength--) {
  18695. const node = nodes[nodesLength];
  18696. const nodeName = node.nodeName.toLowerCase();
  18697. if (nodeName === 'track') {
  18698. if (!this.featuresNativeTextTracks) {
  18699. // Empty video tag tracks so the built-in player doesn't use them also.
  18700. // This may not be fast enough to stop HTML5 browsers from reading the tags
  18701. // so we'll need to turn off any default tracks if we're manually doing
  18702. // captions and subtitles. videoElement.textTracks
  18703. removeNodes.push(node);
  18704. } else {
  18705. // store HTMLTrackElement and TextTrack to remote list
  18706. this.remoteTextTrackEls().addTrackElement_(node);
  18707. this.remoteTextTracks().addTrack(node.track);
  18708. this.textTracks().addTrack(node.track);
  18709. if (!crossoriginTracks && !this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {
  18710. crossoriginTracks = true;
  18711. }
  18712. }
  18713. }
  18714. }
  18715. for (let i = 0; i < removeNodes.length; i++) {
  18716. this.el_.removeChild(removeNodes[i]);
  18717. }
  18718. }
  18719. this.proxyNativeTracks_();
  18720. if (this.featuresNativeTextTracks && crossoriginTracks) {
  18721. 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.');
  18722. }
  18723. // prevent iOS Safari from disabling metadata text tracks during native playback
  18724. this.restoreMetadataTracksInIOSNativePlayer_();
  18725. // Determine if native controls should be used
  18726. // Our goal should be to get the custom controls on mobile solid everywhere
  18727. // so we can remove this all together. Right now this will block custom
  18728. // controls on touch enabled laptops like the Chrome Pixel
  18729. if ((TOUCH_ENABLED || IS_IPHONE) && options.nativeControlsForTouch === true) {
  18730. this.setControls(true);
  18731. }
  18732. // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
  18733. // into a `fullscreenchange` event
  18734. this.proxyWebkitFullscreen_();
  18735. this.triggerReady();
  18736. }
  18737. /**
  18738. * Dispose of `HTML5` media element and remove all tracks.
  18739. */
  18740. dispose() {
  18741. if (this.el_ && this.el_.resetSourceset_) {
  18742. this.el_.resetSourceset_();
  18743. }
  18744. Html5.disposeMediaElement(this.el_);
  18745. this.options_ = null;
  18746. // tech will handle clearing of the emulated track list
  18747. super.dispose();
  18748. }
  18749. /**
  18750. * Modify the media element so that we can detect when
  18751. * the source is changed. Fires `sourceset` just after the source has changed
  18752. */
  18753. setupSourcesetHandling_() {
  18754. setupSourceset(this);
  18755. }
  18756. /**
  18757. * When a captions track is enabled in the iOS Safari native player, all other
  18758. * tracks are disabled (including metadata tracks), which nulls all of their
  18759. * associated cue points. This will restore metadata tracks to their pre-fullscreen
  18760. * state in those cases so that cue points are not needlessly lost.
  18761. *
  18762. * @private
  18763. */
  18764. restoreMetadataTracksInIOSNativePlayer_() {
  18765. const textTracks = this.textTracks();
  18766. let metadataTracksPreFullscreenState;
  18767. // captures a snapshot of every metadata track's current state
  18768. const takeMetadataTrackSnapshot = () => {
  18769. metadataTracksPreFullscreenState = [];
  18770. for (let i = 0; i < textTracks.length; i++) {
  18771. const track = textTracks[i];
  18772. if (track.kind === 'metadata') {
  18773. metadataTracksPreFullscreenState.push({
  18774. track,
  18775. storedMode: track.mode
  18776. });
  18777. }
  18778. }
  18779. };
  18780. // snapshot each metadata track's initial state, and update the snapshot
  18781. // each time there is a track 'change' event
  18782. takeMetadataTrackSnapshot();
  18783. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  18784. this.on('dispose', () => textTracks.removeEventListener('change', takeMetadataTrackSnapshot));
  18785. const restoreTrackMode = () => {
  18786. for (let i = 0; i < metadataTracksPreFullscreenState.length; i++) {
  18787. const storedTrack = metadataTracksPreFullscreenState[i];
  18788. if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {
  18789. storedTrack.track.mode = storedTrack.storedMode;
  18790. }
  18791. }
  18792. // we only want this handler to be executed on the first 'change' event
  18793. textTracks.removeEventListener('change', restoreTrackMode);
  18794. };
  18795. // when we enter fullscreen playback, stop updating the snapshot and
  18796. // restore all track modes to their pre-fullscreen state
  18797. this.on('webkitbeginfullscreen', () => {
  18798. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  18799. // remove the listener before adding it just in case it wasn't previously removed
  18800. textTracks.removeEventListener('change', restoreTrackMode);
  18801. textTracks.addEventListener('change', restoreTrackMode);
  18802. });
  18803. // start updating the snapshot again after leaving fullscreen
  18804. this.on('webkitendfullscreen', () => {
  18805. // remove the listener before adding it just in case it wasn't previously removed
  18806. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  18807. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  18808. // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback
  18809. textTracks.removeEventListener('change', restoreTrackMode);
  18810. });
  18811. }
  18812. /**
  18813. * Attempt to force override of tracks for the given type
  18814. *
  18815. * @param {string} type - Track type to override, possible values include 'Audio',
  18816. * 'Video', and 'Text'.
  18817. * @param {boolean} override - If set to true native audio/video will be overridden,
  18818. * otherwise native audio/video will potentially be used.
  18819. * @private
  18820. */
  18821. overrideNative_(type, override) {
  18822. // If there is no behavioral change don't add/remove listeners
  18823. if (override !== this[`featuresNative${type}Tracks`]) {
  18824. return;
  18825. }
  18826. const lowerCaseType = type.toLowerCase();
  18827. if (this[`${lowerCaseType}TracksListeners_`]) {
  18828. Object.keys(this[`${lowerCaseType}TracksListeners_`]).forEach(eventName => {
  18829. const elTracks = this.el()[`${lowerCaseType}Tracks`];
  18830. elTracks.removeEventListener(eventName, this[`${lowerCaseType}TracksListeners_`][eventName]);
  18831. });
  18832. }
  18833. this[`featuresNative${type}Tracks`] = !override;
  18834. this[`${lowerCaseType}TracksListeners_`] = null;
  18835. this.proxyNativeTracksForType_(lowerCaseType);
  18836. }
  18837. /**
  18838. * Attempt to force override of native audio tracks.
  18839. *
  18840. * @param {boolean} override - If set to true native audio will be overridden,
  18841. * otherwise native audio will potentially be used.
  18842. */
  18843. overrideNativeAudioTracks(override) {
  18844. this.overrideNative_('Audio', override);
  18845. }
  18846. /**
  18847. * Attempt to force override of native video tracks.
  18848. *
  18849. * @param {boolean} override - If set to true native video will be overridden,
  18850. * otherwise native video will potentially be used.
  18851. */
  18852. overrideNativeVideoTracks(override) {
  18853. this.overrideNative_('Video', override);
  18854. }
  18855. /**
  18856. * Proxy native track list events for the given type to our track
  18857. * lists if the browser we are playing in supports that type of track list.
  18858. *
  18859. * @param {string} name - Track type; values include 'audio', 'video', and 'text'
  18860. * @private
  18861. */
  18862. proxyNativeTracksForType_(name) {
  18863. const props = NORMAL[name];
  18864. const elTracks = this.el()[props.getterName];
  18865. const techTracks = this[props.getterName]();
  18866. if (!this[`featuresNative${props.capitalName}Tracks`] || !elTracks || !elTracks.addEventListener) {
  18867. return;
  18868. }
  18869. const listeners = {
  18870. change: e => {
  18871. const event = {
  18872. type: 'change',
  18873. target: techTracks,
  18874. currentTarget: techTracks,
  18875. srcElement: techTracks
  18876. };
  18877. techTracks.trigger(event);
  18878. // if we are a text track change event, we should also notify the
  18879. // remote text track list. This can potentially cause a false positive
  18880. // if we were to get a change event on a non-remote track and
  18881. // we triggered the event on the remote text track list which doesn't
  18882. // contain that track. However, best practices mean looping through the
  18883. // list of tracks and searching for the appropriate mode value, so,
  18884. // this shouldn't pose an issue
  18885. if (name === 'text') {
  18886. this[REMOTE.remoteText.getterName]().trigger(event);
  18887. }
  18888. },
  18889. addtrack(e) {
  18890. techTracks.addTrack(e.track);
  18891. },
  18892. removetrack(e) {
  18893. techTracks.removeTrack(e.track);
  18894. }
  18895. };
  18896. const removeOldTracks = function () {
  18897. const removeTracks = [];
  18898. for (let i = 0; i < techTracks.length; i++) {
  18899. let found = false;
  18900. for (let j = 0; j < elTracks.length; j++) {
  18901. if (elTracks[j] === techTracks[i]) {
  18902. found = true;
  18903. break;
  18904. }
  18905. }
  18906. if (!found) {
  18907. removeTracks.push(techTracks[i]);
  18908. }
  18909. }
  18910. while (removeTracks.length) {
  18911. techTracks.removeTrack(removeTracks.shift());
  18912. }
  18913. };
  18914. this[props.getterName + 'Listeners_'] = listeners;
  18915. Object.keys(listeners).forEach(eventName => {
  18916. const listener = listeners[eventName];
  18917. elTracks.addEventListener(eventName, listener);
  18918. this.on('dispose', e => elTracks.removeEventListener(eventName, listener));
  18919. });
  18920. // Remove (native) tracks that are not used anymore
  18921. this.on('loadstart', removeOldTracks);
  18922. this.on('dispose', e => this.off('loadstart', removeOldTracks));
  18923. }
  18924. /**
  18925. * Proxy all native track list events to our track lists if the browser we are playing
  18926. * in supports that type of track list.
  18927. *
  18928. * @private
  18929. */
  18930. proxyNativeTracks_() {
  18931. NORMAL.names.forEach(name => {
  18932. this.proxyNativeTracksForType_(name);
  18933. });
  18934. }
  18935. /**
  18936. * Create the `Html5` Tech's DOM element.
  18937. *
  18938. * @return {Element}
  18939. * The element that gets created.
  18940. */
  18941. createEl() {
  18942. let el = this.options_.tag;
  18943. // Check if this browser supports moving the element into the box.
  18944. // On the iPhone video will break if you move the element,
  18945. // So we have to create a brand new element.
  18946. // If we ingested the player div, we do not need to move the media element.
  18947. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
  18948. // If the original tag is still there, clone and remove it.
  18949. if (el) {
  18950. const clone = el.cloneNode(true);
  18951. if (el.parentNode) {
  18952. el.parentNode.insertBefore(clone, el);
  18953. }
  18954. Html5.disposeMediaElement(el);
  18955. el = clone;
  18956. } else {
  18957. el = document.createElement('video');
  18958. // determine if native controls should be used
  18959. const tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
  18960. const attributes = merge$2({}, tagAttributes);
  18961. if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
  18962. delete attributes.controls;
  18963. }
  18964. setAttributes(el, Object.assign(attributes, {
  18965. id: this.options_.techId,
  18966. class: 'vjs-tech'
  18967. }));
  18968. }
  18969. el.playerId = this.options_.playerId;
  18970. }
  18971. if (typeof this.options_.preload !== 'undefined') {
  18972. setAttribute(el, 'preload', this.options_.preload);
  18973. }
  18974. if (this.options_.disablePictureInPicture !== undefined) {
  18975. el.disablePictureInPicture = this.options_.disablePictureInPicture;
  18976. }
  18977. // Update specific tag settings, in case they were overridden
  18978. // `autoplay` has to be *last* so that `muted` and `playsinline` are present
  18979. // when iOS/Safari or other browsers attempt to autoplay.
  18980. const settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];
  18981. for (let i = 0; i < settingsAttrs.length; i++) {
  18982. const attr = settingsAttrs[i];
  18983. const value = this.options_[attr];
  18984. if (typeof value !== 'undefined') {
  18985. if (value) {
  18986. setAttribute(el, attr, attr);
  18987. } else {
  18988. removeAttribute(el, attr);
  18989. }
  18990. el[attr] = value;
  18991. }
  18992. }
  18993. return el;
  18994. }
  18995. /**
  18996. * This will be triggered if the loadstart event has already fired, before videojs was
  18997. * ready. Two known examples of when this can happen are:
  18998. * 1. If we're loading the playback object after it has started loading
  18999. * 2. The media is already playing the (often with autoplay on) then
  19000. *
  19001. * This function will fire another loadstart so that videojs can catchup.
  19002. *
  19003. * @fires Tech#loadstart
  19004. *
  19005. * @return {undefined}
  19006. * returns nothing.
  19007. */
  19008. handleLateInit_(el) {
  19009. if (el.networkState === 0 || el.networkState === 3) {
  19010. // The video element hasn't started loading the source yet
  19011. // or didn't find a source
  19012. return;
  19013. }
  19014. if (el.readyState === 0) {
  19015. // NetworkState is set synchronously BUT loadstart is fired at the
  19016. // end of the current stack, usually before setInterval(fn, 0).
  19017. // So at this point we know loadstart may have already fired or is
  19018. // about to fire, and either way the player hasn't seen it yet.
  19019. // We don't want to fire loadstart prematurely here and cause a
  19020. // double loadstart so we'll wait and see if it happens between now
  19021. // and the next loop, and fire it if not.
  19022. // HOWEVER, we also want to make sure it fires before loadedmetadata
  19023. // which could also happen between now and the next loop, so we'll
  19024. // watch for that also.
  19025. let loadstartFired = false;
  19026. const setLoadstartFired = function () {
  19027. loadstartFired = true;
  19028. };
  19029. this.on('loadstart', setLoadstartFired);
  19030. const triggerLoadstart = function () {
  19031. // We did miss the original loadstart. Make sure the player
  19032. // sees loadstart before loadedmetadata
  19033. if (!loadstartFired) {
  19034. this.trigger('loadstart');
  19035. }
  19036. };
  19037. this.on('loadedmetadata', triggerLoadstart);
  19038. this.ready(function () {
  19039. this.off('loadstart', setLoadstartFired);
  19040. this.off('loadedmetadata', triggerLoadstart);
  19041. if (!loadstartFired) {
  19042. // We did miss the original native loadstart. Fire it now.
  19043. this.trigger('loadstart');
  19044. }
  19045. });
  19046. return;
  19047. }
  19048. // From here on we know that loadstart already fired and we missed it.
  19049. // The other readyState events aren't as much of a problem if we double
  19050. // them, so not going to go to as much trouble as loadstart to prevent
  19051. // that unless we find reason to.
  19052. const eventsToTrigger = ['loadstart'];
  19053. // loadedmetadata: newly equal to HAVE_METADATA (1) or greater
  19054. eventsToTrigger.push('loadedmetadata');
  19055. // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
  19056. if (el.readyState >= 2) {
  19057. eventsToTrigger.push('loadeddata');
  19058. }
  19059. // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
  19060. if (el.readyState >= 3) {
  19061. eventsToTrigger.push('canplay');
  19062. }
  19063. // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
  19064. if (el.readyState >= 4) {
  19065. eventsToTrigger.push('canplaythrough');
  19066. }
  19067. // We still need to give the player time to add event listeners
  19068. this.ready(function () {
  19069. eventsToTrigger.forEach(function (type) {
  19070. this.trigger(type);
  19071. }, this);
  19072. });
  19073. }
  19074. /**
  19075. * Set whether we are scrubbing or not.
  19076. * This is used to decide whether we should use `fastSeek` or not.
  19077. * `fastSeek` is used to provide trick play on Safari browsers.
  19078. *
  19079. * @param {boolean} isScrubbing
  19080. * - true for we are currently scrubbing
  19081. * - false for we are no longer scrubbing
  19082. */
  19083. setScrubbing(isScrubbing) {
  19084. this.isScrubbing_ = isScrubbing;
  19085. }
  19086. /**
  19087. * Get whether we are scrubbing or not.
  19088. *
  19089. * @return {boolean} isScrubbing
  19090. * - true for we are currently scrubbing
  19091. * - false for we are no longer scrubbing
  19092. */
  19093. scrubbing() {
  19094. return this.isScrubbing_;
  19095. }
  19096. /**
  19097. * Set current time for the `HTML5` tech.
  19098. *
  19099. * @param {number} seconds
  19100. * Set the current time of the media to this.
  19101. */
  19102. setCurrentTime(seconds) {
  19103. try {
  19104. if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {
  19105. this.el_.fastSeek(seconds);
  19106. } else {
  19107. this.el_.currentTime = seconds;
  19108. }
  19109. } catch (e) {
  19110. log$1(e, 'Video is not ready. (Video.js)');
  19111. // this.warning(VideoJS.warnings.videoNotReady);
  19112. }
  19113. }
  19114. /**
  19115. * Get the current duration of the HTML5 media element.
  19116. *
  19117. * @return {number}
  19118. * The duration of the media or 0 if there is no duration.
  19119. */
  19120. duration() {
  19121. // Android Chrome will report duration as Infinity for VOD HLS until after
  19122. // playback has started, which triggers the live display erroneously.
  19123. // Return NaN if playback has not started and trigger a durationupdate once
  19124. // the duration can be reliably known.
  19125. if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
  19126. // Wait for the first `timeupdate` with currentTime > 0 - there may be
  19127. // several with 0
  19128. const checkProgress = () => {
  19129. if (this.el_.currentTime > 0) {
  19130. // Trigger durationchange for genuinely live video
  19131. if (this.el_.duration === Infinity) {
  19132. this.trigger('durationchange');
  19133. }
  19134. this.off('timeupdate', checkProgress);
  19135. }
  19136. };
  19137. this.on('timeupdate', checkProgress);
  19138. return NaN;
  19139. }
  19140. return this.el_.duration || NaN;
  19141. }
  19142. /**
  19143. * Get the current width of the HTML5 media element.
  19144. *
  19145. * @return {number}
  19146. * The width of the HTML5 media element.
  19147. */
  19148. width() {
  19149. return this.el_.offsetWidth;
  19150. }
  19151. /**
  19152. * Get the current height of the HTML5 media element.
  19153. *
  19154. * @return {number}
  19155. * The height of the HTML5 media element.
  19156. */
  19157. height() {
  19158. return this.el_.offsetHeight;
  19159. }
  19160. /**
  19161. * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into
  19162. * `fullscreenchange` event.
  19163. *
  19164. * @private
  19165. * @fires fullscreenchange
  19166. * @listens webkitendfullscreen
  19167. * @listens webkitbeginfullscreen
  19168. * @listens webkitbeginfullscreen
  19169. */
  19170. proxyWebkitFullscreen_() {
  19171. if (!('webkitDisplayingFullscreen' in this.el_)) {
  19172. return;
  19173. }
  19174. const endFn = function () {
  19175. this.trigger('fullscreenchange', {
  19176. isFullscreen: false
  19177. });
  19178. // Safari will sometimes set controls on the videoelement when existing fullscreen.
  19179. if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {
  19180. this.el_.controls = false;
  19181. }
  19182. };
  19183. const beginFn = function () {
  19184. if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {
  19185. this.one('webkitendfullscreen', endFn);
  19186. this.trigger('fullscreenchange', {
  19187. isFullscreen: true,
  19188. // set a flag in case another tech triggers fullscreenchange
  19189. nativeIOSFullscreen: true
  19190. });
  19191. }
  19192. };
  19193. this.on('webkitbeginfullscreen', beginFn);
  19194. this.on('dispose', () => {
  19195. this.off('webkitbeginfullscreen', beginFn);
  19196. this.off('webkitendfullscreen', endFn);
  19197. });
  19198. }
  19199. /**
  19200. * Check if fullscreen is supported on the video el.
  19201. *
  19202. * @return {boolean}
  19203. * - True if fullscreen is supported.
  19204. * - False if fullscreen is not supported.
  19205. */
  19206. supportsFullScreen() {
  19207. return typeof this.el_.webkitEnterFullScreen === 'function';
  19208. }
  19209. /**
  19210. * Request that the `HTML5` Tech enter fullscreen.
  19211. */
  19212. enterFullScreen() {
  19213. const video = this.el_;
  19214. if (video.paused && video.networkState <= video.HAVE_METADATA) {
  19215. // attempt to prime the video element for programmatic access
  19216. // this isn't necessary on the desktop but shouldn't hurt
  19217. silencePromise(this.el_.play());
  19218. // playing and pausing synchronously during the transition to fullscreen
  19219. // can get iOS ~6.1 devices into a play/pause loop
  19220. this.setTimeout(function () {
  19221. video.pause();
  19222. try {
  19223. video.webkitEnterFullScreen();
  19224. } catch (e) {
  19225. this.trigger('fullscreenerror', e);
  19226. }
  19227. }, 0);
  19228. } else {
  19229. try {
  19230. video.webkitEnterFullScreen();
  19231. } catch (e) {
  19232. this.trigger('fullscreenerror', e);
  19233. }
  19234. }
  19235. }
  19236. /**
  19237. * Request that the `HTML5` Tech exit fullscreen.
  19238. */
  19239. exitFullScreen() {
  19240. if (!this.el_.webkitDisplayingFullscreen) {
  19241. this.trigger('fullscreenerror', new Error('The video is not fullscreen'));
  19242. return;
  19243. }
  19244. this.el_.webkitExitFullScreen();
  19245. }
  19246. /**
  19247. * Create a floating video window always on top of other windows so that users may
  19248. * continue consuming media while they interact with other content sites, or
  19249. * applications on their device.
  19250. *
  19251. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  19252. *
  19253. * @return {Promise}
  19254. * A promise with a Picture-in-Picture window.
  19255. */
  19256. requestPictureInPicture() {
  19257. return this.el_.requestPictureInPicture();
  19258. }
  19259. /**
  19260. * Native requestVideoFrameCallback if supported by browser/tech, or fallback
  19261. * Don't use rVCF on Safari when DRM is playing, as it doesn't fire
  19262. * Needs to be checked later than the constructor
  19263. * This will be a false positive for clear sources loaded after a Fairplay source
  19264. *
  19265. * @param {function} cb function to call
  19266. * @return {number} id of request
  19267. */
  19268. requestVideoFrameCallback(cb) {
  19269. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  19270. return this.el_.requestVideoFrameCallback(cb);
  19271. }
  19272. return super.requestVideoFrameCallback(cb);
  19273. }
  19274. /**
  19275. * Native or fallback requestVideoFrameCallback
  19276. *
  19277. * @param {number} id request id to cancel
  19278. */
  19279. cancelVideoFrameCallback(id) {
  19280. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  19281. this.el_.cancelVideoFrameCallback(id);
  19282. } else {
  19283. super.cancelVideoFrameCallback(id);
  19284. }
  19285. }
  19286. /**
  19287. * A getter/setter for the `Html5` Tech's source object.
  19288. * > Note: Please use {@link Html5#setSource}
  19289. *
  19290. * @param {Tech~SourceObject} [src]
  19291. * The source object you want to set on the `HTML5` techs element.
  19292. *
  19293. * @return {Tech~SourceObject|undefined}
  19294. * - The current source object when a source is not passed in.
  19295. * - undefined when setting
  19296. *
  19297. * @deprecated Since version 5.
  19298. */
  19299. src(src) {
  19300. if (src === undefined) {
  19301. return this.el_.src;
  19302. }
  19303. // Setting src through `src` instead of `setSrc` will be deprecated
  19304. this.setSrc(src);
  19305. }
  19306. /**
  19307. * Reset the tech by removing all sources and then calling
  19308. * {@link Html5.resetMediaElement}.
  19309. */
  19310. reset() {
  19311. Html5.resetMediaElement(this.el_);
  19312. }
  19313. /**
  19314. * Get the current source on the `HTML5` Tech. Falls back to returning the source from
  19315. * the HTML5 media element.
  19316. *
  19317. * @return {Tech~SourceObject}
  19318. * The current source object from the HTML5 tech. With a fallback to the
  19319. * elements source.
  19320. */
  19321. currentSrc() {
  19322. if (this.currentSource_) {
  19323. return this.currentSource_.src;
  19324. }
  19325. return this.el_.currentSrc;
  19326. }
  19327. /**
  19328. * Set controls attribute for the HTML5 media Element.
  19329. *
  19330. * @param {string} val
  19331. * Value to set the controls attribute to
  19332. */
  19333. setControls(val) {
  19334. this.el_.controls = !!val;
  19335. }
  19336. /**
  19337. * Create and returns a remote {@link TextTrack} object.
  19338. *
  19339. * @param {string} kind
  19340. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  19341. *
  19342. * @param {string} [label]
  19343. * Label to identify the text track
  19344. *
  19345. * @param {string} [language]
  19346. * Two letter language abbreviation
  19347. *
  19348. * @return {TextTrack}
  19349. * The TextTrack that gets created.
  19350. */
  19351. addTextTrack(kind, label, language) {
  19352. if (!this.featuresNativeTextTracks) {
  19353. return super.addTextTrack(kind, label, language);
  19354. }
  19355. return this.el_.addTextTrack(kind, label, language);
  19356. }
  19357. /**
  19358. * Creates either native TextTrack or an emulated TextTrack depending
  19359. * on the value of `featuresNativeTextTracks`
  19360. *
  19361. * @param {Object} options
  19362. * The object should contain the options to initialize the TextTrack with.
  19363. *
  19364. * @param {string} [options.kind]
  19365. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  19366. *
  19367. * @param {string} [options.label]
  19368. * Label to identify the text track
  19369. *
  19370. * @param {string} [options.language]
  19371. * Two letter language abbreviation.
  19372. *
  19373. * @param {boolean} [options.default]
  19374. * Default this track to on.
  19375. *
  19376. * @param {string} [options.id]
  19377. * The internal id to assign this track.
  19378. *
  19379. * @param {string} [options.src]
  19380. * A source url for the track.
  19381. *
  19382. * @return {HTMLTrackElement}
  19383. * The track element that gets created.
  19384. */
  19385. createRemoteTextTrack(options) {
  19386. if (!this.featuresNativeTextTracks) {
  19387. return super.createRemoteTextTrack(options);
  19388. }
  19389. const htmlTrackElement = document.createElement('track');
  19390. if (options.kind) {
  19391. htmlTrackElement.kind = options.kind;
  19392. }
  19393. if (options.label) {
  19394. htmlTrackElement.label = options.label;
  19395. }
  19396. if (options.language || options.srclang) {
  19397. htmlTrackElement.srclang = options.language || options.srclang;
  19398. }
  19399. if (options.default) {
  19400. htmlTrackElement.default = options.default;
  19401. }
  19402. if (options.id) {
  19403. htmlTrackElement.id = options.id;
  19404. }
  19405. if (options.src) {
  19406. htmlTrackElement.src = options.src;
  19407. }
  19408. return htmlTrackElement;
  19409. }
  19410. /**
  19411. * Creates a remote text track object and returns an html track element.
  19412. *
  19413. * @param {Object} options The object should contain values for
  19414. * kind, language, label, and src (location of the WebVTT file)
  19415. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack
  19416. * will not be removed from the TextTrackList and HtmlTrackElementList
  19417. * after a source change
  19418. * @return {HTMLTrackElement} An Html Track Element.
  19419. * This can be an emulated {@link HTMLTrackElement} or a native one.
  19420. *
  19421. */
  19422. addRemoteTextTrack(options, manualCleanup) {
  19423. const htmlTrackElement = super.addRemoteTextTrack(options, manualCleanup);
  19424. if (this.featuresNativeTextTracks) {
  19425. this.el().appendChild(htmlTrackElement);
  19426. }
  19427. return htmlTrackElement;
  19428. }
  19429. /**
  19430. * Remove remote `TextTrack` from `TextTrackList` object
  19431. *
  19432. * @param {TextTrack} track
  19433. * `TextTrack` object to remove
  19434. */
  19435. removeRemoteTextTrack(track) {
  19436. super.removeRemoteTextTrack(track);
  19437. if (this.featuresNativeTextTracks) {
  19438. const tracks = this.$$('track');
  19439. let i = tracks.length;
  19440. while (i--) {
  19441. if (track === tracks[i] || track === tracks[i].track) {
  19442. this.el().removeChild(tracks[i]);
  19443. }
  19444. }
  19445. }
  19446. }
  19447. /**
  19448. * Gets available media playback quality metrics as specified by the W3C's Media
  19449. * Playback Quality API.
  19450. *
  19451. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  19452. *
  19453. * @return {Object}
  19454. * An object with supported media playback quality metrics
  19455. */
  19456. getVideoPlaybackQuality() {
  19457. if (typeof this.el().getVideoPlaybackQuality === 'function') {
  19458. return this.el().getVideoPlaybackQuality();
  19459. }
  19460. const videoPlaybackQuality = {};
  19461. if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {
  19462. videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
  19463. videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
  19464. }
  19465. if (window.performance) {
  19466. videoPlaybackQuality.creationTime = window.performance.now();
  19467. }
  19468. return videoPlaybackQuality;
  19469. }
  19470. }
  19471. /* HTML5 Support Testing ---------------------------------------------------- */
  19472. /**
  19473. * Element for testing browser HTML5 media capabilities
  19474. *
  19475. * @type {Element}
  19476. * @constant
  19477. * @private
  19478. */
  19479. defineLazyProperty(Html5, 'TEST_VID', function () {
  19480. if (!isReal()) {
  19481. return;
  19482. }
  19483. const video = document.createElement('video');
  19484. const track = document.createElement('track');
  19485. track.kind = 'captions';
  19486. track.srclang = 'en';
  19487. track.label = 'English';
  19488. video.appendChild(track);
  19489. return video;
  19490. });
  19491. /**
  19492. * Check if HTML5 media is supported by this browser/device.
  19493. *
  19494. * @return {boolean}
  19495. * - True if HTML5 media is supported.
  19496. * - False if HTML5 media is not supported.
  19497. */
  19498. Html5.isSupported = function () {
  19499. // IE with no Media Player is a LIAR! (#984)
  19500. try {
  19501. Html5.TEST_VID.volume = 0.5;
  19502. } catch (e) {
  19503. return false;
  19504. }
  19505. return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
  19506. };
  19507. /**
  19508. * Check if the tech can support the given type
  19509. *
  19510. * @param {string} type
  19511. * The mimetype to check
  19512. * @return {string} 'probably', 'maybe', or '' (empty string)
  19513. */
  19514. Html5.canPlayType = function (type) {
  19515. return Html5.TEST_VID.canPlayType(type);
  19516. };
  19517. /**
  19518. * Check if the tech can support the given source
  19519. *
  19520. * @param {Object} srcObj
  19521. * The source object
  19522. * @param {Object} options
  19523. * The options passed to the tech
  19524. * @return {string} 'probably', 'maybe', or '' (empty string)
  19525. */
  19526. Html5.canPlaySource = function (srcObj, options) {
  19527. return Html5.canPlayType(srcObj.type);
  19528. };
  19529. /**
  19530. * Check if the volume can be changed in this browser/device.
  19531. * Volume cannot be changed in a lot of mobile devices.
  19532. * Specifically, it can't be changed from 1 on iOS.
  19533. *
  19534. * @return {boolean}
  19535. * - True if volume can be controlled
  19536. * - False otherwise
  19537. */
  19538. Html5.canControlVolume = function () {
  19539. // IE will error if Windows Media Player not installed #3315
  19540. try {
  19541. const volume = Html5.TEST_VID.volume;
  19542. Html5.TEST_VID.volume = volume / 2 + 0.1;
  19543. const canControl = volume !== Html5.TEST_VID.volume;
  19544. // With the introduction of iOS 15, there are cases where the volume is read as
  19545. // changed but reverts back to its original state at the start of the next tick.
  19546. // To determine whether volume can be controlled on iOS,
  19547. // a timeout is set and the volume is checked asynchronously.
  19548. // Since `features` doesn't currently work asynchronously, the value is manually set.
  19549. if (canControl && IS_IOS) {
  19550. window.setTimeout(() => {
  19551. if (Html5 && Html5.prototype) {
  19552. Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;
  19553. }
  19554. });
  19555. // default iOS to false, which will be updated in the timeout above.
  19556. return false;
  19557. }
  19558. return canControl;
  19559. } catch (e) {
  19560. return false;
  19561. }
  19562. };
  19563. /**
  19564. * Check if the volume can be muted in this browser/device.
  19565. * Some devices, e.g. iOS, don't allow changing volume
  19566. * but permits muting/unmuting.
  19567. *
  19568. * @return {boolean}
  19569. * - True if volume can be muted
  19570. * - False otherwise
  19571. */
  19572. Html5.canMuteVolume = function () {
  19573. try {
  19574. const muted = Html5.TEST_VID.muted;
  19575. // in some versions of iOS muted property doesn't always
  19576. // work, so we want to set both property and attribute
  19577. Html5.TEST_VID.muted = !muted;
  19578. if (Html5.TEST_VID.muted) {
  19579. setAttribute(Html5.TEST_VID, 'muted', 'muted');
  19580. } else {
  19581. removeAttribute(Html5.TEST_VID, 'muted', 'muted');
  19582. }
  19583. return muted !== Html5.TEST_VID.muted;
  19584. } catch (e) {
  19585. return false;
  19586. }
  19587. };
  19588. /**
  19589. * Check if the playback rate can be changed in this browser/device.
  19590. *
  19591. * @return {boolean}
  19592. * - True if playback rate can be controlled
  19593. * - False otherwise
  19594. */
  19595. Html5.canControlPlaybackRate = function () {
  19596. // Playback rate API is implemented in Android Chrome, but doesn't do anything
  19597. // https://github.com/videojs/video.js/issues/3180
  19598. if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
  19599. return false;
  19600. }
  19601. // IE will error if Windows Media Player not installed #3315
  19602. try {
  19603. const playbackRate = Html5.TEST_VID.playbackRate;
  19604. Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
  19605. return playbackRate !== Html5.TEST_VID.playbackRate;
  19606. } catch (e) {
  19607. return false;
  19608. }
  19609. };
  19610. /**
  19611. * Check if we can override a video/audio elements attributes, with
  19612. * Object.defineProperty.
  19613. *
  19614. * @return {boolean}
  19615. * - True if builtin attributes can be overridden
  19616. * - False otherwise
  19617. */
  19618. Html5.canOverrideAttributes = function () {
  19619. // if we cannot overwrite the src/innerHTML property, there is no support
  19620. // iOS 7 safari for instance cannot do this.
  19621. try {
  19622. const noop = () => {};
  19623. Object.defineProperty(document.createElement('video'), 'src', {
  19624. get: noop,
  19625. set: noop
  19626. });
  19627. Object.defineProperty(document.createElement('audio'), 'src', {
  19628. get: noop,
  19629. set: noop
  19630. });
  19631. Object.defineProperty(document.createElement('video'), 'innerHTML', {
  19632. get: noop,
  19633. set: noop
  19634. });
  19635. Object.defineProperty(document.createElement('audio'), 'innerHTML', {
  19636. get: noop,
  19637. set: noop
  19638. });
  19639. } catch (e) {
  19640. return false;
  19641. }
  19642. return true;
  19643. };
  19644. /**
  19645. * Check to see if native `TextTrack`s are supported by this browser/device.
  19646. *
  19647. * @return {boolean}
  19648. * - True if native `TextTrack`s are supported.
  19649. * - False otherwise
  19650. */
  19651. Html5.supportsNativeTextTracks = function () {
  19652. return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
  19653. };
  19654. /**
  19655. * Check to see if native `VideoTrack`s are supported by this browser/device
  19656. *
  19657. * @return {boolean}
  19658. * - True if native `VideoTrack`s are supported.
  19659. * - False otherwise
  19660. */
  19661. Html5.supportsNativeVideoTracks = function () {
  19662. return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
  19663. };
  19664. /**
  19665. * Check to see if native `AudioTrack`s are supported by this browser/device
  19666. *
  19667. * @return {boolean}
  19668. * - True if native `AudioTrack`s are supported.
  19669. * - False otherwise
  19670. */
  19671. Html5.supportsNativeAudioTracks = function () {
  19672. return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
  19673. };
  19674. /**
  19675. * An array of events available on the Html5 tech.
  19676. *
  19677. * @private
  19678. * @type {Array}
  19679. */
  19680. 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'];
  19681. /**
  19682. * Boolean indicating whether the `Tech` supports volume control.
  19683. *
  19684. * @type {boolean}
  19685. * @default {@link Html5.canControlVolume}
  19686. */
  19687. /**
  19688. * Boolean indicating whether the `Tech` supports muting volume.
  19689. *
  19690. * @type {boolean}
  19691. * @default {@link Html5.canMuteVolume}
  19692. */
  19693. /**
  19694. * Boolean indicating whether the `Tech` supports changing the speed at which the media
  19695. * plays. Examples:
  19696. * - Set player to play 2x (twice) as fast
  19697. * - Set player to play 0.5x (half) as fast
  19698. *
  19699. * @type {boolean}
  19700. * @default {@link Html5.canControlPlaybackRate}
  19701. */
  19702. /**
  19703. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  19704. *
  19705. * @type {boolean}
  19706. * @default
  19707. */
  19708. /**
  19709. * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.
  19710. *
  19711. * @type {boolean}
  19712. * @default {@link Html5.supportsNativeTextTracks}
  19713. */
  19714. /**
  19715. * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.
  19716. *
  19717. * @type {boolean}
  19718. * @default {@link Html5.supportsNativeVideoTracks}
  19719. */
  19720. /**
  19721. * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.
  19722. *
  19723. * @type {boolean}
  19724. * @default {@link Html5.supportsNativeAudioTracks}
  19725. */
  19726. [['featuresMuteControl', 'canMuteVolume'], ['featuresPlaybackRate', 'canControlPlaybackRate'], ['featuresSourceset', 'canOverrideAttributes'], ['featuresNativeTextTracks', 'supportsNativeTextTracks'], ['featuresNativeVideoTracks', 'supportsNativeVideoTracks'], ['featuresNativeAudioTracks', 'supportsNativeAudioTracks']].forEach(function ([key, fn]) {
  19727. defineLazyProperty(Html5.prototype, key, () => Html5[fn](), true);
  19728. });
  19729. Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
  19730. /**
  19731. * Boolean indicating whether the `HTML5` tech currently supports the media element
  19732. * moving in the DOM. iOS breaks if you move the media element, so this is set this to
  19733. * false there. Everywhere else this should be true.
  19734. *
  19735. * @type {boolean}
  19736. * @default
  19737. */
  19738. Html5.prototype.movingMediaElementInDOM = !IS_IOS;
  19739. // TODO: Previous comment: No longer appears to be used. Can probably be removed.
  19740. // Is this true?
  19741. /**
  19742. * Boolean indicating whether the `HTML5` tech currently supports automatic media resize
  19743. * when going into fullscreen.
  19744. *
  19745. * @type {boolean}
  19746. * @default
  19747. */
  19748. Html5.prototype.featuresFullscreenResize = true;
  19749. /**
  19750. * Boolean indicating whether the `HTML5` tech currently supports the progress event.
  19751. * If this is false, manual `progress` events will be triggered instead.
  19752. *
  19753. * @type {boolean}
  19754. * @default
  19755. */
  19756. Html5.prototype.featuresProgressEvents = true;
  19757. /**
  19758. * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.
  19759. * If this is false, manual `timeupdate` events will be triggered instead.
  19760. *
  19761. * @default
  19762. */
  19763. Html5.prototype.featuresTimeupdateEvents = true;
  19764. /**
  19765. * Whether the HTML5 el supports `requestVideoFrameCallback`
  19766. *
  19767. * @type {boolean}
  19768. */
  19769. Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback);
  19770. Html5.disposeMediaElement = function (el) {
  19771. if (!el) {
  19772. return;
  19773. }
  19774. if (el.parentNode) {
  19775. el.parentNode.removeChild(el);
  19776. }
  19777. // remove any child track or source nodes to prevent their loading
  19778. while (el.hasChildNodes()) {
  19779. el.removeChild(el.firstChild);
  19780. }
  19781. // remove any src reference. not setting `src=''` because that causes a warning
  19782. // in firefox
  19783. el.removeAttribute('src');
  19784. // force the media element to update its loading state by calling load()
  19785. // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
  19786. if (typeof el.load === 'function') {
  19787. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  19788. (function () {
  19789. try {
  19790. el.load();
  19791. } catch (e) {
  19792. // not supported
  19793. }
  19794. })();
  19795. }
  19796. };
  19797. Html5.resetMediaElement = function (el) {
  19798. if (!el) {
  19799. return;
  19800. }
  19801. const sources = el.querySelectorAll('source');
  19802. let i = sources.length;
  19803. while (i--) {
  19804. el.removeChild(sources[i]);
  19805. }
  19806. // remove any src reference.
  19807. // not setting `src=''` because that throws an error
  19808. el.removeAttribute('src');
  19809. if (typeof el.load === 'function') {
  19810. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  19811. (function () {
  19812. try {
  19813. el.load();
  19814. } catch (e) {
  19815. // satisfy linter
  19816. }
  19817. })();
  19818. }
  19819. };
  19820. /* Native HTML5 element property wrapping ----------------------------------- */
  19821. // Wrap native boolean attributes with getters that check both property and attribute
  19822. // The list is as followed:
  19823. // muted, defaultMuted, autoplay, controls, loop, playsinline
  19824. [
  19825. /**
  19826. * Get the value of `muted` from the media element. `muted` indicates
  19827. * that the volume for the media should be set to silent. This does not actually change
  19828. * the `volume` attribute.
  19829. *
  19830. * @method Html5#muted
  19831. * @return {boolean}
  19832. * - True if the value of `volume` should be ignored and the audio set to silent.
  19833. * - False if the value of `volume` should be used.
  19834. *
  19835. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  19836. */
  19837. 'muted',
  19838. /**
  19839. * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
  19840. * whether the media should start muted or not. Only changes the default state of the
  19841. * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
  19842. * current state.
  19843. *
  19844. * @method Html5#defaultMuted
  19845. * @return {boolean}
  19846. * - The value of `defaultMuted` from the media element.
  19847. * - True indicates that the media should start muted.
  19848. * - False indicates that the media should not start muted
  19849. *
  19850. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  19851. */
  19852. 'defaultMuted',
  19853. /**
  19854. * Get the value of `autoplay` from the media element. `autoplay` indicates
  19855. * that the media should start to play as soon as the page is ready.
  19856. *
  19857. * @method Html5#autoplay
  19858. * @return {boolean}
  19859. * - The value of `autoplay` from the media element.
  19860. * - True indicates that the media should start as soon as the page loads.
  19861. * - False indicates that the media should not start as soon as the page loads.
  19862. *
  19863. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  19864. */
  19865. 'autoplay',
  19866. /**
  19867. * Get the value of `controls` from the media element. `controls` indicates
  19868. * whether the native media controls should be shown or hidden.
  19869. *
  19870. * @method Html5#controls
  19871. * @return {boolean}
  19872. * - The value of `controls` from the media element.
  19873. * - True indicates that native controls should be showing.
  19874. * - False indicates that native controls should be hidden.
  19875. *
  19876. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
  19877. */
  19878. 'controls',
  19879. /**
  19880. * Get the value of `loop` from the media element. `loop` indicates
  19881. * that the media should return to the start of the media and continue playing once
  19882. * it reaches the end.
  19883. *
  19884. * @method Html5#loop
  19885. * @return {boolean}
  19886. * - The value of `loop` from the media element.
  19887. * - True indicates that playback should seek back to start once
  19888. * the end of a media is reached.
  19889. * - False indicates that playback should not loop back to the start when the
  19890. * end of the media is reached.
  19891. *
  19892. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  19893. */
  19894. 'loop',
  19895. /**
  19896. * Get the value of `playsinline` from the media element. `playsinline` indicates
  19897. * to the browser that non-fullscreen playback is preferred when fullscreen
  19898. * playback is the native default, such as in iOS Safari.
  19899. *
  19900. * @method Html5#playsinline
  19901. * @return {boolean}
  19902. * - The value of `playsinline` from the media element.
  19903. * - True indicates that the media should play inline.
  19904. * - False indicates that the media should not play inline.
  19905. *
  19906. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  19907. */
  19908. 'playsinline'].forEach(function (prop) {
  19909. Html5.prototype[prop] = function () {
  19910. return this.el_[prop] || this.el_.hasAttribute(prop);
  19911. };
  19912. });
  19913. // Wrap native boolean attributes with setters that set both property and attribute
  19914. // The list is as followed:
  19915. // setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline
  19916. // setControls is special-cased above
  19917. [
  19918. /**
  19919. * Set the value of `muted` on the media element. `muted` indicates that the current
  19920. * audio level should be silent.
  19921. *
  19922. * @method Html5#setMuted
  19923. * @param {boolean} muted
  19924. * - True if the audio should be set to silent
  19925. * - False otherwise
  19926. *
  19927. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  19928. */
  19929. 'muted',
  19930. /**
  19931. * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
  19932. * audio level should be silent, but will only effect the muted level on initial playback..
  19933. *
  19934. * @method Html5.prototype.setDefaultMuted
  19935. * @param {boolean} defaultMuted
  19936. * - True if the audio should be set to silent
  19937. * - False otherwise
  19938. *
  19939. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  19940. */
  19941. 'defaultMuted',
  19942. /**
  19943. * Set the value of `autoplay` on the media element. `autoplay` indicates
  19944. * that the media should start to play as soon as the page is ready.
  19945. *
  19946. * @method Html5#setAutoplay
  19947. * @param {boolean} autoplay
  19948. * - True indicates that the media should start as soon as the page loads.
  19949. * - False indicates that the media should not start as soon as the page loads.
  19950. *
  19951. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  19952. */
  19953. 'autoplay',
  19954. /**
  19955. * Set the value of `loop` on the media element. `loop` indicates
  19956. * that the media should return to the start of the media and continue playing once
  19957. * it reaches the end.
  19958. *
  19959. * @method Html5#setLoop
  19960. * @param {boolean} loop
  19961. * - True indicates that playback should seek back to start once
  19962. * the end of a media is reached.
  19963. * - False indicates that playback should not loop back to the start when the
  19964. * end of the media is reached.
  19965. *
  19966. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  19967. */
  19968. 'loop',
  19969. /**
  19970. * Set the value of `playsinline` from the media element. `playsinline` indicates
  19971. * to the browser that non-fullscreen playback is preferred when fullscreen
  19972. * playback is the native default, such as in iOS Safari.
  19973. *
  19974. * @method Html5#setPlaysinline
  19975. * @param {boolean} playsinline
  19976. * - True indicates that the media should play inline.
  19977. * - False indicates that the media should not play inline.
  19978. *
  19979. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  19980. */
  19981. 'playsinline'].forEach(function (prop) {
  19982. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  19983. this.el_[prop] = v;
  19984. if (v) {
  19985. this.el_.setAttribute(prop, prop);
  19986. } else {
  19987. this.el_.removeAttribute(prop);
  19988. }
  19989. };
  19990. });
  19991. // Wrap native properties with a getter
  19992. // The list is as followed
  19993. // paused, currentTime, buffered, volume, poster, preload, error, seeking
  19994. // seekable, ended, playbackRate, defaultPlaybackRate, disablePictureInPicture
  19995. // played, networkState, readyState, videoWidth, videoHeight, crossOrigin
  19996. [
  19997. /**
  19998. * Get the value of `paused` from the media element. `paused` indicates whether the media element
  19999. * is currently paused or not.
  20000. *
  20001. * @method Html5#paused
  20002. * @return {boolean}
  20003. * The value of `paused` from the media element.
  20004. *
  20005. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
  20006. */
  20007. 'paused',
  20008. /**
  20009. * Get the value of `currentTime` from the media element. `currentTime` indicates
  20010. * the current second that the media is at in playback.
  20011. *
  20012. * @method Html5#currentTime
  20013. * @return {number}
  20014. * The value of `currentTime` from the media element.
  20015. *
  20016. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
  20017. */
  20018. 'currentTime',
  20019. /**
  20020. * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
  20021. * object that represents the parts of the media that are already downloaded and
  20022. * available for playback.
  20023. *
  20024. * @method Html5#buffered
  20025. * @return {TimeRange}
  20026. * The value of `buffered` from the media element.
  20027. *
  20028. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
  20029. */
  20030. 'buffered',
  20031. /**
  20032. * Get the value of `volume` from the media element. `volume` indicates
  20033. * the current playback volume of audio for a media. `volume` will be a value from 0
  20034. * (silent) to 1 (loudest and default).
  20035. *
  20036. * @method Html5#volume
  20037. * @return {number}
  20038. * The value of `volume` from the media element. Value will be between 0-1.
  20039. *
  20040. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  20041. */
  20042. 'volume',
  20043. /**
  20044. * Get the value of `poster` from the media element. `poster` indicates
  20045. * that the url of an image file that can/will be shown when no media data is available.
  20046. *
  20047. * @method Html5#poster
  20048. * @return {string}
  20049. * The value of `poster` from the media element. Value will be a url to an
  20050. * image.
  20051. *
  20052. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
  20053. */
  20054. 'poster',
  20055. /**
  20056. * Get the value of `preload` from the media element. `preload` indicates
  20057. * what should download before the media is interacted with. It can have the following
  20058. * values:
  20059. * - none: nothing should be downloaded
  20060. * - metadata: poster and the first few frames of the media may be downloaded to get
  20061. * media dimensions and other metadata
  20062. * - auto: allow the media and metadata for the media to be downloaded before
  20063. * interaction
  20064. *
  20065. * @method Html5#preload
  20066. * @return {string}
  20067. * The value of `preload` from the media element. Will be 'none', 'metadata',
  20068. * or 'auto'.
  20069. *
  20070. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  20071. */
  20072. 'preload',
  20073. /**
  20074. * Get the value of the `error` from the media element. `error` indicates any
  20075. * MediaError that may have occurred during playback. If error returns null there is no
  20076. * current error.
  20077. *
  20078. * @method Html5#error
  20079. * @return {MediaError|null}
  20080. * The value of `error` from the media element. Will be `MediaError` if there
  20081. * is a current error and null otherwise.
  20082. *
  20083. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
  20084. */
  20085. 'error',
  20086. /**
  20087. * Get the value of `seeking` from the media element. `seeking` indicates whether the
  20088. * media is currently seeking to a new position or not.
  20089. *
  20090. * @method Html5#seeking
  20091. * @return {boolean}
  20092. * - The value of `seeking` from the media element.
  20093. * - True indicates that the media is currently seeking to a new position.
  20094. * - False indicates that the media is not seeking to a new position at this time.
  20095. *
  20096. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
  20097. */
  20098. 'seeking',
  20099. /**
  20100. * Get the value of `seekable` from the media element. `seekable` returns a
  20101. * `TimeRange` object indicating ranges of time that can currently be `seeked` to.
  20102. *
  20103. * @method Html5#seekable
  20104. * @return {TimeRange}
  20105. * The value of `seekable` from the media element. A `TimeRange` object
  20106. * indicating the current ranges of time that can be seeked to.
  20107. *
  20108. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
  20109. */
  20110. 'seekable',
  20111. /**
  20112. * Get the value of `ended` from the media element. `ended` indicates whether
  20113. * the media has reached the end or not.
  20114. *
  20115. * @method Html5#ended
  20116. * @return {boolean}
  20117. * - The value of `ended` from the media element.
  20118. * - True indicates that the media has ended.
  20119. * - False indicates that the media has not ended.
  20120. *
  20121. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
  20122. */
  20123. 'ended',
  20124. /**
  20125. * Get the value of `playbackRate` from the media element. `playbackRate` indicates
  20126. * the rate at which the media is currently playing back. Examples:
  20127. * - if playbackRate is set to 2, media will play twice as fast.
  20128. * - if playbackRate is set to 0.5, media will play half as fast.
  20129. *
  20130. * @method Html5#playbackRate
  20131. * @return {number}
  20132. * The value of `playbackRate` from the media element. A number indicating
  20133. * the current playback speed of the media, where 1 is normal speed.
  20134. *
  20135. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  20136. */
  20137. 'playbackRate',
  20138. /**
  20139. * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
  20140. * the rate at which the media is currently playing back. This value will not indicate the current
  20141. * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
  20142. *
  20143. * Examples:
  20144. * - if defaultPlaybackRate is set to 2, media will play twice as fast.
  20145. * - if defaultPlaybackRate is set to 0.5, media will play half as fast.
  20146. *
  20147. * @method Html5.prototype.defaultPlaybackRate
  20148. * @return {number}
  20149. * The value of `defaultPlaybackRate` from the media element. A number indicating
  20150. * the current playback speed of the media, where 1 is normal speed.
  20151. *
  20152. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  20153. */
  20154. 'defaultPlaybackRate',
  20155. /**
  20156. * Get the value of 'disablePictureInPicture' from the video element.
  20157. *
  20158. * @method Html5#disablePictureInPicture
  20159. * @return {boolean} value
  20160. * - The value of `disablePictureInPicture` from the video element.
  20161. * - True indicates that the video can't be played in Picture-In-Picture mode
  20162. * - False indicates that the video can be played in Picture-In-Picture mode
  20163. *
  20164. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  20165. */
  20166. 'disablePictureInPicture',
  20167. /**
  20168. * Get the value of `played` from the media element. `played` returns a `TimeRange`
  20169. * object representing points in the media timeline that have been played.
  20170. *
  20171. * @method Html5#played
  20172. * @return {TimeRange}
  20173. * The value of `played` from the media element. A `TimeRange` object indicating
  20174. * the ranges of time that have been played.
  20175. *
  20176. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
  20177. */
  20178. 'played',
  20179. /**
  20180. * Get the value of `networkState` from the media element. `networkState` indicates
  20181. * the current network state. It returns an enumeration from the following list:
  20182. * - 0: NETWORK_EMPTY
  20183. * - 1: NETWORK_IDLE
  20184. * - 2: NETWORK_LOADING
  20185. * - 3: NETWORK_NO_SOURCE
  20186. *
  20187. * @method Html5#networkState
  20188. * @return {number}
  20189. * The value of `networkState` from the media element. This will be a number
  20190. * from the list in the description.
  20191. *
  20192. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
  20193. */
  20194. 'networkState',
  20195. /**
  20196. * Get the value of `readyState` from the media element. `readyState` indicates
  20197. * the current state of the media element. It returns an enumeration from the
  20198. * following list:
  20199. * - 0: HAVE_NOTHING
  20200. * - 1: HAVE_METADATA
  20201. * - 2: HAVE_CURRENT_DATA
  20202. * - 3: HAVE_FUTURE_DATA
  20203. * - 4: HAVE_ENOUGH_DATA
  20204. *
  20205. * @method Html5#readyState
  20206. * @return {number}
  20207. * The value of `readyState` from the media element. This will be a number
  20208. * from the list in the description.
  20209. *
  20210. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
  20211. */
  20212. 'readyState',
  20213. /**
  20214. * Get the value of `videoWidth` from the video element. `videoWidth` indicates
  20215. * the current width of the video in css pixels.
  20216. *
  20217. * @method Html5#videoWidth
  20218. * @return {number}
  20219. * The value of `videoWidth` from the video element. This will be a number
  20220. * in css pixels.
  20221. *
  20222. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  20223. */
  20224. 'videoWidth',
  20225. /**
  20226. * Get the value of `videoHeight` from the video element. `videoHeight` indicates
  20227. * the current height of the video in css pixels.
  20228. *
  20229. * @method Html5#videoHeight
  20230. * @return {number}
  20231. * The value of `videoHeight` from the video element. This will be a number
  20232. * in css pixels.
  20233. *
  20234. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  20235. */
  20236. 'videoHeight',
  20237. /**
  20238. * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates
  20239. * to the browser that should sent the cookies along with the requests for the
  20240. * different assets/playlists
  20241. *
  20242. * @method Html5#crossOrigin
  20243. * @return {string}
  20244. * - anonymous indicates that the media should not sent cookies.
  20245. * - use-credentials indicates that the media should sent cookies along the requests.
  20246. *
  20247. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  20248. */
  20249. 'crossOrigin'].forEach(function (prop) {
  20250. Html5.prototype[prop] = function () {
  20251. return this.el_[prop];
  20252. };
  20253. });
  20254. // Wrap native properties with a setter in this format:
  20255. // set + toTitleCase(name)
  20256. // The list is as follows:
  20257. // setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate,
  20258. // setDisablePictureInPicture, setCrossOrigin
  20259. [
  20260. /**
  20261. * Set the value of `volume` on the media element. `volume` indicates the current
  20262. * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
  20263. * so on.
  20264. *
  20265. * @method Html5#setVolume
  20266. * @param {number} percentAsDecimal
  20267. * The volume percent as a decimal. Valid range is from 0-1.
  20268. *
  20269. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  20270. */
  20271. 'volume',
  20272. /**
  20273. * Set the value of `src` on the media element. `src` indicates the current
  20274. * {@link Tech~SourceObject} for the media.
  20275. *
  20276. * @method Html5#setSrc
  20277. * @param {Tech~SourceObject} src
  20278. * The source object to set as the current source.
  20279. *
  20280. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
  20281. */
  20282. 'src',
  20283. /**
  20284. * Set the value of `poster` on the media element. `poster` is the url to
  20285. * an image file that can/will be shown when no media data is available.
  20286. *
  20287. * @method Html5#setPoster
  20288. * @param {string} poster
  20289. * The url to an image that should be used as the `poster` for the media
  20290. * element.
  20291. *
  20292. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
  20293. */
  20294. 'poster',
  20295. /**
  20296. * Set the value of `preload` on the media element. `preload` indicates
  20297. * what should download before the media is interacted with. It can have the following
  20298. * values:
  20299. * - none: nothing should be downloaded
  20300. * - metadata: poster and the first few frames of the media may be downloaded to get
  20301. * media dimensions and other metadata
  20302. * - auto: allow the media and metadata for the media to be downloaded before
  20303. * interaction
  20304. *
  20305. * @method Html5#setPreload
  20306. * @param {string} preload
  20307. * The value of `preload` to set on the media element. Must be 'none', 'metadata',
  20308. * or 'auto'.
  20309. *
  20310. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  20311. */
  20312. 'preload',
  20313. /**
  20314. * Set the value of `playbackRate` on the media element. `playbackRate` indicates
  20315. * the rate at which the media should play back. Examples:
  20316. * - if playbackRate is set to 2, media will play twice as fast.
  20317. * - if playbackRate is set to 0.5, media will play half as fast.
  20318. *
  20319. * @method Html5#setPlaybackRate
  20320. * @return {number}
  20321. * The value of `playbackRate` from the media element. A number indicating
  20322. * the current playback speed of the media, where 1 is normal speed.
  20323. *
  20324. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  20325. */
  20326. 'playbackRate',
  20327. /**
  20328. * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
  20329. * the rate at which the media should play back upon initial startup. Changing this value
  20330. * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
  20331. *
  20332. * Example Values:
  20333. * - if playbackRate is set to 2, media will play twice as fast.
  20334. * - if playbackRate is set to 0.5, media will play half as fast.
  20335. *
  20336. * @method Html5.prototype.setDefaultPlaybackRate
  20337. * @return {number}
  20338. * The value of `defaultPlaybackRate` from the media element. A number indicating
  20339. * the current playback speed of the media, where 1 is normal speed.
  20340. *
  20341. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
  20342. */
  20343. 'defaultPlaybackRate',
  20344. /**
  20345. * Prevents the browser from suggesting a Picture-in-Picture context menu
  20346. * or to request Picture-in-Picture automatically in some cases.
  20347. *
  20348. * @method Html5#setDisablePictureInPicture
  20349. * @param {boolean} value
  20350. * The true value will disable Picture-in-Picture mode.
  20351. *
  20352. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  20353. */
  20354. 'disablePictureInPicture',
  20355. /**
  20356. * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates
  20357. * to the browser that should sent the cookies along with the requests for the
  20358. * different assets/playlists
  20359. *
  20360. * @method Html5#setCrossOrigin
  20361. * @param {string} crossOrigin
  20362. * - anonymous indicates that the media should not sent cookies.
  20363. * - use-credentials indicates that the media should sent cookies along the requests.
  20364. *
  20365. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  20366. */
  20367. 'crossOrigin'].forEach(function (prop) {
  20368. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  20369. this.el_[prop] = v;
  20370. };
  20371. });
  20372. // wrap native functions with a function
  20373. // The list is as follows:
  20374. // pause, load, play
  20375. [
  20376. /**
  20377. * A wrapper around the media elements `pause` function. This will call the `HTML5`
  20378. * media elements `pause` function.
  20379. *
  20380. * @method Html5#pause
  20381. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
  20382. */
  20383. 'pause',
  20384. /**
  20385. * A wrapper around the media elements `load` function. This will call the `HTML5`s
  20386. * media element `load` function.
  20387. *
  20388. * @method Html5#load
  20389. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
  20390. */
  20391. 'load',
  20392. /**
  20393. * A wrapper around the media elements `play` function. This will call the `HTML5`s
  20394. * media element `play` function.
  20395. *
  20396. * @method Html5#play
  20397. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
  20398. */
  20399. 'play'].forEach(function (prop) {
  20400. Html5.prototype[prop] = function () {
  20401. return this.el_[prop]();
  20402. };
  20403. });
  20404. Tech.withSourceHandlers(Html5);
  20405. /**
  20406. * Native source handler for Html5, simply passes the source to the media element.
  20407. *
  20408. * @property {Tech~SourceObject} source
  20409. * The source object
  20410. *
  20411. * @property {Html5} tech
  20412. * The instance of the HTML5 tech.
  20413. */
  20414. Html5.nativeSourceHandler = {};
  20415. /**
  20416. * Check if the media element can play the given mime type.
  20417. *
  20418. * @param {string} type
  20419. * The mimetype to check
  20420. *
  20421. * @return {string}
  20422. * 'probably', 'maybe', or '' (empty string)
  20423. */
  20424. Html5.nativeSourceHandler.canPlayType = function (type) {
  20425. // IE without MediaPlayer throws an error (#519)
  20426. try {
  20427. return Html5.TEST_VID.canPlayType(type);
  20428. } catch (e) {
  20429. return '';
  20430. }
  20431. };
  20432. /**
  20433. * Check if the media element can handle a source natively.
  20434. *
  20435. * @param {Tech~SourceObject} source
  20436. * The source object
  20437. *
  20438. * @param {Object} [options]
  20439. * Options to be passed to the tech.
  20440. *
  20441. * @return {string}
  20442. * 'probably', 'maybe', or '' (empty string).
  20443. */
  20444. Html5.nativeSourceHandler.canHandleSource = function (source, options) {
  20445. // If a type was provided we should rely on that
  20446. if (source.type) {
  20447. return Html5.nativeSourceHandler.canPlayType(source.type);
  20448. // If no type, fall back to checking 'video/[EXTENSION]'
  20449. } else if (source.src) {
  20450. const ext = getFileExtension(source.src);
  20451. return Html5.nativeSourceHandler.canPlayType(`video/${ext}`);
  20452. }
  20453. return '';
  20454. };
  20455. /**
  20456. * Pass the source to the native media element.
  20457. *
  20458. * @param {Tech~SourceObject} source
  20459. * The source object
  20460. *
  20461. * @param {Html5} tech
  20462. * The instance of the Html5 tech
  20463. *
  20464. * @param {Object} [options]
  20465. * The options to pass to the source
  20466. */
  20467. Html5.nativeSourceHandler.handleSource = function (source, tech, options) {
  20468. tech.setSrc(source.src);
  20469. };
  20470. /**
  20471. * A noop for the native dispose function, as cleanup is not needed.
  20472. */
  20473. Html5.nativeSourceHandler.dispose = function () {};
  20474. // Register the native source handler
  20475. Html5.registerSourceHandler(Html5.nativeSourceHandler);
  20476. Tech.registerTech('Html5', Html5);
  20477. /**
  20478. * @file player.js
  20479. */
  20480. // The following tech events are simply re-triggered
  20481. // on the player when they happen
  20482. const TECH_EVENTS_RETRIGGER = [
  20483. /**
  20484. * Fired while the user agent is downloading media data.
  20485. *
  20486. * @event Player#progress
  20487. * @type {Event}
  20488. */
  20489. /**
  20490. * Retrigger the `progress` event that was triggered by the {@link Tech}.
  20491. *
  20492. * @private
  20493. * @method Player#handleTechProgress_
  20494. * @fires Player#progress
  20495. * @listens Tech#progress
  20496. */
  20497. 'progress',
  20498. /**
  20499. * Fires when the loading of an audio/video is aborted.
  20500. *
  20501. * @event Player#abort
  20502. * @type {Event}
  20503. */
  20504. /**
  20505. * Retrigger the `abort` event that was triggered by the {@link Tech}.
  20506. *
  20507. * @private
  20508. * @method Player#handleTechAbort_
  20509. * @fires Player#abort
  20510. * @listens Tech#abort
  20511. */
  20512. 'abort',
  20513. /**
  20514. * Fires when the browser is intentionally not getting media data.
  20515. *
  20516. * @event Player#suspend
  20517. * @type {Event}
  20518. */
  20519. /**
  20520. * Retrigger the `suspend` event that was triggered by the {@link Tech}.
  20521. *
  20522. * @private
  20523. * @method Player#handleTechSuspend_
  20524. * @fires Player#suspend
  20525. * @listens Tech#suspend
  20526. */
  20527. 'suspend',
  20528. /**
  20529. * Fires when the current playlist is empty.
  20530. *
  20531. * @event Player#emptied
  20532. * @type {Event}
  20533. */
  20534. /**
  20535. * Retrigger the `emptied` event that was triggered by the {@link Tech}.
  20536. *
  20537. * @private
  20538. * @method Player#handleTechEmptied_
  20539. * @fires Player#emptied
  20540. * @listens Tech#emptied
  20541. */
  20542. 'emptied',
  20543. /**
  20544. * Fires when the browser is trying to get media data, but data is not available.
  20545. *
  20546. * @event Player#stalled
  20547. * @type {Event}
  20548. */
  20549. /**
  20550. * Retrigger the `stalled` event that was triggered by the {@link Tech}.
  20551. *
  20552. * @private
  20553. * @method Player#handleTechStalled_
  20554. * @fires Player#stalled
  20555. * @listens Tech#stalled
  20556. */
  20557. 'stalled',
  20558. /**
  20559. * Fires when the browser has loaded meta data for the audio/video.
  20560. *
  20561. * @event Player#loadedmetadata
  20562. * @type {Event}
  20563. */
  20564. /**
  20565. * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
  20566. *
  20567. * @private
  20568. * @method Player#handleTechLoadedmetadata_
  20569. * @fires Player#loadedmetadata
  20570. * @listens Tech#loadedmetadata
  20571. */
  20572. 'loadedmetadata',
  20573. /**
  20574. * Fires when the browser has loaded the current frame of the audio/video.
  20575. *
  20576. * @event Player#loadeddata
  20577. * @type {event}
  20578. */
  20579. /**
  20580. * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
  20581. *
  20582. * @private
  20583. * @method Player#handleTechLoaddeddata_
  20584. * @fires Player#loadeddata
  20585. * @listens Tech#loadeddata
  20586. */
  20587. 'loadeddata',
  20588. /**
  20589. * Fires when the current playback position has changed.
  20590. *
  20591. * @event Player#timeupdate
  20592. * @type {event}
  20593. */
  20594. /**
  20595. * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
  20596. *
  20597. * @private
  20598. * @method Player#handleTechTimeUpdate_
  20599. * @fires Player#timeupdate
  20600. * @listens Tech#timeupdate
  20601. */
  20602. 'timeupdate',
  20603. /**
  20604. * Fires when the video's intrinsic dimensions change
  20605. *
  20606. * @event Player#resize
  20607. * @type {event}
  20608. */
  20609. /**
  20610. * Retrigger the `resize` event that was triggered by the {@link Tech}.
  20611. *
  20612. * @private
  20613. * @method Player#handleTechResize_
  20614. * @fires Player#resize
  20615. * @listens Tech#resize
  20616. */
  20617. 'resize',
  20618. /**
  20619. * Fires when the volume has been changed
  20620. *
  20621. * @event Player#volumechange
  20622. * @type {event}
  20623. */
  20624. /**
  20625. * Retrigger the `volumechange` event that was triggered by the {@link Tech}.
  20626. *
  20627. * @private
  20628. * @method Player#handleTechVolumechange_
  20629. * @fires Player#volumechange
  20630. * @listens Tech#volumechange
  20631. */
  20632. 'volumechange',
  20633. /**
  20634. * Fires when the text track has been changed
  20635. *
  20636. * @event Player#texttrackchange
  20637. * @type {event}
  20638. */
  20639. /**
  20640. * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
  20641. *
  20642. * @private
  20643. * @method Player#handleTechTexttrackchange_
  20644. * @fires Player#texttrackchange
  20645. * @listens Tech#texttrackchange
  20646. */
  20647. 'texttrackchange'];
  20648. // events to queue when playback rate is zero
  20649. // this is a hash for the sole purpose of mapping non-camel-cased event names
  20650. // to camel-cased function names
  20651. const TECH_EVENTS_QUEUE = {
  20652. canplay: 'CanPlay',
  20653. canplaythrough: 'CanPlayThrough',
  20654. playing: 'Playing',
  20655. seeked: 'Seeked'
  20656. };
  20657. const BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
  20658. const BREAKPOINT_CLASSES = {};
  20659. // grep: vjs-layout-tiny
  20660. // grep: vjs-layout-x-small
  20661. // grep: vjs-layout-small
  20662. // grep: vjs-layout-medium
  20663. // grep: vjs-layout-large
  20664. // grep: vjs-layout-x-large
  20665. // grep: vjs-layout-huge
  20666. BREAKPOINT_ORDER.forEach(k => {
  20667. const v = k.charAt(0) === 'x' ? `x-${k.substring(1)}` : k;
  20668. BREAKPOINT_CLASSES[k] = `vjs-layout-${v}`;
  20669. });
  20670. const DEFAULT_BREAKPOINTS = {
  20671. tiny: 210,
  20672. xsmall: 320,
  20673. small: 425,
  20674. medium: 768,
  20675. large: 1440,
  20676. xlarge: 2560,
  20677. huge: Infinity
  20678. };
  20679. /**
  20680. * An instance of the `Player` class is created when any of the Video.js setup methods
  20681. * are used to initialize a video.
  20682. *
  20683. * After an instance has been created it can be accessed globally in three ways:
  20684. * 1. By calling `videojs.getPlayer('example_video_1');`
  20685. * 2. By calling `videojs('example_video_1');` (not recomended)
  20686. * 2. By using it directly via `videojs.players.example_video_1;`
  20687. *
  20688. * @extends Component
  20689. * @global
  20690. */
  20691. class Player extends Component$1 {
  20692. /**
  20693. * Create an instance of this class.
  20694. *
  20695. * @param {Element} tag
  20696. * The original video DOM element used for configuring options.
  20697. *
  20698. * @param {Object} [options]
  20699. * Object of option names and values.
  20700. *
  20701. * @param {Function} [ready]
  20702. * Ready callback function.
  20703. */
  20704. constructor(tag, options, ready) {
  20705. // Make sure tag ID exists
  20706. tag.id = tag.id || options.id || `vjs_video_${newGUID()}`;
  20707. // Set Options
  20708. // The options argument overrides options set in the video tag
  20709. // which overrides globally set options.
  20710. // This latter part coincides with the load order
  20711. // (tag must exist before Player)
  20712. options = Object.assign(Player.getTagSettings(tag), options);
  20713. // Delay the initialization of children because we need to set up
  20714. // player properties first, and can't use `this` before `super()`
  20715. options.initChildren = false;
  20716. // Same with creating the element
  20717. options.createEl = false;
  20718. // don't auto mixin the evented mixin
  20719. options.evented = false;
  20720. // we don't want the player to report touch activity on itself
  20721. // see enableTouchActivity in Component
  20722. options.reportTouchActivity = false;
  20723. // If language is not set, get the closest lang attribute
  20724. if (!options.language) {
  20725. const closest = tag.closest('[lang]');
  20726. if (closest) {
  20727. options.language = closest.getAttribute('lang');
  20728. }
  20729. }
  20730. // Run base component initializing with new options
  20731. super(null, options, ready);
  20732. // Create bound methods for document listeners.
  20733. this.boundDocumentFullscreenChange_ = e => this.documentFullscreenChange_(e);
  20734. this.boundFullWindowOnEscKey_ = e => this.fullWindowOnEscKey(e);
  20735. this.boundUpdateStyleEl_ = e => this.updateStyleEl_(e);
  20736. this.boundApplyInitTime_ = e => this.applyInitTime_(e);
  20737. this.boundUpdateCurrentBreakpoint_ = e => this.updateCurrentBreakpoint_(e);
  20738. this.boundHandleTechClick_ = e => this.handleTechClick_(e);
  20739. this.boundHandleTechDoubleClick_ = e => this.handleTechDoubleClick_(e);
  20740. this.boundHandleTechTouchStart_ = e => this.handleTechTouchStart_(e);
  20741. this.boundHandleTechTouchMove_ = e => this.handleTechTouchMove_(e);
  20742. this.boundHandleTechTouchEnd_ = e => this.handleTechTouchEnd_(e);
  20743. this.boundHandleTechTap_ = e => this.handleTechTap_(e);
  20744. // default isFullscreen_ to false
  20745. this.isFullscreen_ = false;
  20746. // create logger
  20747. this.log = createLogger(this.id_);
  20748. // Hold our own reference to fullscreen api so it can be mocked in tests
  20749. this.fsApi_ = FullscreenApi;
  20750. // Tracks when a tech changes the poster
  20751. this.isPosterFromTech_ = false;
  20752. // Holds callback info that gets queued when playback rate is zero
  20753. // and a seek is happening
  20754. this.queuedCallbacks_ = [];
  20755. // Turn off API access because we're loading a new tech that might load asynchronously
  20756. this.isReady_ = false;
  20757. // Init state hasStarted_
  20758. this.hasStarted_ = false;
  20759. // Init state userActive_
  20760. this.userActive_ = false;
  20761. // Init debugEnabled_
  20762. this.debugEnabled_ = false;
  20763. // Init state audioOnlyMode_
  20764. this.audioOnlyMode_ = false;
  20765. // Init state audioPosterMode_
  20766. this.audioPosterMode_ = false;
  20767. // Init state audioOnlyCache_
  20768. this.audioOnlyCache_ = {
  20769. playerHeight: null,
  20770. hiddenChildren: []
  20771. };
  20772. // if the global option object was accidentally blown away by
  20773. // someone, bail early with an informative error
  20774. if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) {
  20775. throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
  20776. }
  20777. // Store the original tag used to set options
  20778. this.tag = tag;
  20779. // Store the tag attributes used to restore html5 element
  20780. this.tagAttributes = tag && getAttributes(tag);
  20781. // Update current language
  20782. this.language(this.options_.language);
  20783. // Update Supported Languages
  20784. if (options.languages) {
  20785. // Normalise player option languages to lowercase
  20786. const languagesToLower = {};
  20787. Object.getOwnPropertyNames(options.languages).forEach(function (name) {
  20788. languagesToLower[name.toLowerCase()] = options.languages[name];
  20789. });
  20790. this.languages_ = languagesToLower;
  20791. } else {
  20792. this.languages_ = Player.prototype.options_.languages;
  20793. }
  20794. this.resetCache_();
  20795. // Set poster
  20796. this.poster_ = options.poster || '';
  20797. // Set controls
  20798. this.controls_ = !!options.controls;
  20799. // Original tag settings stored in options
  20800. // now remove immediately so native controls don't flash.
  20801. // May be turned back on by HTML5 tech if nativeControlsForTouch is true
  20802. tag.controls = false;
  20803. tag.removeAttribute('controls');
  20804. this.changingSrc_ = false;
  20805. this.playCallbacks_ = [];
  20806. this.playTerminatedQueue_ = [];
  20807. // the attribute overrides the option
  20808. if (tag.hasAttribute('autoplay')) {
  20809. this.autoplay(true);
  20810. } else {
  20811. // otherwise use the setter to validate and
  20812. // set the correct value.
  20813. this.autoplay(this.options_.autoplay);
  20814. }
  20815. // check plugins
  20816. if (options.plugins) {
  20817. Object.keys(options.plugins).forEach(name => {
  20818. if (typeof this[name] !== 'function') {
  20819. throw new Error(`plugin "${name}" does not exist`);
  20820. }
  20821. });
  20822. }
  20823. /*
  20824. * Store the internal state of scrubbing
  20825. *
  20826. * @private
  20827. * @return {Boolean} True if the user is scrubbing
  20828. */
  20829. this.scrubbing_ = false;
  20830. this.el_ = this.createEl();
  20831. // Make this an evented object and use `el_` as its event bus.
  20832. evented(this, {
  20833. eventBusKey: 'el_'
  20834. });
  20835. // listen to document and player fullscreenchange handlers so we receive those events
  20836. // before a user can receive them so we can update isFullscreen appropriately.
  20837. // make sure that we listen to fullscreenchange events before everything else to make sure that
  20838. // our isFullscreen method is updated properly for internal components as well as external.
  20839. if (this.fsApi_.requestFullscreen) {
  20840. on(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  20841. this.on(this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  20842. }
  20843. if (this.fluid_) {
  20844. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  20845. }
  20846. // We also want to pass the original player options to each component and plugin
  20847. // as well so they don't need to reach back into the player for options later.
  20848. // We also need to do another copy of this.options_ so we don't end up with
  20849. // an infinite loop.
  20850. const playerOptionsCopy = merge$2(this.options_);
  20851. // Load plugins
  20852. if (options.plugins) {
  20853. Object.keys(options.plugins).forEach(name => {
  20854. this[name](options.plugins[name]);
  20855. });
  20856. }
  20857. // Enable debug mode to fire debugon event for all plugins.
  20858. if (options.debug) {
  20859. this.debug(true);
  20860. }
  20861. this.options_.playerOptions = playerOptionsCopy;
  20862. this.middleware_ = [];
  20863. this.playbackRates(options.playbackRates);
  20864. this.initChildren();
  20865. // Set isAudio based on whether or not an audio tag was used
  20866. this.isAudio(tag.nodeName.toLowerCase() === 'audio');
  20867. // Update controls className. Can't do this when the controls are initially
  20868. // set because the element doesn't exist yet.
  20869. if (this.controls()) {
  20870. this.addClass('vjs-controls-enabled');
  20871. } else {
  20872. this.addClass('vjs-controls-disabled');
  20873. }
  20874. // Set ARIA label and region role depending on player type
  20875. this.el_.setAttribute('role', 'region');
  20876. if (this.isAudio()) {
  20877. this.el_.setAttribute('aria-label', this.localize('Audio Player'));
  20878. } else {
  20879. this.el_.setAttribute('aria-label', this.localize('Video Player'));
  20880. }
  20881. if (this.isAudio()) {
  20882. this.addClass('vjs-audio');
  20883. }
  20884. // TODO: Make this smarter. Toggle user state between touching/mousing
  20885. // using events, since devices can have both touch and mouse events.
  20886. // TODO: Make this check be performed again when the window switches between monitors
  20887. // (See https://github.com/videojs/video.js/issues/5683)
  20888. if (TOUCH_ENABLED) {
  20889. this.addClass('vjs-touch-enabled');
  20890. }
  20891. // iOS Safari has broken hover handling
  20892. if (!IS_IOS) {
  20893. this.addClass('vjs-workinghover');
  20894. }
  20895. // Make player easily findable by ID
  20896. Player.players[this.id_] = this;
  20897. // Add a major version class to aid css in plugins
  20898. const majorVersion = version$5.split('.')[0];
  20899. this.addClass(`vjs-v${majorVersion}`);
  20900. // When the player is first initialized, trigger activity so components
  20901. // like the control bar show themselves if needed
  20902. this.userActive(true);
  20903. this.reportUserActivity();
  20904. this.one('play', e => this.listenForUserActivity_(e));
  20905. this.on('keydown', e => this.handleKeyDown(e));
  20906. this.on('languagechange', e => this.handleLanguagechange(e));
  20907. this.breakpoints(this.options_.breakpoints);
  20908. this.responsive(this.options_.responsive);
  20909. // Calling both the audio mode methods after the player is fully
  20910. // setup to be able to listen to the events triggered by them
  20911. this.on('ready', () => {
  20912. // Calling the audioPosterMode method first so that
  20913. // the audioOnlyMode can take precedence when both options are set to true
  20914. this.audioPosterMode(this.options_.audioPosterMode);
  20915. this.audioOnlyMode(this.options_.audioOnlyMode);
  20916. });
  20917. }
  20918. /**
  20919. * Destroys the video player and does any necessary cleanup.
  20920. *
  20921. * This is especially helpful if you are dynamically adding and removing videos
  20922. * to/from the DOM.
  20923. *
  20924. * @fires Player#dispose
  20925. */
  20926. dispose() {
  20927. /**
  20928. * Called when the player is being disposed of.
  20929. *
  20930. * @event Player#dispose
  20931. * @type {Event}
  20932. */
  20933. this.trigger('dispose');
  20934. // prevent dispose from being called twice
  20935. this.off('dispose');
  20936. // Make sure all player-specific document listeners are unbound. This is
  20937. off(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  20938. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  20939. if (this.styleEl_ && this.styleEl_.parentNode) {
  20940. this.styleEl_.parentNode.removeChild(this.styleEl_);
  20941. this.styleEl_ = null;
  20942. }
  20943. // Kill reference to this player
  20944. Player.players[this.id_] = null;
  20945. if (this.tag && this.tag.player) {
  20946. this.tag.player = null;
  20947. }
  20948. if (this.el_ && this.el_.player) {
  20949. this.el_.player = null;
  20950. }
  20951. if (this.tech_) {
  20952. this.tech_.dispose();
  20953. this.isPosterFromTech_ = false;
  20954. this.poster_ = '';
  20955. }
  20956. if (this.playerElIngest_) {
  20957. this.playerElIngest_ = null;
  20958. }
  20959. if (this.tag) {
  20960. this.tag = null;
  20961. }
  20962. clearCacheForPlayer(this);
  20963. // remove all event handlers for track lists
  20964. // all tracks and track listeners are removed on
  20965. // tech dispose
  20966. ALL.names.forEach(name => {
  20967. const props = ALL[name];
  20968. const list = this[props.getterName]();
  20969. // if it is not a native list
  20970. // we have to manually remove event listeners
  20971. if (list && list.off) {
  20972. list.off();
  20973. }
  20974. });
  20975. // the actual .el_ is removed here, or replaced if
  20976. super.dispose({
  20977. restoreEl: this.options_.restoreEl
  20978. });
  20979. }
  20980. /**
  20981. * Create the `Player`'s DOM element.
  20982. *
  20983. * @return {Element}
  20984. * The DOM element that gets created.
  20985. */
  20986. createEl() {
  20987. let tag = this.tag;
  20988. let el;
  20989. let playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
  20990. const divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
  20991. if (playerElIngest) {
  20992. el = this.el_ = tag.parentNode;
  20993. } else if (!divEmbed) {
  20994. el = this.el_ = super.createEl('div');
  20995. }
  20996. // Copy over all the attributes from the tag, including ID and class
  20997. // ID will now reference player box, not the video tag
  20998. const attrs = getAttributes(tag);
  20999. if (divEmbed) {
  21000. el = this.el_ = tag;
  21001. tag = this.tag = document.createElement('video');
  21002. while (el.children.length) {
  21003. tag.appendChild(el.firstChild);
  21004. }
  21005. if (!hasClass(el, 'video-js')) {
  21006. addClass(el, 'video-js');
  21007. }
  21008. el.appendChild(tag);
  21009. playerElIngest = this.playerElIngest_ = el;
  21010. // move properties over from our custom `video-js` element
  21011. // to our new `video` element. This will move things like
  21012. // `src` or `controls` that were set via js before the player
  21013. // was initialized.
  21014. Object.keys(el).forEach(k => {
  21015. try {
  21016. tag[k] = el[k];
  21017. } catch (e) {
  21018. // we got a a property like outerHTML which we can't actually copy, ignore it
  21019. }
  21020. });
  21021. }
  21022. // set tabindex to -1 to remove the video element from the focus order
  21023. tag.setAttribute('tabindex', '-1');
  21024. attrs.tabindex = '-1';
  21025. // Workaround for #4583 on Chrome (on Windows) with JAWS.
  21026. // See https://github.com/FreedomScientific/VFO-standards-support/issues/78
  21027. // Note that we can't detect if JAWS is being used, but this ARIA attribute
  21028. // doesn't change behavior of Chrome if JAWS is not being used
  21029. if (IS_CHROME && IS_WINDOWS) {
  21030. tag.setAttribute('role', 'application');
  21031. attrs.role = 'application';
  21032. }
  21033. // Remove width/height attrs from tag so CSS can make it 100% width/height
  21034. tag.removeAttribute('width');
  21035. tag.removeAttribute('height');
  21036. if ('width' in attrs) {
  21037. delete attrs.width;
  21038. }
  21039. if ('height' in attrs) {
  21040. delete attrs.height;
  21041. }
  21042. Object.getOwnPropertyNames(attrs).forEach(function (attr) {
  21043. // don't copy over the class attribute to the player element when we're in a div embed
  21044. // the class is already set up properly in the divEmbed case
  21045. // and we want to make sure that the `video-js` class doesn't get lost
  21046. if (!(divEmbed && attr === 'class')) {
  21047. el.setAttribute(attr, attrs[attr]);
  21048. }
  21049. if (divEmbed) {
  21050. tag.setAttribute(attr, attrs[attr]);
  21051. }
  21052. });
  21053. // Update tag id/class for use as HTML5 playback tech
  21054. // Might think we should do this after embedding in container so .vjs-tech class
  21055. // doesn't flash 100% width/height, but class only applies with .video-js parent
  21056. tag.playerId = tag.id;
  21057. tag.id += '_html5_api';
  21058. tag.className = 'vjs-tech';
  21059. // Make player findable on elements
  21060. tag.player = el.player = this;
  21061. // Default state of video is paused
  21062. this.addClass('vjs-paused');
  21063. // Add a style element in the player that we'll use to set the width/height
  21064. // of the player in a way that's still overridable by CSS, just like the
  21065. // video element
  21066. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
  21067. this.styleEl_ = createStyleElement('vjs-styles-dimensions');
  21068. const defaultsStyleEl = $('.vjs-styles-defaults');
  21069. const head = $('head');
  21070. head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
  21071. }
  21072. this.fill_ = false;
  21073. this.fluid_ = false;
  21074. // Pass in the width/height/aspectRatio options which will update the style el
  21075. this.width(this.options_.width);
  21076. this.height(this.options_.height);
  21077. this.fill(this.options_.fill);
  21078. this.fluid(this.options_.fluid);
  21079. this.aspectRatio(this.options_.aspectRatio);
  21080. // support both crossOrigin and crossorigin to reduce confusion and issues around the name
  21081. this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin);
  21082. // Hide any links within the video/audio tag,
  21083. // because IE doesn't hide them completely from screen readers.
  21084. const links = tag.getElementsByTagName('a');
  21085. for (let i = 0; i < links.length; i++) {
  21086. const linkEl = links.item(i);
  21087. addClass(linkEl, 'vjs-hidden');
  21088. linkEl.setAttribute('hidden', 'hidden');
  21089. }
  21090. // insertElFirst seems to cause the networkState to flicker from 3 to 2, so
  21091. // keep track of the original for later so we can know if the source originally failed
  21092. tag.initNetworkState_ = tag.networkState;
  21093. // Wrap video tag in div (el/box) container
  21094. if (tag.parentNode && !playerElIngest) {
  21095. tag.parentNode.insertBefore(el, tag);
  21096. }
  21097. // insert the tag as the first child of the player element
  21098. // then manually add it to the children array so that this.addChild
  21099. // will work properly for other components
  21100. //
  21101. // Breaks iPhone, fixed in HTML5 setup.
  21102. prependTo(tag, el);
  21103. this.children_.unshift(tag);
  21104. // Set lang attr on player to ensure CSS :lang() in consistent with player
  21105. // if it's been set to something different to the doc
  21106. this.el_.setAttribute('lang', this.language_);
  21107. this.el_.setAttribute('translate', 'no');
  21108. this.el_ = el;
  21109. return el;
  21110. }
  21111. /**
  21112. * Get or set the `Player`'s crossOrigin option. For the HTML5 player, this
  21113. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  21114. * behavior.
  21115. *
  21116. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  21117. *
  21118. * @param {string|null} [value]
  21119. * The value to set the `Player`'s crossOrigin to. If an argument is
  21120. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  21121. *
  21122. * @return {string|null|undefined}
  21123. * - The current crossOrigin value of the `Player` when getting.
  21124. * - undefined when setting
  21125. */
  21126. crossOrigin(value) {
  21127. // `null` can be set to unset a value
  21128. if (typeof value === 'undefined') {
  21129. return this.techGet_('crossOrigin');
  21130. }
  21131. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  21132. log$1.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  21133. return;
  21134. }
  21135. this.techCall_('setCrossOrigin', value);
  21136. if (this.posterImage) {
  21137. this.posterImage.crossOrigin(value);
  21138. }
  21139. return;
  21140. }
  21141. /**
  21142. * A getter/setter for the `Player`'s width. Returns the player's configured value.
  21143. * To get the current width use `currentWidth()`.
  21144. *
  21145. * @param {number} [value]
  21146. * The value to set the `Player`'s width to.
  21147. *
  21148. * @return {number}
  21149. * The current width of the `Player` when getting.
  21150. */
  21151. width(value) {
  21152. return this.dimension('width', value);
  21153. }
  21154. /**
  21155. * A getter/setter for the `Player`'s height. Returns the player's configured value.
  21156. * To get the current height use `currentheight()`.
  21157. *
  21158. * @param {number} [value]
  21159. * The value to set the `Player`'s height to.
  21160. *
  21161. * @return {number}
  21162. * The current height of the `Player` when getting.
  21163. */
  21164. height(value) {
  21165. return this.dimension('height', value);
  21166. }
  21167. /**
  21168. * A getter/setter for the `Player`'s width & height.
  21169. *
  21170. * @param {string} dimension
  21171. * This string can be:
  21172. * - 'width'
  21173. * - 'height'
  21174. *
  21175. * @param {number} [value]
  21176. * Value for dimension specified in the first argument.
  21177. *
  21178. * @return {number}
  21179. * The dimension arguments value when getting (width/height).
  21180. */
  21181. dimension(dimension, value) {
  21182. const privDimension = dimension + '_';
  21183. if (value === undefined) {
  21184. return this[privDimension] || 0;
  21185. }
  21186. if (value === '' || value === 'auto') {
  21187. // If an empty string is given, reset the dimension to be automatic
  21188. this[privDimension] = undefined;
  21189. this.updateStyleEl_();
  21190. return;
  21191. }
  21192. const parsedVal = parseFloat(value);
  21193. if (isNaN(parsedVal)) {
  21194. log$1.error(`Improper value "${value}" supplied for for ${dimension}`);
  21195. return;
  21196. }
  21197. this[privDimension] = parsedVal;
  21198. this.updateStyleEl_();
  21199. }
  21200. /**
  21201. * A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
  21202. *
  21203. * Turning this on will turn off fill mode.
  21204. *
  21205. * @param {boolean} [bool]
  21206. * - A value of true adds the class.
  21207. * - A value of false removes the class.
  21208. * - No value will be a getter.
  21209. *
  21210. * @return {boolean|undefined}
  21211. * - The value of fluid when getting.
  21212. * - `undefined` when setting.
  21213. */
  21214. fluid(bool) {
  21215. if (bool === undefined) {
  21216. return !!this.fluid_;
  21217. }
  21218. this.fluid_ = !!bool;
  21219. if (isEvented(this)) {
  21220. this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  21221. }
  21222. if (bool) {
  21223. this.addClass('vjs-fluid');
  21224. this.fill(false);
  21225. addEventedCallback(this, () => {
  21226. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  21227. });
  21228. } else {
  21229. this.removeClass('vjs-fluid');
  21230. }
  21231. this.updateStyleEl_();
  21232. }
  21233. /**
  21234. * A getter/setter/toggler for the vjs-fill `className` on the `Player`.
  21235. *
  21236. * Turning this on will turn off fluid mode.
  21237. *
  21238. * @param {boolean} [bool]
  21239. * - A value of true adds the class.
  21240. * - A value of false removes the class.
  21241. * - No value will be a getter.
  21242. *
  21243. * @return {boolean|undefined}
  21244. * - The value of fluid when getting.
  21245. * - `undefined` when setting.
  21246. */
  21247. fill(bool) {
  21248. if (bool === undefined) {
  21249. return !!this.fill_;
  21250. }
  21251. this.fill_ = !!bool;
  21252. if (bool) {
  21253. this.addClass('vjs-fill');
  21254. this.fluid(false);
  21255. } else {
  21256. this.removeClass('vjs-fill');
  21257. }
  21258. }
  21259. /**
  21260. * Get/Set the aspect ratio
  21261. *
  21262. * @param {string} [ratio]
  21263. * Aspect ratio for player
  21264. *
  21265. * @return {string|undefined}
  21266. * returns the current aspect ratio when getting
  21267. */
  21268. /**
  21269. * A getter/setter for the `Player`'s aspect ratio.
  21270. *
  21271. * @param {string} [ratio]
  21272. * The value to set the `Player`'s aspect ratio to.
  21273. *
  21274. * @return {string|undefined}
  21275. * - The current aspect ratio of the `Player` when getting.
  21276. * - undefined when setting
  21277. */
  21278. aspectRatio(ratio) {
  21279. if (ratio === undefined) {
  21280. return this.aspectRatio_;
  21281. }
  21282. // Check for width:height format
  21283. if (!/^\d+\:\d+$/.test(ratio)) {
  21284. throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
  21285. }
  21286. this.aspectRatio_ = ratio;
  21287. // We're assuming if you set an aspect ratio you want fluid mode,
  21288. // because in fixed mode you could calculate width and height yourself.
  21289. this.fluid(true);
  21290. this.updateStyleEl_();
  21291. }
  21292. /**
  21293. * Update styles of the `Player` element (height, width and aspect ratio).
  21294. *
  21295. * @private
  21296. * @listens Tech#loadedmetadata
  21297. */
  21298. updateStyleEl_() {
  21299. if (window.VIDEOJS_NO_DYNAMIC_STYLE === true) {
  21300. const width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
  21301. const height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
  21302. const techEl = this.tech_ && this.tech_.el();
  21303. if (techEl) {
  21304. if (width >= 0) {
  21305. techEl.width = width;
  21306. }
  21307. if (height >= 0) {
  21308. techEl.height = height;
  21309. }
  21310. }
  21311. return;
  21312. }
  21313. let width;
  21314. let height;
  21315. let aspectRatio;
  21316. let idClass;
  21317. // The aspect ratio is either used directly or to calculate width and height.
  21318. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
  21319. // Use any aspectRatio that's been specifically set
  21320. aspectRatio = this.aspectRatio_;
  21321. } else if (this.videoWidth() > 0) {
  21322. // Otherwise try to get the aspect ratio from the video metadata
  21323. aspectRatio = this.videoWidth() + ':' + this.videoHeight();
  21324. } else {
  21325. // Or use a default. The video element's is 2:1, but 16:9 is more common.
  21326. aspectRatio = '16:9';
  21327. }
  21328. // Get the ratio as a decimal we can use to calculate dimensions
  21329. const ratioParts = aspectRatio.split(':');
  21330. const ratioMultiplier = ratioParts[1] / ratioParts[0];
  21331. if (this.width_ !== undefined) {
  21332. // Use any width that's been specifically set
  21333. width = this.width_;
  21334. } else if (this.height_ !== undefined) {
  21335. // Or calculate the width from the aspect ratio if a height has been set
  21336. width = this.height_ / ratioMultiplier;
  21337. } else {
  21338. // Or use the video's metadata, or use the video el's default of 300
  21339. width = this.videoWidth() || 300;
  21340. }
  21341. if (this.height_ !== undefined) {
  21342. // Use any height that's been specifically set
  21343. height = this.height_;
  21344. } else {
  21345. // Otherwise calculate the height from the ratio and the width
  21346. height = width * ratioMultiplier;
  21347. }
  21348. // Ensure the CSS class is valid by starting with an alpha character
  21349. if (/^[^a-zA-Z]/.test(this.id())) {
  21350. idClass = 'dimensions-' + this.id();
  21351. } else {
  21352. idClass = this.id() + '-dimensions';
  21353. }
  21354. // Ensure the right class is still on the player for the style element
  21355. this.addClass(idClass);
  21356. setTextContent(this.styleEl_, `
  21357. .${idClass} {
  21358. width: ${width}px;
  21359. height: ${height}px;
  21360. }
  21361. .${idClass}.vjs-fluid:not(.vjs-audio-only-mode) {
  21362. padding-top: ${ratioMultiplier * 100}%;
  21363. }
  21364. `);
  21365. }
  21366. /**
  21367. * Load/Create an instance of playback {@link Tech} including element
  21368. * and API methods. Then append the `Tech` element in `Player` as a child.
  21369. *
  21370. * @param {string} techName
  21371. * name of the playback technology
  21372. *
  21373. * @param {string} source
  21374. * video source
  21375. *
  21376. * @private
  21377. */
  21378. loadTech_(techName, source) {
  21379. // Pause and remove current playback technology
  21380. if (this.tech_) {
  21381. this.unloadTech_();
  21382. }
  21383. const titleTechName = toTitleCase$1(techName);
  21384. const camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1);
  21385. // get rid of the HTML5 video tag as soon as we are using another tech
  21386. if (titleTechName !== 'Html5' && this.tag) {
  21387. Tech.getTech('Html5').disposeMediaElement(this.tag);
  21388. this.tag.player = null;
  21389. this.tag = null;
  21390. }
  21391. this.techName_ = titleTechName;
  21392. // Turn off API access because we're loading a new tech that might load asynchronously
  21393. this.isReady_ = false;
  21394. let autoplay = this.autoplay();
  21395. // if autoplay is a string (or `true` with normalizeAutoplay: true) we pass false to the tech
  21396. // because the player is going to handle autoplay on `loadstart`
  21397. if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeAutoplay) {
  21398. autoplay = false;
  21399. }
  21400. // Grab tech-specific options from player options and add source and parent element to use.
  21401. const techOptions = {
  21402. source,
  21403. autoplay,
  21404. 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
  21405. 'playerId': this.id(),
  21406. 'techId': `${this.id()}_${camelTechName}_api`,
  21407. 'playsinline': this.options_.playsinline,
  21408. 'preload': this.options_.preload,
  21409. 'loop': this.options_.loop,
  21410. 'disablePictureInPicture': this.options_.disablePictureInPicture,
  21411. 'muted': this.options_.muted,
  21412. 'poster': this.poster(),
  21413. 'language': this.language(),
  21414. 'playerElIngest': this.playerElIngest_ || false,
  21415. 'vtt.js': this.options_['vtt.js'],
  21416. 'canOverridePoster': !!this.options_.techCanOverridePoster,
  21417. 'enableSourceset': this.options_.enableSourceset
  21418. };
  21419. ALL.names.forEach(name => {
  21420. const props = ALL[name];
  21421. techOptions[props.getterName] = this[props.privateName];
  21422. });
  21423. Object.assign(techOptions, this.options_[titleTechName]);
  21424. Object.assign(techOptions, this.options_[camelTechName]);
  21425. Object.assign(techOptions, this.options_[techName.toLowerCase()]);
  21426. if (this.tag) {
  21427. techOptions.tag = this.tag;
  21428. }
  21429. if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
  21430. techOptions.startTime = this.cache_.currentTime;
  21431. }
  21432. // Initialize tech instance
  21433. const TechClass = Tech.getTech(techName);
  21434. if (!TechClass) {
  21435. throw new Error(`No Tech named '${titleTechName}' exists! '${titleTechName}' should be registered using videojs.registerTech()'`);
  21436. }
  21437. this.tech_ = new TechClass(techOptions);
  21438. // player.triggerReady is always async, so don't need this to be async
  21439. this.tech_.ready(bind_(this, this.handleTechReady_), true);
  21440. textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
  21441. // Listen to all HTML5-defined events and trigger them on the player
  21442. TECH_EVENTS_RETRIGGER.forEach(event => {
  21443. this.on(this.tech_, event, e => this[`handleTech${toTitleCase$1(event)}_`](e));
  21444. });
  21445. Object.keys(TECH_EVENTS_QUEUE).forEach(event => {
  21446. this.on(this.tech_, event, eventObj => {
  21447. if (this.tech_.playbackRate() === 0 && this.tech_.seeking()) {
  21448. this.queuedCallbacks_.push({
  21449. callback: this[`handleTech${TECH_EVENTS_QUEUE[event]}_`].bind(this),
  21450. event: eventObj
  21451. });
  21452. return;
  21453. }
  21454. this[`handleTech${TECH_EVENTS_QUEUE[event]}_`](eventObj);
  21455. });
  21456. });
  21457. this.on(this.tech_, 'loadstart', e => this.handleTechLoadStart_(e));
  21458. this.on(this.tech_, 'sourceset', e => this.handleTechSourceset_(e));
  21459. this.on(this.tech_, 'waiting', e => this.handleTechWaiting_(e));
  21460. this.on(this.tech_, 'ended', e => this.handleTechEnded_(e));
  21461. this.on(this.tech_, 'seeking', e => this.handleTechSeeking_(e));
  21462. this.on(this.tech_, 'play', e => this.handleTechPlay_(e));
  21463. this.on(this.tech_, 'pause', e => this.handleTechPause_(e));
  21464. this.on(this.tech_, 'durationchange', e => this.handleTechDurationChange_(e));
  21465. this.on(this.tech_, 'fullscreenchange', (e, data) => this.handleTechFullscreenChange_(e, data));
  21466. this.on(this.tech_, 'fullscreenerror', (e, err) => this.handleTechFullscreenError_(e, err));
  21467. this.on(this.tech_, 'enterpictureinpicture', e => this.handleTechEnterPictureInPicture_(e));
  21468. this.on(this.tech_, 'leavepictureinpicture', e => this.handleTechLeavePictureInPicture_(e));
  21469. this.on(this.tech_, 'error', e => this.handleTechError_(e));
  21470. this.on(this.tech_, 'posterchange', e => this.handleTechPosterChange_(e));
  21471. this.on(this.tech_, 'textdata', e => this.handleTechTextData_(e));
  21472. this.on(this.tech_, 'ratechange', e => this.handleTechRateChange_(e));
  21473. this.on(this.tech_, 'loadedmetadata', this.boundUpdateStyleEl_);
  21474. this.usingNativeControls(this.techGet_('controls'));
  21475. if (this.controls() && !this.usingNativeControls()) {
  21476. this.addTechControlsListeners_();
  21477. }
  21478. // Add the tech element in the DOM if it was not already there
  21479. // Make sure to not insert the original video element if using Html5
  21480. if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {
  21481. prependTo(this.tech_.el(), this.el());
  21482. }
  21483. // Get rid of the original video tag reference after the first tech is loaded
  21484. if (this.tag) {
  21485. this.tag.player = null;
  21486. this.tag = null;
  21487. }
  21488. }
  21489. /**
  21490. * Unload and dispose of the current playback {@link Tech}.
  21491. *
  21492. * @private
  21493. */
  21494. unloadTech_() {
  21495. // Save the current text tracks so that we can reuse the same text tracks with the next tech
  21496. ALL.names.forEach(name => {
  21497. const props = ALL[name];
  21498. this[props.privateName] = this[props.getterName]();
  21499. });
  21500. this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
  21501. this.isReady_ = false;
  21502. this.tech_.dispose();
  21503. this.tech_ = false;
  21504. if (this.isPosterFromTech_) {
  21505. this.poster_ = '';
  21506. this.trigger('posterchange');
  21507. }
  21508. this.isPosterFromTech_ = false;
  21509. }
  21510. /**
  21511. * Return a reference to the current {@link Tech}.
  21512. * It will print a warning by default about the danger of using the tech directly
  21513. * but any argument that is passed in will silence the warning.
  21514. *
  21515. * @param {*} [safety]
  21516. * Anything passed in to silence the warning
  21517. *
  21518. * @return {Tech}
  21519. * The Tech
  21520. */
  21521. tech(safety) {
  21522. if (safety === undefined) {
  21523. 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');
  21524. }
  21525. return this.tech_;
  21526. }
  21527. /**
  21528. * Set up click and touch listeners for the playback element
  21529. *
  21530. * - On desktops: a click on the video itself will toggle playback
  21531. * - On mobile devices: a click on the video toggles controls
  21532. * which is done by toggling the user state between active and
  21533. * inactive
  21534. * - A tap can signal that a user has become active or has become inactive
  21535. * e.g. a quick tap on an iPhone movie should reveal the controls. Another
  21536. * quick tap should hide them again (signaling the user is in an inactive
  21537. * viewing state)
  21538. * - In addition to this, we still want the user to be considered inactive after
  21539. * a few seconds of inactivity.
  21540. *
  21541. * > Note: the only part of iOS interaction we can't mimic with this setup
  21542. * is a touch and hold on the video element counting as activity in order to
  21543. * keep the controls showing, but that shouldn't be an issue. A touch and hold
  21544. * on any controls will still keep the user active
  21545. *
  21546. * @private
  21547. */
  21548. addTechControlsListeners_() {
  21549. // Make sure to remove all the previous listeners in case we are called multiple times.
  21550. this.removeTechControlsListeners_();
  21551. this.on(this.tech_, 'click', this.boundHandleTechClick_);
  21552. this.on(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  21553. // If the controls were hidden we don't want that to change without a tap event
  21554. // so we'll check if the controls were already showing before reporting user
  21555. // activity
  21556. this.on(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  21557. this.on(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  21558. this.on(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  21559. // The tap listener needs to come after the touchend listener because the tap
  21560. // listener cancels out any reportedUserActivity when setting userActive(false)
  21561. this.on(this.tech_, 'tap', this.boundHandleTechTap_);
  21562. }
  21563. /**
  21564. * Remove the listeners used for click and tap controls. This is needed for
  21565. * toggling to controls disabled, where a tap/touch should do nothing.
  21566. *
  21567. * @private
  21568. */
  21569. removeTechControlsListeners_() {
  21570. // We don't want to just use `this.off()` because there might be other needed
  21571. // listeners added by techs that extend this.
  21572. this.off(this.tech_, 'tap', this.boundHandleTechTap_);
  21573. this.off(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  21574. this.off(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  21575. this.off(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  21576. this.off(this.tech_, 'click', this.boundHandleTechClick_);
  21577. this.off(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  21578. }
  21579. /**
  21580. * Player waits for the tech to be ready
  21581. *
  21582. * @private
  21583. */
  21584. handleTechReady_() {
  21585. this.triggerReady();
  21586. // Keep the same volume as before
  21587. if (this.cache_.volume) {
  21588. this.techCall_('setVolume', this.cache_.volume);
  21589. }
  21590. // Look if the tech found a higher resolution poster while loading
  21591. this.handleTechPosterChange_();
  21592. // Update the duration if available
  21593. this.handleTechDurationChange_();
  21594. }
  21595. /**
  21596. * Retrigger the `loadstart` event that was triggered by the {@link Tech}.
  21597. *
  21598. * @fires Player#loadstart
  21599. * @listens Tech#loadstart
  21600. * @private
  21601. */
  21602. handleTechLoadStart_() {
  21603. // TODO: Update to use `emptied` event instead. See #1277.
  21604. this.removeClass('vjs-ended', 'vjs-seeking');
  21605. // reset the error state
  21606. this.error(null);
  21607. // Update the duration
  21608. this.handleTechDurationChange_();
  21609. if (!this.paused()) {
  21610. /**
  21611. * Fired when the user agent begins looking for media data
  21612. *
  21613. * @event Player#loadstart
  21614. * @type {Event}
  21615. */
  21616. this.trigger('loadstart');
  21617. } else {
  21618. // reset the hasStarted state
  21619. this.hasStarted(false);
  21620. this.trigger('loadstart');
  21621. }
  21622. // autoplay happens after loadstart for the browser,
  21623. // so we mimic that behavior
  21624. this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? 'play' : this.autoplay());
  21625. }
  21626. /**
  21627. * Handle autoplay string values, rather than the typical boolean
  21628. * values that should be handled by the tech. Note that this is not
  21629. * part of any specification. Valid values and what they do can be
  21630. * found on the autoplay getter at Player#autoplay()
  21631. */
  21632. manualAutoplay_(type) {
  21633. if (!this.tech_ || typeof type !== 'string') {
  21634. return;
  21635. }
  21636. // Save original muted() value, set muted to true, and attempt to play().
  21637. // On promise rejection, restore muted from saved value
  21638. const resolveMuted = () => {
  21639. const previouslyMuted = this.muted();
  21640. this.muted(true);
  21641. const restoreMuted = () => {
  21642. this.muted(previouslyMuted);
  21643. };
  21644. // restore muted on play terminatation
  21645. this.playTerminatedQueue_.push(restoreMuted);
  21646. const mutedPromise = this.play();
  21647. if (!isPromise(mutedPromise)) {
  21648. return;
  21649. }
  21650. return mutedPromise.catch(err => {
  21651. restoreMuted();
  21652. throw new Error(`Rejection at manualAutoplay. Restoring muted value. ${err ? err : ''}`);
  21653. });
  21654. };
  21655. let promise;
  21656. // if muted defaults to true
  21657. // the only thing we can do is call play
  21658. if (type === 'any' && !this.muted()) {
  21659. promise = this.play();
  21660. if (isPromise(promise)) {
  21661. promise = promise.catch(resolveMuted);
  21662. }
  21663. } else if (type === 'muted' && !this.muted()) {
  21664. promise = resolveMuted();
  21665. } else {
  21666. promise = this.play();
  21667. }
  21668. if (!isPromise(promise)) {
  21669. return;
  21670. }
  21671. return promise.then(() => {
  21672. this.trigger({
  21673. type: 'autoplay-success',
  21674. autoplay: type
  21675. });
  21676. }).catch(() => {
  21677. this.trigger({
  21678. type: 'autoplay-failure',
  21679. autoplay: type
  21680. });
  21681. });
  21682. }
  21683. /**
  21684. * Update the internal source caches so that we return the correct source from
  21685. * `src()`, `currentSource()`, and `currentSources()`.
  21686. *
  21687. * > Note: `currentSources` will not be updated if the source that is passed in exists
  21688. * in the current `currentSources` cache.
  21689. *
  21690. *
  21691. * @param {Tech~SourceObject} srcObj
  21692. * A string or object source to update our caches to.
  21693. */
  21694. updateSourceCaches_(srcObj = '') {
  21695. let src = srcObj;
  21696. let type = '';
  21697. if (typeof src !== 'string') {
  21698. src = srcObj.src;
  21699. type = srcObj.type;
  21700. }
  21701. // make sure all the caches are set to default values
  21702. // to prevent null checking
  21703. this.cache_.source = this.cache_.source || {};
  21704. this.cache_.sources = this.cache_.sources || [];
  21705. // try to get the type of the src that was passed in
  21706. if (src && !type) {
  21707. type = findMimetype(this, src);
  21708. }
  21709. // update `currentSource` cache always
  21710. this.cache_.source = merge$2({}, srcObj, {
  21711. src,
  21712. type
  21713. });
  21714. const matchingSources = this.cache_.sources.filter(s => s.src && s.src === src);
  21715. const sourceElSources = [];
  21716. const sourceEls = this.$$('source');
  21717. const matchingSourceEls = [];
  21718. for (let i = 0; i < sourceEls.length; i++) {
  21719. const sourceObj = getAttributes(sourceEls[i]);
  21720. sourceElSources.push(sourceObj);
  21721. if (sourceObj.src && sourceObj.src === src) {
  21722. matchingSourceEls.push(sourceObj.src);
  21723. }
  21724. }
  21725. // if we have matching source els but not matching sources
  21726. // the current source cache is not up to date
  21727. if (matchingSourceEls.length && !matchingSources.length) {
  21728. this.cache_.sources = sourceElSources;
  21729. // if we don't have matching source or source els set the
  21730. // sources cache to the `currentSource` cache
  21731. } else if (!matchingSources.length) {
  21732. this.cache_.sources = [this.cache_.source];
  21733. }
  21734. // update the tech `src` cache
  21735. this.cache_.src = src;
  21736. }
  21737. /**
  21738. * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}
  21739. * causing the media element to reload.
  21740. *
  21741. * It will fire for the initial source and each subsequent source.
  21742. * This event is a custom event from Video.js and is triggered by the {@link Tech}.
  21743. *
  21744. * The event object for this event contains a `src` property that will contain the source
  21745. * that was available when the event was triggered. This is generally only necessary if Video.js
  21746. * is switching techs while the source was being changed.
  21747. *
  21748. * It is also fired when `load` is called on the player (or media element)
  21749. * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
  21750. * says that the resource selection algorithm needs to be aborted and restarted.
  21751. * In this case, it is very likely that the `src` property will be set to the
  21752. * empty string `""` to indicate we do not know what the source will be but
  21753. * that it is changing.
  21754. *
  21755. * *This event is currently still experimental and may change in minor releases.*
  21756. * __To use this, pass `enableSourceset` option to the player.__
  21757. *
  21758. * @event Player#sourceset
  21759. * @type {Event}
  21760. * @prop {string} src
  21761. * The source url available when the `sourceset` was triggered.
  21762. * It will be an empty string if we cannot know what the source is
  21763. * but know that the source will change.
  21764. */
  21765. /**
  21766. * Retrigger the `sourceset` event that was triggered by the {@link Tech}.
  21767. *
  21768. * @fires Player#sourceset
  21769. * @listens Tech#sourceset
  21770. * @private
  21771. */
  21772. handleTechSourceset_(event) {
  21773. // only update the source cache when the source
  21774. // was not updated using the player api
  21775. if (!this.changingSrc_) {
  21776. let updateSourceCaches = src => this.updateSourceCaches_(src);
  21777. const playerSrc = this.currentSource().src;
  21778. const eventSrc = event.src;
  21779. // if we have a playerSrc that is not a blob, and a tech src that is a blob
  21780. if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
  21781. // if both the tech source and the player source were updated we assume
  21782. // something like @videojs/http-streaming did the sourceset and skip updating the source cache.
  21783. if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
  21784. updateSourceCaches = () => {};
  21785. }
  21786. }
  21787. // update the source to the initial source right away
  21788. // in some cases this will be empty string
  21789. updateSourceCaches(eventSrc);
  21790. // if the `sourceset` `src` was an empty string
  21791. // wait for a `loadstart` to update the cache to `currentSrc`.
  21792. // If a sourceset happens before a `loadstart`, we reset the state
  21793. if (!event.src) {
  21794. this.tech_.any(['sourceset', 'loadstart'], e => {
  21795. // if a sourceset happens before a `loadstart` there
  21796. // is nothing to do as this `handleTechSourceset_`
  21797. // will be called again and this will be handled there.
  21798. if (e.type === 'sourceset') {
  21799. return;
  21800. }
  21801. const techSrc = this.techGet('currentSrc');
  21802. this.lastSource_.tech = techSrc;
  21803. this.updateSourceCaches_(techSrc);
  21804. });
  21805. }
  21806. }
  21807. this.lastSource_ = {
  21808. player: this.currentSource().src,
  21809. tech: event.src
  21810. };
  21811. this.trigger({
  21812. src: event.src,
  21813. type: 'sourceset'
  21814. });
  21815. }
  21816. /**
  21817. * Add/remove the vjs-has-started class
  21818. *
  21819. *
  21820. * @param {boolean} request
  21821. * - true: adds the class
  21822. * - false: remove the class
  21823. *
  21824. * @return {boolean}
  21825. * the boolean value of hasStarted_
  21826. */
  21827. hasStarted(request) {
  21828. if (request === undefined) {
  21829. // act as getter, if we have no request to change
  21830. return this.hasStarted_;
  21831. }
  21832. if (request === this.hasStarted_) {
  21833. return;
  21834. }
  21835. this.hasStarted_ = request;
  21836. if (this.hasStarted_) {
  21837. this.addClass('vjs-has-started');
  21838. } else {
  21839. this.removeClass('vjs-has-started');
  21840. }
  21841. }
  21842. /**
  21843. * Fired whenever the media begins or resumes playback
  21844. *
  21845. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
  21846. * @fires Player#play
  21847. * @listens Tech#play
  21848. * @private
  21849. */
  21850. handleTechPlay_() {
  21851. this.removeClass('vjs-ended', 'vjs-paused');
  21852. this.addClass('vjs-playing');
  21853. // hide the poster when the user hits play
  21854. this.hasStarted(true);
  21855. /**
  21856. * Triggered whenever an {@link Tech#play} event happens. Indicates that
  21857. * playback has started or resumed.
  21858. *
  21859. * @event Player#play
  21860. * @type {Event}
  21861. */
  21862. this.trigger('play');
  21863. }
  21864. /**
  21865. * Retrigger the `ratechange` event that was triggered by the {@link Tech}.
  21866. *
  21867. * If there were any events queued while the playback rate was zero, fire
  21868. * those events now.
  21869. *
  21870. * @private
  21871. * @method Player#handleTechRateChange_
  21872. * @fires Player#ratechange
  21873. * @listens Tech#ratechange
  21874. */
  21875. handleTechRateChange_() {
  21876. if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
  21877. this.queuedCallbacks_.forEach(queued => queued.callback(queued.event));
  21878. this.queuedCallbacks_ = [];
  21879. }
  21880. this.cache_.lastPlaybackRate = this.tech_.playbackRate();
  21881. /**
  21882. * Fires when the playing speed of the audio/video is changed
  21883. *
  21884. * @event Player#ratechange
  21885. * @type {event}
  21886. */
  21887. this.trigger('ratechange');
  21888. }
  21889. /**
  21890. * Retrigger the `waiting` event that was triggered by the {@link Tech}.
  21891. *
  21892. * @fires Player#waiting
  21893. * @listens Tech#waiting
  21894. * @private
  21895. */
  21896. handleTechWaiting_() {
  21897. this.addClass('vjs-waiting');
  21898. /**
  21899. * A readyState change on the DOM element has caused playback to stop.
  21900. *
  21901. * @event Player#waiting
  21902. * @type {Event}
  21903. */
  21904. this.trigger('waiting');
  21905. // Browsers may emit a timeupdate event after a waiting event. In order to prevent
  21906. // premature removal of the waiting class, wait for the time to change.
  21907. const timeWhenWaiting = this.currentTime();
  21908. const timeUpdateListener = () => {
  21909. if (timeWhenWaiting !== this.currentTime()) {
  21910. this.removeClass('vjs-waiting');
  21911. this.off('timeupdate', timeUpdateListener);
  21912. }
  21913. };
  21914. this.on('timeupdate', timeUpdateListener);
  21915. }
  21916. /**
  21917. * Retrigger the `canplay` event that was triggered by the {@link Tech}.
  21918. * > Note: This is not consistent between browsers. See #1351
  21919. *
  21920. * @fires Player#canplay
  21921. * @listens Tech#canplay
  21922. * @private
  21923. */
  21924. handleTechCanPlay_() {
  21925. this.removeClass('vjs-waiting');
  21926. /**
  21927. * The media has a readyState of HAVE_FUTURE_DATA or greater.
  21928. *
  21929. * @event Player#canplay
  21930. * @type {Event}
  21931. */
  21932. this.trigger('canplay');
  21933. }
  21934. /**
  21935. * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.
  21936. *
  21937. * @fires Player#canplaythrough
  21938. * @listens Tech#canplaythrough
  21939. * @private
  21940. */
  21941. handleTechCanPlayThrough_() {
  21942. this.removeClass('vjs-waiting');
  21943. /**
  21944. * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the
  21945. * entire media file can be played without buffering.
  21946. *
  21947. * @event Player#canplaythrough
  21948. * @type {Event}
  21949. */
  21950. this.trigger('canplaythrough');
  21951. }
  21952. /**
  21953. * Retrigger the `playing` event that was triggered by the {@link Tech}.
  21954. *
  21955. * @fires Player#playing
  21956. * @listens Tech#playing
  21957. * @private
  21958. */
  21959. handleTechPlaying_() {
  21960. this.removeClass('vjs-waiting');
  21961. /**
  21962. * The media is no longer blocked from playback, and has started playing.
  21963. *
  21964. * @event Player#playing
  21965. * @type {Event}
  21966. */
  21967. this.trigger('playing');
  21968. }
  21969. /**
  21970. * Retrigger the `seeking` event that was triggered by the {@link Tech}.
  21971. *
  21972. * @fires Player#seeking
  21973. * @listens Tech#seeking
  21974. * @private
  21975. */
  21976. handleTechSeeking_() {
  21977. this.addClass('vjs-seeking');
  21978. /**
  21979. * Fired whenever the player is jumping to a new time
  21980. *
  21981. * @event Player#seeking
  21982. * @type {Event}
  21983. */
  21984. this.trigger('seeking');
  21985. }
  21986. /**
  21987. * Retrigger the `seeked` event that was triggered by the {@link Tech}.
  21988. *
  21989. * @fires Player#seeked
  21990. * @listens Tech#seeked
  21991. * @private
  21992. */
  21993. handleTechSeeked_() {
  21994. this.removeClass('vjs-seeking', 'vjs-ended');
  21995. /**
  21996. * Fired when the player has finished jumping to a new time
  21997. *
  21998. * @event Player#seeked
  21999. * @type {Event}
  22000. */
  22001. this.trigger('seeked');
  22002. }
  22003. /**
  22004. * Retrigger the `pause` event that was triggered by the {@link Tech}.
  22005. *
  22006. * @fires Player#pause
  22007. * @listens Tech#pause
  22008. * @private
  22009. */
  22010. handleTechPause_() {
  22011. this.removeClass('vjs-playing');
  22012. this.addClass('vjs-paused');
  22013. /**
  22014. * Fired whenever the media has been paused
  22015. *
  22016. * @event Player#pause
  22017. * @type {Event}
  22018. */
  22019. this.trigger('pause');
  22020. }
  22021. /**
  22022. * Retrigger the `ended` event that was triggered by the {@link Tech}.
  22023. *
  22024. * @fires Player#ended
  22025. * @listens Tech#ended
  22026. * @private
  22027. */
  22028. handleTechEnded_() {
  22029. this.addClass('vjs-ended');
  22030. this.removeClass('vjs-waiting');
  22031. if (this.options_.loop) {
  22032. this.currentTime(0);
  22033. this.play();
  22034. } else if (!this.paused()) {
  22035. this.pause();
  22036. }
  22037. /**
  22038. * Fired when the end of the media resource is reached (currentTime == duration)
  22039. *
  22040. * @event Player#ended
  22041. * @type {Event}
  22042. */
  22043. this.trigger('ended');
  22044. }
  22045. /**
  22046. * Fired when the duration of the media resource is first known or changed
  22047. *
  22048. * @listens Tech#durationchange
  22049. * @private
  22050. */
  22051. handleTechDurationChange_() {
  22052. this.duration(this.techGet_('duration'));
  22053. }
  22054. /**
  22055. * Handle a click on the media element to play/pause
  22056. *
  22057. * @param {Event} event
  22058. * the event that caused this function to trigger
  22059. *
  22060. * @listens Tech#click
  22061. * @private
  22062. */
  22063. handleTechClick_(event) {
  22064. // When controls are disabled a click should not toggle playback because
  22065. // the click is considered a control
  22066. if (!this.controls_) {
  22067. return;
  22068. }
  22069. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.click === undefined || this.options_.userActions.click !== false) {
  22070. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.click === 'function') {
  22071. this.options_.userActions.click.call(this, event);
  22072. } else if (this.paused()) {
  22073. silencePromise(this.play());
  22074. } else {
  22075. this.pause();
  22076. }
  22077. }
  22078. }
  22079. /**
  22080. * Handle a double-click on the media element to enter/exit fullscreen
  22081. *
  22082. * @param {Event} event
  22083. * the event that caused this function to trigger
  22084. *
  22085. * @listens Tech#dblclick
  22086. * @private
  22087. */
  22088. handleTechDoubleClick_(event) {
  22089. if (!this.controls_) {
  22090. return;
  22091. }
  22092. // we do not want to toggle fullscreen state
  22093. // when double-clicking inside a control bar or a modal
  22094. const inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), el => el.contains(event.target));
  22095. if (!inAllowedEls) {
  22096. /*
  22097. * options.userActions.doubleClick
  22098. *
  22099. * If `undefined` or `true`, double-click toggles fullscreen if controls are present
  22100. * Set to `false` to disable double-click handling
  22101. * Set to a function to substitute an external double-click handler
  22102. */
  22103. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) {
  22104. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') {
  22105. this.options_.userActions.doubleClick.call(this, event);
  22106. } else if (this.isFullscreen()) {
  22107. this.exitFullscreen();
  22108. } else {
  22109. this.requestFullscreen();
  22110. }
  22111. }
  22112. }
  22113. }
  22114. /**
  22115. * Handle a tap on the media element. It will toggle the user
  22116. * activity state, which hides and shows the controls.
  22117. *
  22118. * @listens Tech#tap
  22119. * @private
  22120. */
  22121. handleTechTap_() {
  22122. this.userActive(!this.userActive());
  22123. }
  22124. /**
  22125. * Handle touch to start
  22126. *
  22127. * @listens Tech#touchstart
  22128. * @private
  22129. */
  22130. handleTechTouchStart_() {
  22131. this.userWasActive = this.userActive();
  22132. }
  22133. /**
  22134. * Handle touch to move
  22135. *
  22136. * @listens Tech#touchmove
  22137. * @private
  22138. */
  22139. handleTechTouchMove_() {
  22140. if (this.userWasActive) {
  22141. this.reportUserActivity();
  22142. }
  22143. }
  22144. /**
  22145. * Handle touch to end
  22146. *
  22147. * @param {Event} event
  22148. * the touchend event that triggered
  22149. * this function
  22150. *
  22151. * @listens Tech#touchend
  22152. * @private
  22153. */
  22154. handleTechTouchEnd_(event) {
  22155. // Stop the mouse events from also happening
  22156. if (event.cancelable) {
  22157. event.preventDefault();
  22158. }
  22159. }
  22160. /**
  22161. * @private
  22162. */
  22163. toggleFullscreenClass_() {
  22164. if (this.isFullscreen()) {
  22165. this.addClass('vjs-fullscreen');
  22166. } else {
  22167. this.removeClass('vjs-fullscreen');
  22168. }
  22169. }
  22170. /**
  22171. * when the document fschange event triggers it calls this
  22172. */
  22173. documentFullscreenChange_(e) {
  22174. const targetPlayer = e.target.player;
  22175. // if another player was fullscreen
  22176. // do a null check for targetPlayer because older firefox's would put document as e.target
  22177. if (targetPlayer && targetPlayer !== this) {
  22178. return;
  22179. }
  22180. const el = this.el();
  22181. let isFs = document[this.fsApi_.fullscreenElement] === el;
  22182. if (!isFs && el.matches) {
  22183. isFs = el.matches(':' + this.fsApi_.fullscreen);
  22184. } else if (!isFs && el.msMatchesSelector) {
  22185. isFs = el.msMatchesSelector(':' + this.fsApi_.fullscreen);
  22186. }
  22187. this.isFullscreen(isFs);
  22188. }
  22189. /**
  22190. * Handle Tech Fullscreen Change
  22191. *
  22192. * @param {Event} event
  22193. * the fullscreenchange event that triggered this function
  22194. *
  22195. * @param {Object} data
  22196. * the data that was sent with the event
  22197. *
  22198. * @private
  22199. * @listens Tech#fullscreenchange
  22200. * @fires Player#fullscreenchange
  22201. */
  22202. handleTechFullscreenChange_(event, data) {
  22203. if (data) {
  22204. if (data.nativeIOSFullscreen) {
  22205. this.addClass('vjs-ios-native-fs');
  22206. this.tech_.one('webkitendfullscreen', () => {
  22207. this.removeClass('vjs-ios-native-fs');
  22208. });
  22209. }
  22210. this.isFullscreen(data.isFullscreen);
  22211. }
  22212. }
  22213. handleTechFullscreenError_(event, err) {
  22214. this.trigger('fullscreenerror', err);
  22215. }
  22216. /**
  22217. * @private
  22218. */
  22219. togglePictureInPictureClass_() {
  22220. if (this.isInPictureInPicture()) {
  22221. this.addClass('vjs-picture-in-picture');
  22222. } else {
  22223. this.removeClass('vjs-picture-in-picture');
  22224. }
  22225. }
  22226. /**
  22227. * Handle Tech Enter Picture-in-Picture.
  22228. *
  22229. * @param {Event} event
  22230. * the enterpictureinpicture event that triggered this function
  22231. *
  22232. * @private
  22233. * @listens Tech#enterpictureinpicture
  22234. */
  22235. handleTechEnterPictureInPicture_(event) {
  22236. this.isInPictureInPicture(true);
  22237. }
  22238. /**
  22239. * Handle Tech Leave Picture-in-Picture.
  22240. *
  22241. * @param {Event} event
  22242. * the leavepictureinpicture event that triggered this function
  22243. *
  22244. * @private
  22245. * @listens Tech#leavepictureinpicture
  22246. */
  22247. handleTechLeavePictureInPicture_(event) {
  22248. this.isInPictureInPicture(false);
  22249. }
  22250. /**
  22251. * Fires when an error occurred during the loading of an audio/video.
  22252. *
  22253. * @private
  22254. * @listens Tech#error
  22255. */
  22256. handleTechError_() {
  22257. const error = this.tech_.error();
  22258. this.error(error);
  22259. }
  22260. /**
  22261. * Retrigger the `textdata` event that was triggered by the {@link Tech}.
  22262. *
  22263. * @fires Player#textdata
  22264. * @listens Tech#textdata
  22265. * @private
  22266. */
  22267. handleTechTextData_() {
  22268. let data = null;
  22269. if (arguments.length > 1) {
  22270. data = arguments[1];
  22271. }
  22272. /**
  22273. * Fires when we get a textdata event from tech
  22274. *
  22275. * @event Player#textdata
  22276. * @type {Event}
  22277. */
  22278. this.trigger('textdata', data);
  22279. }
  22280. /**
  22281. * Get object for cached values.
  22282. *
  22283. * @return {Object}
  22284. * get the current object cache
  22285. */
  22286. getCache() {
  22287. return this.cache_;
  22288. }
  22289. /**
  22290. * Resets the internal cache object.
  22291. *
  22292. * Using this function outside the player constructor or reset method may
  22293. * have unintended side-effects.
  22294. *
  22295. * @private
  22296. */
  22297. resetCache_() {
  22298. this.cache_ = {
  22299. // Right now, the currentTime is not _really_ cached because it is always
  22300. // retrieved from the tech (see: currentTime). However, for completeness,
  22301. // we set it to zero here to ensure that if we do start actually caching
  22302. // it, we reset it along with everything else.
  22303. currentTime: 0,
  22304. initTime: 0,
  22305. inactivityTimeout: this.options_.inactivityTimeout,
  22306. duration: NaN,
  22307. lastVolume: 1,
  22308. lastPlaybackRate: this.defaultPlaybackRate(),
  22309. media: null,
  22310. src: '',
  22311. source: {},
  22312. sources: [],
  22313. playbackRates: [],
  22314. volume: 1
  22315. };
  22316. }
  22317. /**
  22318. * Pass values to the playback tech
  22319. *
  22320. * @param {string} [method]
  22321. * the method to call
  22322. *
  22323. * @param {Object} arg
  22324. * the argument to pass
  22325. *
  22326. * @private
  22327. */
  22328. techCall_(method, arg) {
  22329. // If it's not ready yet, call method when it is
  22330. this.ready(function () {
  22331. if (method in allowedSetters) {
  22332. return set(this.middleware_, this.tech_, method, arg);
  22333. } else if (method in allowedMediators) {
  22334. return mediate(this.middleware_, this.tech_, method, arg);
  22335. }
  22336. try {
  22337. if (this.tech_) {
  22338. this.tech_[method](arg);
  22339. }
  22340. } catch (e) {
  22341. log$1(e);
  22342. throw e;
  22343. }
  22344. }, true);
  22345. }
  22346. /**
  22347. * Mediate attempt to call playback tech method
  22348. * and return the value of the method called.
  22349. *
  22350. * @param {string} method
  22351. * Tech method
  22352. *
  22353. * @return {*}
  22354. * Value returned by the tech method called, undefined if tech
  22355. * is not ready or tech method is not present
  22356. *
  22357. * @private
  22358. */
  22359. techGet_(method) {
  22360. if (!this.tech_ || !this.tech_.isReady_) {
  22361. return;
  22362. }
  22363. if (method in allowedGetters) {
  22364. return get(this.middleware_, this.tech_, method);
  22365. } else if (method in allowedMediators) {
  22366. return mediate(this.middleware_, this.tech_, method);
  22367. }
  22368. // Log error when playback tech object is present but method
  22369. // is undefined or unavailable
  22370. try {
  22371. return this.tech_[method]();
  22372. } catch (e) {
  22373. // When building additional tech libs, an expected method may not be defined yet
  22374. if (this.tech_[method] === undefined) {
  22375. log$1(`Video.js: ${method} method not defined for ${this.techName_} playback technology.`, e);
  22376. throw e;
  22377. }
  22378. // When a method isn't available on the object it throws a TypeError
  22379. if (e.name === 'TypeError') {
  22380. log$1(`Video.js: ${method} unavailable on ${this.techName_} playback technology element.`, e);
  22381. this.tech_.isReady_ = false;
  22382. throw e;
  22383. }
  22384. // If error unknown, just log and throw
  22385. log$1(e);
  22386. throw e;
  22387. }
  22388. }
  22389. /**
  22390. * Attempt to begin playback at the first opportunity.
  22391. *
  22392. * @return {Promise|undefined}
  22393. * Returns a promise if the browser supports Promises (or one
  22394. * was passed in as an option). This promise will be resolved on
  22395. * the return value of play. If this is undefined it will fulfill the
  22396. * promise chain otherwise the promise chain will be fulfilled when
  22397. * the promise from play is fulfilled.
  22398. */
  22399. play() {
  22400. return new Promise(resolve => {
  22401. this.play_(resolve);
  22402. });
  22403. }
  22404. /**
  22405. * The actual logic for play, takes a callback that will be resolved on the
  22406. * return value of play. This allows us to resolve to the play promise if there
  22407. * is one on modern browsers.
  22408. *
  22409. * @private
  22410. * @param {Function} [callback]
  22411. * The callback that should be called when the techs play is actually called
  22412. */
  22413. play_(callback = silencePromise) {
  22414. this.playCallbacks_.push(callback);
  22415. const isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));
  22416. const isSafariOrIOS = Boolean(IS_ANY_SAFARI || IS_IOS);
  22417. // treat calls to play_ somewhat like the `one` event function
  22418. if (this.waitToPlay_) {
  22419. this.off(['ready', 'loadstart'], this.waitToPlay_);
  22420. this.waitToPlay_ = null;
  22421. }
  22422. // if the player/tech is not ready or the src itself is not ready
  22423. // queue up a call to play on `ready` or `loadstart`
  22424. if (!this.isReady_ || !isSrcReady) {
  22425. this.waitToPlay_ = e => {
  22426. this.play_();
  22427. };
  22428. this.one(['ready', 'loadstart'], this.waitToPlay_);
  22429. // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod
  22430. // in that case, we need to prime the video element by calling load so it'll be ready in time
  22431. if (!isSrcReady && isSafariOrIOS) {
  22432. this.load();
  22433. }
  22434. return;
  22435. }
  22436. // If the player/tech is ready and we have a source, we can attempt playback.
  22437. const val = this.techGet_('play');
  22438. // For native playback, reset the progress bar if we get a play call from a replay.
  22439. const isNativeReplay = isSafariOrIOS && this.hasClass('vjs-ended');
  22440. if (isNativeReplay) {
  22441. this.resetProgressBar_();
  22442. }
  22443. // play was terminated if the returned value is null
  22444. if (val === null) {
  22445. this.runPlayTerminatedQueue_();
  22446. } else {
  22447. this.runPlayCallbacks_(val);
  22448. }
  22449. }
  22450. /**
  22451. * These functions will be run when if play is terminated. If play
  22452. * runPlayCallbacks_ is run these function will not be run. This allows us
  22453. * to differentiate between a terminated play and an actual call to play.
  22454. */
  22455. runPlayTerminatedQueue_() {
  22456. const queue = this.playTerminatedQueue_.slice(0);
  22457. this.playTerminatedQueue_ = [];
  22458. queue.forEach(function (q) {
  22459. q();
  22460. });
  22461. }
  22462. /**
  22463. * When a callback to play is delayed we have to run these
  22464. * callbacks when play is actually called on the tech. This function
  22465. * runs the callbacks that were delayed and accepts the return value
  22466. * from the tech.
  22467. *
  22468. * @param {undefined|Promise} val
  22469. * The return value from the tech.
  22470. */
  22471. runPlayCallbacks_(val) {
  22472. const callbacks = this.playCallbacks_.slice(0);
  22473. this.playCallbacks_ = [];
  22474. // clear play terminatedQueue since we finished a real play
  22475. this.playTerminatedQueue_ = [];
  22476. callbacks.forEach(function (cb) {
  22477. cb(val);
  22478. });
  22479. }
  22480. /**
  22481. * Pause the video playback
  22482. *
  22483. * @return {Player}
  22484. * A reference to the player object this function was called on
  22485. */
  22486. pause() {
  22487. this.techCall_('pause');
  22488. }
  22489. /**
  22490. * Check if the player is paused or has yet to play
  22491. *
  22492. * @return {boolean}
  22493. * - false: if the media is currently playing
  22494. * - true: if media is not currently playing
  22495. */
  22496. paused() {
  22497. // The initial state of paused should be true (in Safari it's actually false)
  22498. return this.techGet_('paused') === false ? false : true;
  22499. }
  22500. /**
  22501. * Get a TimeRange object representing the current ranges of time that the user
  22502. * has played.
  22503. *
  22504. * @return { import('./utils/time').TimeRange }
  22505. * A time range object that represents all the increments of time that have
  22506. * been played.
  22507. */
  22508. played() {
  22509. return this.techGet_('played') || createTimeRanges$1(0, 0);
  22510. }
  22511. /**
  22512. * Returns whether or not the user is "scrubbing". Scrubbing is
  22513. * when the user has clicked the progress bar handle and is
  22514. * dragging it along the progress bar.
  22515. *
  22516. * @param {boolean} [isScrubbing]
  22517. * whether the user is or is not scrubbing
  22518. *
  22519. * @return {boolean}
  22520. * The value of scrubbing when getting
  22521. */
  22522. scrubbing(isScrubbing) {
  22523. if (typeof isScrubbing === 'undefined') {
  22524. return this.scrubbing_;
  22525. }
  22526. this.scrubbing_ = !!isScrubbing;
  22527. this.techCall_('setScrubbing', this.scrubbing_);
  22528. if (isScrubbing) {
  22529. this.addClass('vjs-scrubbing');
  22530. } else {
  22531. this.removeClass('vjs-scrubbing');
  22532. }
  22533. }
  22534. /**
  22535. * Get or set the current time (in seconds)
  22536. *
  22537. * @param {number|string} [seconds]
  22538. * The time to seek to in seconds
  22539. *
  22540. * @return {number}
  22541. * - the current time in seconds when getting
  22542. */
  22543. currentTime(seconds) {
  22544. if (typeof seconds !== 'undefined') {
  22545. if (seconds < 0) {
  22546. seconds = 0;
  22547. }
  22548. if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {
  22549. this.cache_.initTime = seconds;
  22550. this.off('canplay', this.boundApplyInitTime_);
  22551. this.one('canplay', this.boundApplyInitTime_);
  22552. return;
  22553. }
  22554. this.techCall_('setCurrentTime', seconds);
  22555. this.cache_.initTime = 0;
  22556. return;
  22557. }
  22558. // cache last currentTime and return. default to 0 seconds
  22559. //
  22560. // Caching the currentTime is meant to prevent a massive amount of reads on the tech's
  22561. // currentTime when scrubbing, but may not provide much performance benefit after all.
  22562. // Should be tested. Also something has to read the actual current time or the cache will
  22563. // never get updated.
  22564. this.cache_.currentTime = this.techGet_('currentTime') || 0;
  22565. return this.cache_.currentTime;
  22566. }
  22567. /**
  22568. * Apply the value of initTime stored in cache as currentTime.
  22569. *
  22570. * @private
  22571. */
  22572. applyInitTime_() {
  22573. this.currentTime(this.cache_.initTime);
  22574. }
  22575. /**
  22576. * Normally gets the length in time of the video in seconds;
  22577. * in all but the rarest use cases an argument will NOT be passed to the method
  22578. *
  22579. * > **NOTE**: The video must have started loading before the duration can be
  22580. * known, and depending on preload behaviour may not be known until the video starts
  22581. * playing.
  22582. *
  22583. * @fires Player#durationchange
  22584. *
  22585. * @param {number} [seconds]
  22586. * The duration of the video to set in seconds
  22587. *
  22588. * @return {number}
  22589. * - The duration of the video in seconds when getting
  22590. */
  22591. duration(seconds) {
  22592. if (seconds === undefined) {
  22593. // return NaN if the duration is not known
  22594. return this.cache_.duration !== undefined ? this.cache_.duration : NaN;
  22595. }
  22596. seconds = parseFloat(seconds);
  22597. // Standardize on Infinity for signaling video is live
  22598. if (seconds < 0) {
  22599. seconds = Infinity;
  22600. }
  22601. if (seconds !== this.cache_.duration) {
  22602. // Cache the last set value for optimized scrubbing
  22603. this.cache_.duration = seconds;
  22604. if (seconds === Infinity) {
  22605. this.addClass('vjs-live');
  22606. } else {
  22607. this.removeClass('vjs-live');
  22608. }
  22609. if (!isNaN(seconds)) {
  22610. // Do not fire durationchange unless the duration value is known.
  22611. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  22612. /**
  22613. * @event Player#durationchange
  22614. * @type {Event}
  22615. */
  22616. this.trigger('durationchange');
  22617. }
  22618. }
  22619. }
  22620. /**
  22621. * Calculates how much time is left in the video. Not part
  22622. * of the native video API.
  22623. *
  22624. * @return {number}
  22625. * The time remaining in seconds
  22626. */
  22627. remainingTime() {
  22628. return this.duration() - this.currentTime();
  22629. }
  22630. /**
  22631. * A remaining time function that is intended to be used when
  22632. * the time is to be displayed directly to the user.
  22633. *
  22634. * @return {number}
  22635. * The rounded time remaining in seconds
  22636. */
  22637. remainingTimeDisplay() {
  22638. return Math.floor(this.duration()) - Math.floor(this.currentTime());
  22639. }
  22640. //
  22641. // Kind of like an array of portions of the video that have been downloaded.
  22642. /**
  22643. * Get a TimeRange object with an array of the times of the video
  22644. * that have been downloaded. If you just want the percent of the
  22645. * video that's been downloaded, use bufferedPercent.
  22646. *
  22647. * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
  22648. *
  22649. * @return { import('./utils/time').TimeRange }
  22650. * A mock {@link TimeRanges} object (following HTML spec)
  22651. */
  22652. buffered() {
  22653. let buffered = this.techGet_('buffered');
  22654. if (!buffered || !buffered.length) {
  22655. buffered = createTimeRanges$1(0, 0);
  22656. }
  22657. return buffered;
  22658. }
  22659. /**
  22660. * Get the percent (as a decimal) of the video that's been downloaded.
  22661. * This method is not a part of the native HTML video API.
  22662. *
  22663. * @return {number}
  22664. * A decimal between 0 and 1 representing the percent
  22665. * that is buffered 0 being 0% and 1 being 100%
  22666. */
  22667. bufferedPercent() {
  22668. return bufferedPercent(this.buffered(), this.duration());
  22669. }
  22670. /**
  22671. * Get the ending time of the last buffered time range
  22672. * This is used in the progress bar to encapsulate all time ranges.
  22673. *
  22674. * @return {number}
  22675. * The end of the last buffered time range
  22676. */
  22677. bufferedEnd() {
  22678. const buffered = this.buffered();
  22679. const duration = this.duration();
  22680. let end = buffered.end(buffered.length - 1);
  22681. if (end > duration) {
  22682. end = duration;
  22683. }
  22684. return end;
  22685. }
  22686. /**
  22687. * Get or set the current volume of the media
  22688. *
  22689. * @param {number} [percentAsDecimal]
  22690. * The new volume as a decimal percent:
  22691. * - 0 is muted/0%/off
  22692. * - 1.0 is 100%/full
  22693. * - 0.5 is half volume or 50%
  22694. *
  22695. * @return {number}
  22696. * The current volume as a percent when getting
  22697. */
  22698. volume(percentAsDecimal) {
  22699. let vol;
  22700. if (percentAsDecimal !== undefined) {
  22701. // Force value to between 0 and 1
  22702. vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal)));
  22703. this.cache_.volume = vol;
  22704. this.techCall_('setVolume', vol);
  22705. if (vol > 0) {
  22706. this.lastVolume_(vol);
  22707. }
  22708. return;
  22709. }
  22710. // Default to 1 when returning current volume.
  22711. vol = parseFloat(this.techGet_('volume'));
  22712. return isNaN(vol) ? 1 : vol;
  22713. }
  22714. /**
  22715. * Get the current muted state, or turn mute on or off
  22716. *
  22717. * @param {boolean} [muted]
  22718. * - true to mute
  22719. * - false to unmute
  22720. *
  22721. * @return {boolean}
  22722. * - true if mute is on and getting
  22723. * - false if mute is off and getting
  22724. */
  22725. muted(muted) {
  22726. if (muted !== undefined) {
  22727. this.techCall_('setMuted', muted);
  22728. return;
  22729. }
  22730. return this.techGet_('muted') || false;
  22731. }
  22732. /**
  22733. * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted
  22734. * indicates the state of muted on initial playback.
  22735. *
  22736. * ```js
  22737. * var myPlayer = videojs('some-player-id');
  22738. *
  22739. * myPlayer.src("http://www.example.com/path/to/video.mp4");
  22740. *
  22741. * // get, should be false
  22742. * console.log(myPlayer.defaultMuted());
  22743. * // set to true
  22744. * myPlayer.defaultMuted(true);
  22745. * // get should be true
  22746. * console.log(myPlayer.defaultMuted());
  22747. * ```
  22748. *
  22749. * @param {boolean} [defaultMuted]
  22750. * - true to mute
  22751. * - false to unmute
  22752. *
  22753. * @return {boolean|Player}
  22754. * - true if defaultMuted is on and getting
  22755. * - false if defaultMuted is off and getting
  22756. * - A reference to the current player when setting
  22757. */
  22758. defaultMuted(defaultMuted) {
  22759. if (defaultMuted !== undefined) {
  22760. return this.techCall_('setDefaultMuted', defaultMuted);
  22761. }
  22762. return this.techGet_('defaultMuted') || false;
  22763. }
  22764. /**
  22765. * Get the last volume, or set it
  22766. *
  22767. * @param {number} [percentAsDecimal]
  22768. * The new last volume as a decimal percent:
  22769. * - 0 is muted/0%/off
  22770. * - 1.0 is 100%/full
  22771. * - 0.5 is half volume or 50%
  22772. *
  22773. * @return {number}
  22774. * the current value of lastVolume as a percent when getting
  22775. *
  22776. * @private
  22777. */
  22778. lastVolume_(percentAsDecimal) {
  22779. if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {
  22780. this.cache_.lastVolume = percentAsDecimal;
  22781. return;
  22782. }
  22783. return this.cache_.lastVolume;
  22784. }
  22785. /**
  22786. * Check if current tech can support native fullscreen
  22787. * (e.g. with built in controls like iOS)
  22788. *
  22789. * @return {boolean}
  22790. * if native fullscreen is supported
  22791. */
  22792. supportsFullScreen() {
  22793. return this.techGet_('supportsFullScreen') || false;
  22794. }
  22795. /**
  22796. * Check if the player is in fullscreen mode or tell the player that it
  22797. * is or is not in fullscreen mode.
  22798. *
  22799. * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
  22800. * property and instead document.fullscreenElement is used. But isFullscreen is
  22801. * still a valuable property for internal player workings.
  22802. *
  22803. * @param {boolean} [isFS]
  22804. * Set the players current fullscreen state
  22805. *
  22806. * @return {boolean}
  22807. * - true if fullscreen is on and getting
  22808. * - false if fullscreen is off and getting
  22809. */
  22810. isFullscreen(isFS) {
  22811. if (isFS !== undefined) {
  22812. const oldValue = this.isFullscreen_;
  22813. this.isFullscreen_ = Boolean(isFS);
  22814. // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange
  22815. // this is the only place where we trigger fullscreenchange events for older browsers
  22816. // fullWindow mode is treated as a prefixed event and will get a fullscreenchange event as well
  22817. if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {
  22818. /**
  22819. * @event Player#fullscreenchange
  22820. * @type {Event}
  22821. */
  22822. this.trigger('fullscreenchange');
  22823. }
  22824. this.toggleFullscreenClass_();
  22825. return;
  22826. }
  22827. return this.isFullscreen_;
  22828. }
  22829. /**
  22830. * Increase the size of the video to full screen
  22831. * In some browsers, full screen is not supported natively, so it enters
  22832. * "full window mode", where the video fills the browser window.
  22833. * In browsers and devices that support native full screen, sometimes the
  22834. * browser's default controls will be shown, and not the Video.js custom skin.
  22835. * This includes most mobile devices (iOS, Android) and older versions of
  22836. * Safari.
  22837. *
  22838. * @param {Object} [fullscreenOptions]
  22839. * Override the player fullscreen options
  22840. *
  22841. * @fires Player#fullscreenchange
  22842. */
  22843. requestFullscreen(fullscreenOptions) {
  22844. if (this.isInPictureInPicture()) {
  22845. this.exitPictureInPicture();
  22846. }
  22847. const self = this;
  22848. return new Promise((resolve, reject) => {
  22849. function offHandler() {
  22850. self.off('fullscreenerror', errorHandler);
  22851. self.off('fullscreenchange', changeHandler);
  22852. }
  22853. function changeHandler() {
  22854. offHandler();
  22855. resolve();
  22856. }
  22857. function errorHandler(e, err) {
  22858. offHandler();
  22859. reject(err);
  22860. }
  22861. self.one('fullscreenchange', changeHandler);
  22862. self.one('fullscreenerror', errorHandler);
  22863. const promise = self.requestFullscreenHelper_(fullscreenOptions);
  22864. if (promise) {
  22865. promise.then(offHandler, offHandler);
  22866. promise.then(resolve, reject);
  22867. }
  22868. });
  22869. }
  22870. requestFullscreenHelper_(fullscreenOptions) {
  22871. let fsOptions;
  22872. // Only pass fullscreen options to requestFullscreen in spec-compliant browsers.
  22873. // Use defaults or player configured option unless passed directly to this method.
  22874. if (!this.fsApi_.prefixed) {
  22875. fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
  22876. if (fullscreenOptions !== undefined) {
  22877. fsOptions = fullscreenOptions;
  22878. }
  22879. }
  22880. // This method works as follows:
  22881. // 1. if a fullscreen api is available, use it
  22882. // 1. call requestFullscreen with potential options
  22883. // 2. if we got a promise from above, use it to update isFullscreen()
  22884. // 2. otherwise, if the tech supports fullscreen, call `enterFullScreen` on it.
  22885. // This is particularly used for iPhone, older iPads, and non-safari browser on iOS.
  22886. // 3. otherwise, use "fullWindow" mode
  22887. if (this.fsApi_.requestFullscreen) {
  22888. const promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);
  22889. // Even on browsers with promise support this may not return a promise
  22890. if (promise) {
  22891. promise.then(() => this.isFullscreen(true), () => this.isFullscreen(false));
  22892. }
  22893. return promise;
  22894. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  22895. // we can't take the video.js controls fullscreen but we can go fullscreen
  22896. // with native controls
  22897. this.techCall_('enterFullScreen');
  22898. } else {
  22899. // fullscreen isn't supported so we'll just stretch the video element to
  22900. // fill the viewport
  22901. this.enterFullWindow();
  22902. }
  22903. }
  22904. /**
  22905. * Return the video to its normal size after having been in full screen mode
  22906. *
  22907. * @fires Player#fullscreenchange
  22908. */
  22909. exitFullscreen() {
  22910. const self = this;
  22911. return new Promise((resolve, reject) => {
  22912. function offHandler() {
  22913. self.off('fullscreenerror', errorHandler);
  22914. self.off('fullscreenchange', changeHandler);
  22915. }
  22916. function changeHandler() {
  22917. offHandler();
  22918. resolve();
  22919. }
  22920. function errorHandler(e, err) {
  22921. offHandler();
  22922. reject(err);
  22923. }
  22924. self.one('fullscreenchange', changeHandler);
  22925. self.one('fullscreenerror', errorHandler);
  22926. const promise = self.exitFullscreenHelper_();
  22927. if (promise) {
  22928. promise.then(offHandler, offHandler);
  22929. // map the promise to our resolve/reject methods
  22930. promise.then(resolve, reject);
  22931. }
  22932. });
  22933. }
  22934. exitFullscreenHelper_() {
  22935. if (this.fsApi_.requestFullscreen) {
  22936. const promise = document[this.fsApi_.exitFullscreen]();
  22937. // Even on browsers with promise support this may not return a promise
  22938. if (promise) {
  22939. // we're splitting the promise here, so, we want to catch the
  22940. // potential error so that this chain doesn't have unhandled errors
  22941. silencePromise(promise.then(() => this.isFullscreen(false)));
  22942. }
  22943. return promise;
  22944. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  22945. this.techCall_('exitFullScreen');
  22946. } else {
  22947. this.exitFullWindow();
  22948. }
  22949. }
  22950. /**
  22951. * When fullscreen isn't supported we can stretch the
  22952. * video container to as wide as the browser will let us.
  22953. *
  22954. * @fires Player#enterFullWindow
  22955. */
  22956. enterFullWindow() {
  22957. this.isFullscreen(true);
  22958. this.isFullWindow = true;
  22959. // Storing original doc overflow value to return to when fullscreen is off
  22960. this.docOrigOverflow = document.documentElement.style.overflow;
  22961. // Add listener for esc key to exit fullscreen
  22962. on(document, 'keydown', this.boundFullWindowOnEscKey_);
  22963. // Hide any scroll bars
  22964. document.documentElement.style.overflow = 'hidden';
  22965. // Apply fullscreen styles
  22966. addClass(document.body, 'vjs-full-window');
  22967. /**
  22968. * @event Player#enterFullWindow
  22969. * @type {Event}
  22970. */
  22971. this.trigger('enterFullWindow');
  22972. }
  22973. /**
  22974. * Check for call to either exit full window or
  22975. * full screen on ESC key
  22976. *
  22977. * @param {string} event
  22978. * Event to check for key press
  22979. */
  22980. fullWindowOnEscKey(event) {
  22981. if (keycode.isEventKey(event, 'Esc')) {
  22982. if (this.isFullscreen() === true) {
  22983. if (!this.isFullWindow) {
  22984. this.exitFullscreen();
  22985. } else {
  22986. this.exitFullWindow();
  22987. }
  22988. }
  22989. }
  22990. }
  22991. /**
  22992. * Exit full window
  22993. *
  22994. * @fires Player#exitFullWindow
  22995. */
  22996. exitFullWindow() {
  22997. this.isFullscreen(false);
  22998. this.isFullWindow = false;
  22999. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  23000. // Unhide scroll bars.
  23001. document.documentElement.style.overflow = this.docOrigOverflow;
  23002. // Remove fullscreen styles
  23003. removeClass(document.body, 'vjs-full-window');
  23004. // Resize the box, controller, and poster to original sizes
  23005. // this.positionAll();
  23006. /**
  23007. * @event Player#exitFullWindow
  23008. * @type {Event}
  23009. */
  23010. this.trigger('exitFullWindow');
  23011. }
  23012. /**
  23013. * Disable Picture-in-Picture mode.
  23014. *
  23015. * @param {boolean} value
  23016. * - true will disable Picture-in-Picture mode
  23017. * - false will enable Picture-in-Picture mode
  23018. */
  23019. disablePictureInPicture(value) {
  23020. if (value === undefined) {
  23021. return this.techGet_('disablePictureInPicture');
  23022. }
  23023. this.techCall_('setDisablePictureInPicture', value);
  23024. this.options_.disablePictureInPicture = value;
  23025. this.trigger('disablepictureinpicturechanged');
  23026. }
  23027. /**
  23028. * Check if the player is in Picture-in-Picture mode or tell the player that it
  23029. * is or is not in Picture-in-Picture mode.
  23030. *
  23031. * @param {boolean} [isPiP]
  23032. * Set the players current Picture-in-Picture state
  23033. *
  23034. * @return {boolean}
  23035. * - true if Picture-in-Picture is on and getting
  23036. * - false if Picture-in-Picture is off and getting
  23037. */
  23038. isInPictureInPicture(isPiP) {
  23039. if (isPiP !== undefined) {
  23040. this.isInPictureInPicture_ = !!isPiP;
  23041. this.togglePictureInPictureClass_();
  23042. return;
  23043. }
  23044. return !!this.isInPictureInPicture_;
  23045. }
  23046. /**
  23047. * Create a floating video window always on top of other windows so that users may
  23048. * continue consuming media while they interact with other content sites, or
  23049. * applications on their device.
  23050. *
  23051. * This can use document picture-in-picture or element picture in picture
  23052. *
  23053. * Set `enableDocumentPictureInPicture` to `true` to use docPiP on a supported browser
  23054. * Else set `disablePictureInPicture` to `false` to disable elPiP on a supported browser
  23055. *
  23056. *
  23057. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/}
  23058. * @see [Spec]{@link https://wicg.github.io/document-picture-in-picture/}
  23059. *
  23060. * @fires Player#enterpictureinpicture
  23061. *
  23062. * @return {Promise}
  23063. * A promise with a Picture-in-Picture window.
  23064. */
  23065. requestPictureInPicture() {
  23066. if (this.options_.enableDocumentPictureInPicture && window.documentPictureInPicture) {
  23067. const pipContainer = document.createElement(this.el().tagName);
  23068. pipContainer.classList = this.el().classList;
  23069. pipContainer.classList.add('vjs-pip-container');
  23070. if (this.posterImage) {
  23071. pipContainer.appendChild(this.posterImage.el().cloneNode(true));
  23072. }
  23073. if (this.titleBar) {
  23074. pipContainer.appendChild(this.titleBar.el().cloneNode(true));
  23075. }
  23076. pipContainer.appendChild(createEl('p', {
  23077. className: 'vjs-pip-text'
  23078. }, {}, this.localize('Playing in picture-in-picture')));
  23079. return window.documentPictureInPicture.requestWindow({
  23080. // The aspect ratio won't be correct, Chrome bug https://crbug.com/1407629
  23081. initialAspectRatio: this.videoWidth() / this.videoHeight(),
  23082. copyStyleSheets: true
  23083. }).then(pipWindow => {
  23084. this.el_.parentNode.insertBefore(pipContainer, this.el_);
  23085. pipWindow.document.body.append(this.el_);
  23086. pipWindow.document.body.classList.add('vjs-pip-window');
  23087. this.player_.isInPictureInPicture(true);
  23088. this.player_.trigger('enterpictureinpicture');
  23089. // Listen for the PiP closing event to move the video back.
  23090. pipWindow.addEventListener('unload', event => {
  23091. const pipVideo = event.target.querySelector('.video-js');
  23092. pipContainer.replaceWith(pipVideo);
  23093. this.player_.isInPictureInPicture(false);
  23094. this.player_.trigger('leavepictureinpicture');
  23095. });
  23096. return pipWindow;
  23097. });
  23098. }
  23099. if ('pictureInPictureEnabled' in document && this.disablePictureInPicture() === false) {
  23100. /**
  23101. * This event fires when the player enters picture in picture mode
  23102. *
  23103. * @event Player#enterpictureinpicture
  23104. * @type {Event}
  23105. */
  23106. return this.techGet_('requestPictureInPicture');
  23107. }
  23108. return Promise.reject('No PiP mode is available');
  23109. }
  23110. /**
  23111. * Exit Picture-in-Picture mode.
  23112. *
  23113. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  23114. *
  23115. * @fires Player#leavepictureinpicture
  23116. *
  23117. * @return {Promise}
  23118. * A promise.
  23119. */
  23120. exitPictureInPicture() {
  23121. if (window.documentPictureInPicture && window.documentPictureInPicture.window) {
  23122. // With documentPictureInPicture, Player#leavepictureinpicture is fired in the unload handler
  23123. window.documentPictureInPicture.window.close();
  23124. return Promise.resolve();
  23125. }
  23126. if ('pictureInPictureEnabled' in document) {
  23127. /**
  23128. * This event fires when the player leaves picture in picture mode
  23129. *
  23130. * @event Player#leavepictureinpicture
  23131. * @type {Event}
  23132. */
  23133. return document.exitPictureInPicture();
  23134. }
  23135. }
  23136. /**
  23137. * Called when this Player has focus and a key gets pressed down, or when
  23138. * any Component of this player receives a key press that it doesn't handle.
  23139. * This allows player-wide hotkeys (either as defined below, or optionally
  23140. * by an external function).
  23141. *
  23142. * @param {Event} event
  23143. * The `keydown` event that caused this function to be called.
  23144. *
  23145. * @listens keydown
  23146. */
  23147. handleKeyDown(event) {
  23148. const {
  23149. userActions
  23150. } = this.options_;
  23151. // Bail out if hotkeys are not configured.
  23152. if (!userActions || !userActions.hotkeys) {
  23153. return;
  23154. }
  23155. // Function that determines whether or not to exclude an element from
  23156. // hotkeys handling.
  23157. const excludeElement = el => {
  23158. const tagName = el.tagName.toLowerCase();
  23159. // The first and easiest test is for `contenteditable` elements.
  23160. if (el.isContentEditable) {
  23161. return true;
  23162. }
  23163. // Inputs matching these types will still trigger hotkey handling as
  23164. // they are not text inputs.
  23165. const allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];
  23166. if (tagName === 'input') {
  23167. return allowedInputTypes.indexOf(el.type) === -1;
  23168. }
  23169. // The final test is by tag name. These tags will be excluded entirely.
  23170. const excludedTags = ['textarea'];
  23171. return excludedTags.indexOf(tagName) !== -1;
  23172. };
  23173. // Bail out if the user is focused on an interactive form element.
  23174. if (excludeElement(this.el_.ownerDocument.activeElement)) {
  23175. return;
  23176. }
  23177. if (typeof userActions.hotkeys === 'function') {
  23178. userActions.hotkeys.call(this, event);
  23179. } else {
  23180. this.handleHotkeys(event);
  23181. }
  23182. }
  23183. /**
  23184. * Called when this Player receives a hotkey keydown event.
  23185. * Supported player-wide hotkeys are:
  23186. *
  23187. * f - toggle fullscreen
  23188. * m - toggle mute
  23189. * k or Space - toggle play/pause
  23190. *
  23191. * @param {Event} event
  23192. * The `keydown` event that caused this function to be called.
  23193. */
  23194. handleHotkeys(event) {
  23195. const hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {};
  23196. // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set
  23197. const {
  23198. fullscreenKey = keydownEvent => keycode.isEventKey(keydownEvent, 'f'),
  23199. muteKey = keydownEvent => keycode.isEventKey(keydownEvent, 'm'),
  23200. playPauseKey = keydownEvent => keycode.isEventKey(keydownEvent, 'k') || keycode.isEventKey(keydownEvent, 'Space')
  23201. } = hotkeys;
  23202. if (fullscreenKey.call(this, event)) {
  23203. event.preventDefault();
  23204. event.stopPropagation();
  23205. const FSToggle = Component$1.getComponent('FullscreenToggle');
  23206. if (document[this.fsApi_.fullscreenEnabled] !== false) {
  23207. FSToggle.prototype.handleClick.call(this, event);
  23208. }
  23209. } else if (muteKey.call(this, event)) {
  23210. event.preventDefault();
  23211. event.stopPropagation();
  23212. const MuteToggle = Component$1.getComponent('MuteToggle');
  23213. MuteToggle.prototype.handleClick.call(this, event);
  23214. } else if (playPauseKey.call(this, event)) {
  23215. event.preventDefault();
  23216. event.stopPropagation();
  23217. const PlayToggle = Component$1.getComponent('PlayToggle');
  23218. PlayToggle.prototype.handleClick.call(this, event);
  23219. }
  23220. }
  23221. /**
  23222. * Check whether the player can play a given mimetype
  23223. *
  23224. * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype
  23225. *
  23226. * @param {string} type
  23227. * The mimetype to check
  23228. *
  23229. * @return {string}
  23230. * 'probably', 'maybe', or '' (empty string)
  23231. */
  23232. canPlayType(type) {
  23233. let can;
  23234. // Loop through each playback technology in the options order
  23235. for (let i = 0, j = this.options_.techOrder; i < j.length; i++) {
  23236. const techName = j[i];
  23237. let tech = Tech.getTech(techName);
  23238. // Support old behavior of techs being registered as components.
  23239. // Remove once that deprecated behavior is removed.
  23240. if (!tech) {
  23241. tech = Component$1.getComponent(techName);
  23242. }
  23243. // Check if the current tech is defined before continuing
  23244. if (!tech) {
  23245. log$1.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  23246. continue;
  23247. }
  23248. // Check if the browser supports this technology
  23249. if (tech.isSupported()) {
  23250. can = tech.canPlayType(type);
  23251. if (can) {
  23252. return can;
  23253. }
  23254. }
  23255. }
  23256. return '';
  23257. }
  23258. /**
  23259. * Select source based on tech-order or source-order
  23260. * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
  23261. * defaults to tech-order selection
  23262. *
  23263. * @param {Array} sources
  23264. * The sources for a media asset
  23265. *
  23266. * @return {Object|boolean}
  23267. * Object of source and tech order or false
  23268. */
  23269. selectSource(sources) {
  23270. // Get only the techs specified in `techOrder` that exist and are supported by the
  23271. // current platform
  23272. const techs = this.options_.techOrder.map(techName => {
  23273. return [techName, Tech.getTech(techName)];
  23274. }).filter(([techName, tech]) => {
  23275. // Check if the current tech is defined before continuing
  23276. if (tech) {
  23277. // Check if the browser supports this technology
  23278. return tech.isSupported();
  23279. }
  23280. log$1.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  23281. return false;
  23282. });
  23283. // Iterate over each `innerArray` element once per `outerArray` element and execute
  23284. // `tester` with both. If `tester` returns a non-falsy value, exit early and return
  23285. // that value.
  23286. const findFirstPassingTechSourcePair = function (outerArray, innerArray, tester) {
  23287. let found;
  23288. outerArray.some(outerChoice => {
  23289. return innerArray.some(innerChoice => {
  23290. found = tester(outerChoice, innerChoice);
  23291. if (found) {
  23292. return true;
  23293. }
  23294. });
  23295. });
  23296. return found;
  23297. };
  23298. let foundSourceAndTech;
  23299. const flip = fn => (a, b) => fn(b, a);
  23300. const finder = ([techName, tech], source) => {
  23301. if (tech.canPlaySource(source, this.options_[techName.toLowerCase()])) {
  23302. return {
  23303. source,
  23304. tech: techName
  23305. };
  23306. }
  23307. };
  23308. // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
  23309. // to select from them based on their priority.
  23310. if (this.options_.sourceOrder) {
  23311. // Source-first ordering
  23312. foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
  23313. } else {
  23314. // Tech-first ordering
  23315. foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
  23316. }
  23317. return foundSourceAndTech || false;
  23318. }
  23319. /**
  23320. * Executes source setting and getting logic
  23321. *
  23322. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  23323. * A SourceObject, an array of SourceObjects, or a string referencing
  23324. * a URL to a media source. It is _highly recommended_ that an object
  23325. * or array of objects is used here, so that source selection
  23326. * algorithms can take the `type` into account.
  23327. *
  23328. * If not provided, this method acts as a getter.
  23329. * @param {boolean} isRetry
  23330. * Indicates whether this is being called internally as a result of a retry
  23331. *
  23332. * @return {string|undefined}
  23333. * If the `source` argument is missing, returns the current source
  23334. * URL. Otherwise, returns nothing/undefined.
  23335. */
  23336. handleSrc_(source, isRetry) {
  23337. // getter usage
  23338. if (typeof source === 'undefined') {
  23339. return this.cache_.src || '';
  23340. }
  23341. // Reset retry behavior for new source
  23342. if (this.resetRetryOnError_) {
  23343. this.resetRetryOnError_();
  23344. }
  23345. // filter out invalid sources and turn our source into
  23346. // an array of source objects
  23347. const sources = filterSource(source);
  23348. // if a source was passed in then it is invalid because
  23349. // it was filtered to a zero length Array. So we have to
  23350. // show an error
  23351. if (!sources.length) {
  23352. this.setTimeout(function () {
  23353. this.error({
  23354. code: 4,
  23355. message: this.options_.notSupportedMessage
  23356. });
  23357. }, 0);
  23358. return;
  23359. }
  23360. // initial sources
  23361. this.changingSrc_ = true;
  23362. // Only update the cached source list if we are not retrying a new source after error,
  23363. // since in that case we want to include the failed source(s) in the cache
  23364. if (!isRetry) {
  23365. this.cache_.sources = sources;
  23366. }
  23367. this.updateSourceCaches_(sources[0]);
  23368. // middlewareSource is the source after it has been changed by middleware
  23369. setSource(this, sources[0], (middlewareSource, mws) => {
  23370. this.middleware_ = mws;
  23371. // since sourceSet is async we have to update the cache again after we select a source since
  23372. // the source that is selected could be out of order from the cache update above this callback.
  23373. if (!isRetry) {
  23374. this.cache_.sources = sources;
  23375. }
  23376. this.updateSourceCaches_(middlewareSource);
  23377. const err = this.src_(middlewareSource);
  23378. if (err) {
  23379. if (sources.length > 1) {
  23380. return this.handleSrc_(sources.slice(1));
  23381. }
  23382. this.changingSrc_ = false;
  23383. // We need to wrap this in a timeout to give folks a chance to add error event handlers
  23384. this.setTimeout(function () {
  23385. this.error({
  23386. code: 4,
  23387. message: this.options_.notSupportedMessage
  23388. });
  23389. }, 0);
  23390. // we could not find an appropriate tech, but let's still notify the delegate that this is it
  23391. // this needs a better comment about why this is needed
  23392. this.triggerReady();
  23393. return;
  23394. }
  23395. setTech(mws, this.tech_);
  23396. });
  23397. // Try another available source if this one fails before playback.
  23398. if (sources.length > 1) {
  23399. const retry = () => {
  23400. // Remove the error modal
  23401. this.error(null);
  23402. this.handleSrc_(sources.slice(1), true);
  23403. };
  23404. const stopListeningForErrors = () => {
  23405. this.off('error', retry);
  23406. };
  23407. this.one('error', retry);
  23408. this.one('playing', stopListeningForErrors);
  23409. this.resetRetryOnError_ = () => {
  23410. this.off('error', retry);
  23411. this.off('playing', stopListeningForErrors);
  23412. };
  23413. }
  23414. }
  23415. /**
  23416. * Get or set the video source.
  23417. *
  23418. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  23419. * A SourceObject, an array of SourceObjects, or a string referencing
  23420. * a URL to a media source. It is _highly recommended_ that an object
  23421. * or array of objects is used here, so that source selection
  23422. * algorithms can take the `type` into account.
  23423. *
  23424. * If not provided, this method acts as a getter.
  23425. *
  23426. * @return {string|undefined}
  23427. * If the `source` argument is missing, returns the current source
  23428. * URL. Otherwise, returns nothing/undefined.
  23429. */
  23430. src(source) {
  23431. return this.handleSrc_(source, false);
  23432. }
  23433. /**
  23434. * Set the source object on the tech, returns a boolean that indicates whether
  23435. * there is a tech that can play the source or not
  23436. *
  23437. * @param {Tech~SourceObject} source
  23438. * The source object to set on the Tech
  23439. *
  23440. * @return {boolean}
  23441. * - True if there is no Tech to playback this source
  23442. * - False otherwise
  23443. *
  23444. * @private
  23445. */
  23446. src_(source) {
  23447. const sourceTech = this.selectSource([source]);
  23448. if (!sourceTech) {
  23449. return true;
  23450. }
  23451. if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
  23452. this.changingSrc_ = true;
  23453. // load this technology with the chosen source
  23454. this.loadTech_(sourceTech.tech, sourceTech.source);
  23455. this.tech_.ready(() => {
  23456. this.changingSrc_ = false;
  23457. });
  23458. return false;
  23459. }
  23460. // wait until the tech is ready to set the source
  23461. // and set it synchronously if possible (#2326)
  23462. this.ready(function () {
  23463. // The setSource tech method was added with source handlers
  23464. // so older techs won't support it
  23465. // We need to check the direct prototype for the case where subclasses
  23466. // of the tech do not support source handlers
  23467. if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {
  23468. this.techCall_('setSource', source);
  23469. } else {
  23470. this.techCall_('src', source.src);
  23471. }
  23472. this.changingSrc_ = false;
  23473. }, true);
  23474. return false;
  23475. }
  23476. /**
  23477. * Begin loading the src data.
  23478. */
  23479. load() {
  23480. this.techCall_('load');
  23481. }
  23482. /**
  23483. * Reset the player. Loads the first tech in the techOrder,
  23484. * removes all the text tracks in the existing `tech`,
  23485. * and calls `reset` on the `tech`.
  23486. */
  23487. reset() {
  23488. if (this.paused()) {
  23489. this.doReset_();
  23490. } else {
  23491. const playPromise = this.play();
  23492. silencePromise(playPromise.then(() => this.doReset_()));
  23493. }
  23494. }
  23495. doReset_() {
  23496. if (this.tech_) {
  23497. this.tech_.clearTracks('text');
  23498. }
  23499. this.resetCache_();
  23500. this.poster('');
  23501. this.loadTech_(this.options_.techOrder[0], null);
  23502. this.techCall_('reset');
  23503. this.resetControlBarUI_();
  23504. if (isEvented(this)) {
  23505. this.trigger('playerreset');
  23506. }
  23507. }
  23508. /**
  23509. * Reset Control Bar's UI by calling sub-methods that reset
  23510. * all of Control Bar's components
  23511. */
  23512. resetControlBarUI_() {
  23513. this.resetProgressBar_();
  23514. this.resetPlaybackRate_();
  23515. this.resetVolumeBar_();
  23516. }
  23517. /**
  23518. * Reset tech's progress so progress bar is reset in the UI
  23519. */
  23520. resetProgressBar_() {
  23521. this.currentTime(0);
  23522. const {
  23523. currentTimeDisplay,
  23524. durationDisplay,
  23525. progressControl,
  23526. remainingTimeDisplay
  23527. } = this.controlBar || {};
  23528. const {
  23529. seekBar
  23530. } = progressControl || {};
  23531. if (currentTimeDisplay) {
  23532. currentTimeDisplay.updateContent();
  23533. }
  23534. if (durationDisplay) {
  23535. durationDisplay.updateContent();
  23536. }
  23537. if (remainingTimeDisplay) {
  23538. remainingTimeDisplay.updateContent();
  23539. }
  23540. if (seekBar) {
  23541. seekBar.update();
  23542. if (seekBar.loadProgressBar) {
  23543. seekBar.loadProgressBar.update();
  23544. }
  23545. }
  23546. }
  23547. /**
  23548. * Reset Playback ratio
  23549. */
  23550. resetPlaybackRate_() {
  23551. this.playbackRate(this.defaultPlaybackRate());
  23552. this.handleTechRateChange_();
  23553. }
  23554. /**
  23555. * Reset Volume bar
  23556. */
  23557. resetVolumeBar_() {
  23558. this.volume(1.0);
  23559. this.trigger('volumechange');
  23560. }
  23561. /**
  23562. * Returns all of the current source objects.
  23563. *
  23564. * @return {Tech~SourceObject[]}
  23565. * The current source objects
  23566. */
  23567. currentSources() {
  23568. const source = this.currentSource();
  23569. const sources = [];
  23570. // assume `{}` or `{ src }`
  23571. if (Object.keys(source).length !== 0) {
  23572. sources.push(source);
  23573. }
  23574. return this.cache_.sources || sources;
  23575. }
  23576. /**
  23577. * Returns the current source object.
  23578. *
  23579. * @return {Tech~SourceObject}
  23580. * The current source object
  23581. */
  23582. currentSource() {
  23583. return this.cache_.source || {};
  23584. }
  23585. /**
  23586. * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
  23587. * Can be used in conjunction with `currentType` to assist in rebuilding the current source object.
  23588. *
  23589. * @return {string}
  23590. * The current source
  23591. */
  23592. currentSrc() {
  23593. return this.currentSource() && this.currentSource().src || '';
  23594. }
  23595. /**
  23596. * Get the current source type e.g. video/mp4
  23597. * This can allow you rebuild the current source object so that you could load the same
  23598. * source and tech later
  23599. *
  23600. * @return {string}
  23601. * The source MIME type
  23602. */
  23603. currentType() {
  23604. return this.currentSource() && this.currentSource().type || '';
  23605. }
  23606. /**
  23607. * Get or set the preload attribute
  23608. *
  23609. * @param {boolean} [value]
  23610. * - true means that we should preload
  23611. * - false means that we should not preload
  23612. *
  23613. * @return {string}
  23614. * The preload attribute value when getting
  23615. */
  23616. preload(value) {
  23617. if (value !== undefined) {
  23618. this.techCall_('setPreload', value);
  23619. this.options_.preload = value;
  23620. return;
  23621. }
  23622. return this.techGet_('preload');
  23623. }
  23624. /**
  23625. * Get or set the autoplay option. When this is a boolean it will
  23626. * modify the attribute on the tech. When this is a string the attribute on
  23627. * the tech will be removed and `Player` will handle autoplay on loadstarts.
  23628. *
  23629. * @param {boolean|string} [value]
  23630. * - true: autoplay using the browser behavior
  23631. * - false: do not autoplay
  23632. * - 'play': call play() on every loadstart
  23633. * - 'muted': call muted() then play() on every loadstart
  23634. * - 'any': call play() on every loadstart. if that fails call muted() then play().
  23635. * - *: values other than those listed here will be set `autoplay` to true
  23636. *
  23637. * @return {boolean|string}
  23638. * The current value of autoplay when getting
  23639. */
  23640. autoplay(value) {
  23641. // getter usage
  23642. if (value === undefined) {
  23643. return this.options_.autoplay || false;
  23644. }
  23645. let techAutoplay;
  23646. // if the value is a valid string set it to that, or normalize `true` to 'play', if need be
  23647. if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {
  23648. this.options_.autoplay = value;
  23649. this.manualAutoplay_(typeof value === 'string' ? value : 'play');
  23650. techAutoplay = false;
  23651. // any falsy value sets autoplay to false in the browser,
  23652. // lets do the same
  23653. } else if (!value) {
  23654. this.options_.autoplay = false;
  23655. // any other value (ie truthy) sets autoplay to true
  23656. } else {
  23657. this.options_.autoplay = true;
  23658. }
  23659. techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay;
  23660. // if we don't have a tech then we do not queue up
  23661. // a setAutoplay call on tech ready. We do this because the
  23662. // autoplay option will be passed in the constructor and we
  23663. // do not need to set it twice
  23664. if (this.tech_) {
  23665. this.techCall_('setAutoplay', techAutoplay);
  23666. }
  23667. }
  23668. /**
  23669. * Set or unset the playsinline attribute.
  23670. * Playsinline tells the browser that non-fullscreen playback is preferred.
  23671. *
  23672. * @param {boolean} [value]
  23673. * - true means that we should try to play inline by default
  23674. * - false means that we should use the browser's default playback mode,
  23675. * which in most cases is inline. iOS Safari is a notable exception
  23676. * and plays fullscreen by default.
  23677. *
  23678. * @return {string|Player}
  23679. * - the current value of playsinline
  23680. * - the player when setting
  23681. *
  23682. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  23683. */
  23684. playsinline(value) {
  23685. if (value !== undefined) {
  23686. this.techCall_('setPlaysinline', value);
  23687. this.options_.playsinline = value;
  23688. return this;
  23689. }
  23690. return this.techGet_('playsinline');
  23691. }
  23692. /**
  23693. * Get or set the loop attribute on the video element.
  23694. *
  23695. * @param {boolean} [value]
  23696. * - true means that we should loop the video
  23697. * - false means that we should not loop the video
  23698. *
  23699. * @return {boolean}
  23700. * The current value of loop when getting
  23701. */
  23702. loop(value) {
  23703. if (value !== undefined) {
  23704. this.techCall_('setLoop', value);
  23705. this.options_.loop = value;
  23706. return;
  23707. }
  23708. return this.techGet_('loop');
  23709. }
  23710. /**
  23711. * Get or set the poster image source url
  23712. *
  23713. * @fires Player#posterchange
  23714. *
  23715. * @param {string} [src]
  23716. * Poster image source URL
  23717. *
  23718. * @return {string}
  23719. * The current value of poster when getting
  23720. */
  23721. poster(src) {
  23722. if (src === undefined) {
  23723. return this.poster_;
  23724. }
  23725. // The correct way to remove a poster is to set as an empty string
  23726. // other falsey values will throw errors
  23727. if (!src) {
  23728. src = '';
  23729. }
  23730. if (src === this.poster_) {
  23731. return;
  23732. }
  23733. // update the internal poster variable
  23734. this.poster_ = src;
  23735. // update the tech's poster
  23736. this.techCall_('setPoster', src);
  23737. this.isPosterFromTech_ = false;
  23738. // alert components that the poster has been set
  23739. /**
  23740. * This event fires when the poster image is changed on the player.
  23741. *
  23742. * @event Player#posterchange
  23743. * @type {Event}
  23744. */
  23745. this.trigger('posterchange');
  23746. }
  23747. /**
  23748. * Some techs (e.g. YouTube) can provide a poster source in an
  23749. * asynchronous way. We want the poster component to use this
  23750. * poster source so that it covers up the tech's controls.
  23751. * (YouTube's play button). However we only want to use this
  23752. * source if the player user hasn't set a poster through
  23753. * the normal APIs.
  23754. *
  23755. * @fires Player#posterchange
  23756. * @listens Tech#posterchange
  23757. * @private
  23758. */
  23759. handleTechPosterChange_() {
  23760. if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
  23761. const newPoster = this.tech_.poster() || '';
  23762. if (newPoster !== this.poster_) {
  23763. this.poster_ = newPoster;
  23764. this.isPosterFromTech_ = true;
  23765. // Let components know the poster has changed
  23766. this.trigger('posterchange');
  23767. }
  23768. }
  23769. }
  23770. /**
  23771. * Get or set whether or not the controls are showing.
  23772. *
  23773. * @fires Player#controlsenabled
  23774. *
  23775. * @param {boolean} [bool]
  23776. * - true to turn controls on
  23777. * - false to turn controls off
  23778. *
  23779. * @return {boolean}
  23780. * The current value of controls when getting
  23781. */
  23782. controls(bool) {
  23783. if (bool === undefined) {
  23784. return !!this.controls_;
  23785. }
  23786. bool = !!bool;
  23787. // Don't trigger a change event unless it actually changed
  23788. if (this.controls_ === bool) {
  23789. return;
  23790. }
  23791. this.controls_ = bool;
  23792. if (this.usingNativeControls()) {
  23793. this.techCall_('setControls', bool);
  23794. }
  23795. if (this.controls_) {
  23796. this.removeClass('vjs-controls-disabled');
  23797. this.addClass('vjs-controls-enabled');
  23798. /**
  23799. * @event Player#controlsenabled
  23800. * @type {Event}
  23801. */
  23802. this.trigger('controlsenabled');
  23803. if (!this.usingNativeControls()) {
  23804. this.addTechControlsListeners_();
  23805. }
  23806. } else {
  23807. this.removeClass('vjs-controls-enabled');
  23808. this.addClass('vjs-controls-disabled');
  23809. /**
  23810. * @event Player#controlsdisabled
  23811. * @type {Event}
  23812. */
  23813. this.trigger('controlsdisabled');
  23814. if (!this.usingNativeControls()) {
  23815. this.removeTechControlsListeners_();
  23816. }
  23817. }
  23818. }
  23819. /**
  23820. * Toggle native controls on/off. Native controls are the controls built into
  23821. * devices (e.g. default iPhone controls) or other techs
  23822. * (e.g. Vimeo Controls)
  23823. * **This should only be set by the current tech, because only the tech knows
  23824. * if it can support native controls**
  23825. *
  23826. * @fires Player#usingnativecontrols
  23827. * @fires Player#usingcustomcontrols
  23828. *
  23829. * @param {boolean} [bool]
  23830. * - true to turn native controls on
  23831. * - false to turn native controls off
  23832. *
  23833. * @return {boolean}
  23834. * The current value of native controls when getting
  23835. */
  23836. usingNativeControls(bool) {
  23837. if (bool === undefined) {
  23838. return !!this.usingNativeControls_;
  23839. }
  23840. bool = !!bool;
  23841. // Don't trigger a change event unless it actually changed
  23842. if (this.usingNativeControls_ === bool) {
  23843. return;
  23844. }
  23845. this.usingNativeControls_ = bool;
  23846. if (this.usingNativeControls_) {
  23847. this.addClass('vjs-using-native-controls');
  23848. /**
  23849. * player is using the native device controls
  23850. *
  23851. * @event Player#usingnativecontrols
  23852. * @type {Event}
  23853. */
  23854. this.trigger('usingnativecontrols');
  23855. } else {
  23856. this.removeClass('vjs-using-native-controls');
  23857. /**
  23858. * player is using the custom HTML controls
  23859. *
  23860. * @event Player#usingcustomcontrols
  23861. * @type {Event}
  23862. */
  23863. this.trigger('usingcustomcontrols');
  23864. }
  23865. }
  23866. /**
  23867. * Set or get the current MediaError
  23868. *
  23869. * @fires Player#error
  23870. *
  23871. * @param {MediaError|string|number} [err]
  23872. * A MediaError or a string/number to be turned
  23873. * into a MediaError
  23874. *
  23875. * @return {MediaError|null}
  23876. * The current MediaError when getting (or null)
  23877. */
  23878. error(err) {
  23879. if (err === undefined) {
  23880. return this.error_ || null;
  23881. }
  23882. // allow hooks to modify error object
  23883. hooks('beforeerror').forEach(hookFunction => {
  23884. const newErr = hookFunction(this, err);
  23885. if (!(isObject$1(newErr) && !Array.isArray(newErr) || typeof newErr === 'string' || typeof newErr === 'number' || newErr === null)) {
  23886. this.log.error('please return a value that MediaError expects in beforeerror hooks');
  23887. return;
  23888. }
  23889. err = newErr;
  23890. });
  23891. // Suppress the first error message for no compatible source until
  23892. // user interaction
  23893. if (this.options_.suppressNotSupportedError && err && err.code === 4) {
  23894. const triggerSuppressedError = function () {
  23895. this.error(err);
  23896. };
  23897. this.options_.suppressNotSupportedError = false;
  23898. this.any(['click', 'touchstart'], triggerSuppressedError);
  23899. this.one('loadstart', function () {
  23900. this.off(['click', 'touchstart'], triggerSuppressedError);
  23901. });
  23902. return;
  23903. }
  23904. // restoring to default
  23905. if (err === null) {
  23906. this.error_ = err;
  23907. this.removeClass('vjs-error');
  23908. if (this.errorDisplay) {
  23909. this.errorDisplay.close();
  23910. }
  23911. return;
  23912. }
  23913. this.error_ = new MediaError(err);
  23914. // add the vjs-error classname to the player
  23915. this.addClass('vjs-error');
  23916. // log the name of the error type and any message
  23917. // IE11 logs "[object object]" and required you to expand message to see error object
  23918. log$1.error(`(CODE:${this.error_.code} ${MediaError.errorTypes[this.error_.code]})`, this.error_.message, this.error_);
  23919. /**
  23920. * @event Player#error
  23921. * @type {Event}
  23922. */
  23923. this.trigger('error');
  23924. // notify hooks of the per player error
  23925. hooks('error').forEach(hookFunction => hookFunction(this, this.error_));
  23926. return;
  23927. }
  23928. /**
  23929. * Report user activity
  23930. *
  23931. * @param {Object} event
  23932. * Event object
  23933. */
  23934. reportUserActivity(event) {
  23935. this.userActivity_ = true;
  23936. }
  23937. /**
  23938. * Get/set if user is active
  23939. *
  23940. * @fires Player#useractive
  23941. * @fires Player#userinactive
  23942. *
  23943. * @param {boolean} [bool]
  23944. * - true if the user is active
  23945. * - false if the user is inactive
  23946. *
  23947. * @return {boolean}
  23948. * The current value of userActive when getting
  23949. */
  23950. userActive(bool) {
  23951. if (bool === undefined) {
  23952. return this.userActive_;
  23953. }
  23954. bool = !!bool;
  23955. if (bool === this.userActive_) {
  23956. return;
  23957. }
  23958. this.userActive_ = bool;
  23959. if (this.userActive_) {
  23960. this.userActivity_ = true;
  23961. this.removeClass('vjs-user-inactive');
  23962. this.addClass('vjs-user-active');
  23963. /**
  23964. * @event Player#useractive
  23965. * @type {Event}
  23966. */
  23967. this.trigger('useractive');
  23968. return;
  23969. }
  23970. // Chrome/Safari/IE have bugs where when you change the cursor it can
  23971. // trigger a mousemove event. This causes an issue when you're hiding
  23972. // the cursor when the user is inactive, and a mousemove signals user
  23973. // activity. Making it impossible to go into inactive mode. Specifically
  23974. // this happens in fullscreen when we really need to hide the cursor.
  23975. //
  23976. // When this gets resolved in ALL browsers it can be removed
  23977. // https://code.google.com/p/chromium/issues/detail?id=103041
  23978. if (this.tech_) {
  23979. this.tech_.one('mousemove', function (e) {
  23980. e.stopPropagation();
  23981. e.preventDefault();
  23982. });
  23983. }
  23984. this.userActivity_ = false;
  23985. this.removeClass('vjs-user-active');
  23986. this.addClass('vjs-user-inactive');
  23987. /**
  23988. * @event Player#userinactive
  23989. * @type {Event}
  23990. */
  23991. this.trigger('userinactive');
  23992. }
  23993. /**
  23994. * Listen for user activity based on timeout value
  23995. *
  23996. * @private
  23997. */
  23998. listenForUserActivity_() {
  23999. let mouseInProgress;
  24000. let lastMoveX;
  24001. let lastMoveY;
  24002. const handleActivity = bind_(this, this.reportUserActivity);
  24003. const handleMouseMove = function (e) {
  24004. // #1068 - Prevent mousemove spamming
  24005. // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
  24006. if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
  24007. lastMoveX = e.screenX;
  24008. lastMoveY = e.screenY;
  24009. handleActivity();
  24010. }
  24011. };
  24012. const handleMouseDown = function () {
  24013. handleActivity();
  24014. // For as long as the they are touching the device or have their mouse down,
  24015. // we consider them active even if they're not moving their finger or mouse.
  24016. // So we want to continue to update that they are active
  24017. this.clearInterval(mouseInProgress);
  24018. // Setting userActivity=true now and setting the interval to the same time
  24019. // as the activityCheck interval (250) should ensure we never miss the
  24020. // next activityCheck
  24021. mouseInProgress = this.setInterval(handleActivity, 250);
  24022. };
  24023. const handleMouseUpAndMouseLeave = function (event) {
  24024. handleActivity();
  24025. // Stop the interval that maintains activity if the mouse/touch is down
  24026. this.clearInterval(mouseInProgress);
  24027. };
  24028. // Any mouse movement will be considered user activity
  24029. this.on('mousedown', handleMouseDown);
  24030. this.on('mousemove', handleMouseMove);
  24031. this.on('mouseup', handleMouseUpAndMouseLeave);
  24032. this.on('mouseleave', handleMouseUpAndMouseLeave);
  24033. const controlBar = this.getChild('controlBar');
  24034. // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed)
  24035. // controlBar would no longer be hidden by default timeout.
  24036. if (controlBar && !IS_IOS && !IS_ANDROID) {
  24037. controlBar.on('mouseenter', function (event) {
  24038. if (this.player().options_.inactivityTimeout !== 0) {
  24039. this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;
  24040. }
  24041. this.player().options_.inactivityTimeout = 0;
  24042. });
  24043. controlBar.on('mouseleave', function (event) {
  24044. this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;
  24045. });
  24046. }
  24047. // Listen for keyboard navigation
  24048. // Shouldn't need to use inProgress interval because of key repeat
  24049. this.on('keydown', handleActivity);
  24050. this.on('keyup', handleActivity);
  24051. // Run an interval every 250 milliseconds instead of stuffing everything into
  24052. // the mousemove/touchmove function itself, to prevent performance degradation.
  24053. // `this.reportUserActivity` simply sets this.userActivity_ to true, which
  24054. // then gets picked up by this loop
  24055. // http://ejohn.org/blog/learning-from-twitter/
  24056. let inactivityTimeout;
  24057. this.setInterval(function () {
  24058. // Check to see if mouse/touch activity has happened
  24059. if (!this.userActivity_) {
  24060. return;
  24061. }
  24062. // Reset the activity tracker
  24063. this.userActivity_ = false;
  24064. // If the user state was inactive, set the state to active
  24065. this.userActive(true);
  24066. // Clear any existing inactivity timeout to start the timer over
  24067. this.clearTimeout(inactivityTimeout);
  24068. const timeout = this.options_.inactivityTimeout;
  24069. if (timeout <= 0) {
  24070. return;
  24071. }
  24072. // In <timeout> milliseconds, if no more activity has occurred the
  24073. // user will be considered inactive
  24074. inactivityTimeout = this.setTimeout(function () {
  24075. // Protect against the case where the inactivityTimeout can trigger just
  24076. // before the next user activity is picked up by the activity check loop
  24077. // causing a flicker
  24078. if (!this.userActivity_) {
  24079. this.userActive(false);
  24080. }
  24081. }, timeout);
  24082. }, 250);
  24083. }
  24084. /**
  24085. * Gets or sets the current playback rate. A playback rate of
  24086. * 1.0 represents normal speed and 0.5 would indicate half-speed
  24087. * playback, for instance.
  24088. *
  24089. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
  24090. *
  24091. * @param {number} [rate]
  24092. * New playback rate to set.
  24093. *
  24094. * @return {number}
  24095. * The current playback rate when getting or 1.0
  24096. */
  24097. playbackRate(rate) {
  24098. if (rate !== undefined) {
  24099. // NOTE: this.cache_.lastPlaybackRate is set from the tech handler
  24100. // that is registered above
  24101. this.techCall_('setPlaybackRate', rate);
  24102. return;
  24103. }
  24104. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  24105. return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');
  24106. }
  24107. return 1.0;
  24108. }
  24109. /**
  24110. * Gets or sets the current default playback rate. A default playback rate of
  24111. * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
  24112. * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not
  24113. * not the current playbackRate.
  24114. *
  24115. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
  24116. *
  24117. * @param {number} [rate]
  24118. * New default playback rate to set.
  24119. *
  24120. * @return {number|Player}
  24121. * - The default playback rate when getting or 1.0
  24122. * - the player when setting
  24123. */
  24124. defaultPlaybackRate(rate) {
  24125. if (rate !== undefined) {
  24126. return this.techCall_('setDefaultPlaybackRate', rate);
  24127. }
  24128. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  24129. return this.techGet_('defaultPlaybackRate');
  24130. }
  24131. return 1.0;
  24132. }
  24133. /**
  24134. * Gets or sets the audio flag
  24135. *
  24136. * @param {boolean} bool
  24137. * - true signals that this is an audio player
  24138. * - false signals that this is not an audio player
  24139. *
  24140. * @return {boolean}
  24141. * The current value of isAudio when getting
  24142. */
  24143. isAudio(bool) {
  24144. if (bool !== undefined) {
  24145. this.isAudio_ = !!bool;
  24146. return;
  24147. }
  24148. return !!this.isAudio_;
  24149. }
  24150. enableAudioOnlyUI_() {
  24151. // Update styling immediately to show the control bar so we can get its height
  24152. this.addClass('vjs-audio-only-mode');
  24153. const playerChildren = this.children();
  24154. const controlBar = this.getChild('ControlBar');
  24155. const controlBarHeight = controlBar && controlBar.currentHeight();
  24156. // Hide all player components except the control bar. Control bar components
  24157. // needed only for video are hidden with CSS
  24158. playerChildren.forEach(child => {
  24159. if (child === controlBar) {
  24160. return;
  24161. }
  24162. if (child.el_ && !child.hasClass('vjs-hidden')) {
  24163. child.hide();
  24164. this.audioOnlyCache_.hiddenChildren.push(child);
  24165. }
  24166. });
  24167. this.audioOnlyCache_.playerHeight = this.currentHeight();
  24168. // Set the player height the same as the control bar
  24169. this.height(controlBarHeight);
  24170. this.trigger('audioonlymodechange');
  24171. }
  24172. disableAudioOnlyUI_() {
  24173. this.removeClass('vjs-audio-only-mode');
  24174. // Show player components that were previously hidden
  24175. this.audioOnlyCache_.hiddenChildren.forEach(child => child.show());
  24176. // Reset player height
  24177. this.height(this.audioOnlyCache_.playerHeight);
  24178. this.trigger('audioonlymodechange');
  24179. }
  24180. /**
  24181. * Get the current audioOnlyMode state or set audioOnlyMode to true or false.
  24182. *
  24183. * Setting this to `true` will hide all player components except the control bar,
  24184. * as well as control bar components needed only for video.
  24185. *
  24186. * @param {boolean} [value]
  24187. * The value to set audioOnlyMode to.
  24188. *
  24189. * @return {Promise|boolean}
  24190. * A Promise is returned when setting the state, and a boolean when getting
  24191. * the present state
  24192. */
  24193. audioOnlyMode(value) {
  24194. if (typeof value !== 'boolean' || value === this.audioOnlyMode_) {
  24195. return this.audioOnlyMode_;
  24196. }
  24197. this.audioOnlyMode_ = value;
  24198. // Enable Audio Only Mode
  24199. if (value) {
  24200. const exitPromises = [];
  24201. // Fullscreen and PiP are not supported in audioOnlyMode, so exit if we need to.
  24202. if (this.isInPictureInPicture()) {
  24203. exitPromises.push(this.exitPictureInPicture());
  24204. }
  24205. if (this.isFullscreen()) {
  24206. exitPromises.push(this.exitFullscreen());
  24207. }
  24208. if (this.audioPosterMode()) {
  24209. exitPromises.push(this.audioPosterMode(false));
  24210. }
  24211. return Promise.all(exitPromises).then(() => this.enableAudioOnlyUI_());
  24212. }
  24213. // Disable Audio Only Mode
  24214. return Promise.resolve().then(() => this.disableAudioOnlyUI_());
  24215. }
  24216. enablePosterModeUI_() {
  24217. // Hide the video element and show the poster image to enable posterModeUI
  24218. const tech = this.tech_ && this.tech_;
  24219. tech.hide();
  24220. this.addClass('vjs-audio-poster-mode');
  24221. this.trigger('audiopostermodechange');
  24222. }
  24223. disablePosterModeUI_() {
  24224. // Show the video element and hide the poster image to disable posterModeUI
  24225. const tech = this.tech_ && this.tech_;
  24226. tech.show();
  24227. this.removeClass('vjs-audio-poster-mode');
  24228. this.trigger('audiopostermodechange');
  24229. }
  24230. /**
  24231. * Get the current audioPosterMode state or set audioPosterMode to true or false
  24232. *
  24233. * @param {boolean} [value]
  24234. * The value to set audioPosterMode to.
  24235. *
  24236. * @return {Promise|boolean}
  24237. * A Promise is returned when setting the state, and a boolean when getting
  24238. * the present state
  24239. */
  24240. audioPosterMode(value) {
  24241. if (typeof value !== 'boolean' || value === this.audioPosterMode_) {
  24242. return this.audioPosterMode_;
  24243. }
  24244. this.audioPosterMode_ = value;
  24245. if (value) {
  24246. if (this.audioOnlyMode()) {
  24247. const audioOnlyModePromise = this.audioOnlyMode(false);
  24248. return audioOnlyModePromise.then(() => {
  24249. // enable audio poster mode after audio only mode is disabled
  24250. this.enablePosterModeUI_();
  24251. });
  24252. }
  24253. return Promise.resolve().then(() => {
  24254. // enable audio poster mode
  24255. this.enablePosterModeUI_();
  24256. });
  24257. }
  24258. return Promise.resolve().then(() => {
  24259. // disable audio poster mode
  24260. this.disablePosterModeUI_();
  24261. });
  24262. }
  24263. /**
  24264. * A helper method for adding a {@link TextTrack} to our
  24265. * {@link TextTrackList}.
  24266. *
  24267. * In addition to the W3C settings we allow adding additional info through options.
  24268. *
  24269. * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
  24270. *
  24271. * @param {string} [kind]
  24272. * the kind of TextTrack you are adding
  24273. *
  24274. * @param {string} [label]
  24275. * the label to give the TextTrack label
  24276. *
  24277. * @param {string} [language]
  24278. * the language to set on the TextTrack
  24279. *
  24280. * @return {TextTrack|undefined}
  24281. * the TextTrack that was added or undefined
  24282. * if there is no tech
  24283. */
  24284. addTextTrack(kind, label, language) {
  24285. if (this.tech_) {
  24286. return this.tech_.addTextTrack(kind, label, language);
  24287. }
  24288. }
  24289. /**
  24290. * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}.
  24291. *
  24292. * @param {Object} options
  24293. * Options to pass to {@link HTMLTrackElement} during creation. See
  24294. * {@link HTMLTrackElement} for object properties that you should use.
  24295. *
  24296. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack will not be removed
  24297. * from the TextTrackList and HtmlTrackElementList
  24298. * after a source change
  24299. *
  24300. * @return { import('./tracks/html-track-element').default }
  24301. * the HTMLTrackElement that was created and added
  24302. * to the HtmlTrackElementList and the remote
  24303. * TextTrackList
  24304. *
  24305. */
  24306. addRemoteTextTrack(options, manualCleanup) {
  24307. if (this.tech_) {
  24308. return this.tech_.addRemoteTextTrack(options, manualCleanup);
  24309. }
  24310. }
  24311. /**
  24312. * Remove a remote {@link TextTrack} from the respective
  24313. * {@link TextTrackList} and {@link HtmlTrackElementList}.
  24314. *
  24315. * @param {Object} track
  24316. * Remote {@link TextTrack} to remove
  24317. *
  24318. * @return {undefined}
  24319. * does not return anything
  24320. */
  24321. removeRemoteTextTrack(obj = {}) {
  24322. let {
  24323. track
  24324. } = obj;
  24325. if (!track) {
  24326. track = obj;
  24327. }
  24328. // destructure the input into an object with a track argument, defaulting to arguments[0]
  24329. // default the whole argument to an empty object if nothing was passed in
  24330. if (this.tech_) {
  24331. return this.tech_.removeRemoteTextTrack(track);
  24332. }
  24333. }
  24334. /**
  24335. * Gets available media playback quality metrics as specified by the W3C's Media
  24336. * Playback Quality API.
  24337. *
  24338. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  24339. *
  24340. * @return {Object|undefined}
  24341. * An object with supported media playback quality metrics or undefined if there
  24342. * is no tech or the tech does not support it.
  24343. */
  24344. getVideoPlaybackQuality() {
  24345. return this.techGet_('getVideoPlaybackQuality');
  24346. }
  24347. /**
  24348. * Get video width
  24349. *
  24350. * @return {number}
  24351. * current video width
  24352. */
  24353. videoWidth() {
  24354. return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
  24355. }
  24356. /**
  24357. * Get video height
  24358. *
  24359. * @return {number}
  24360. * current video height
  24361. */
  24362. videoHeight() {
  24363. return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
  24364. }
  24365. /**
  24366. * The player's language code.
  24367. *
  24368. * Changing the language will trigger
  24369. * [languagechange]{@link Player#event:languagechange}
  24370. * which Components can use to update control text.
  24371. * ClickableComponent will update its control text by default on
  24372. * [languagechange]{@link Player#event:languagechange}.
  24373. *
  24374. * @fires Player#languagechange
  24375. *
  24376. * @param {string} [code]
  24377. * the language code to set the player to
  24378. *
  24379. * @return {string}
  24380. * The current language code when getting
  24381. */
  24382. language(code) {
  24383. if (code === undefined) {
  24384. return this.language_;
  24385. }
  24386. if (this.language_ !== String(code).toLowerCase()) {
  24387. this.language_ = String(code).toLowerCase();
  24388. // during first init, it's possible some things won't be evented
  24389. if (isEvented(this)) {
  24390. /**
  24391. * fires when the player language change
  24392. *
  24393. * @event Player#languagechange
  24394. * @type {Event}
  24395. */
  24396. this.trigger('languagechange');
  24397. }
  24398. }
  24399. }
  24400. /**
  24401. * Get the player's language dictionary
  24402. * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
  24403. * Languages specified directly in the player options have precedence
  24404. *
  24405. * @return {Array}
  24406. * An array of of supported languages
  24407. */
  24408. languages() {
  24409. return merge$2(Player.prototype.options_.languages, this.languages_);
  24410. }
  24411. /**
  24412. * returns a JavaScript object representing the current track
  24413. * information. **DOES not return it as JSON**
  24414. *
  24415. * @return {Object}
  24416. * Object representing the current of track info
  24417. */
  24418. toJSON() {
  24419. const options = merge$2(this.options_);
  24420. const tracks = options.tracks;
  24421. options.tracks = [];
  24422. for (let i = 0; i < tracks.length; i++) {
  24423. let track = tracks[i];
  24424. // deep merge tracks and null out player so no circular references
  24425. track = merge$2(track);
  24426. track.player = undefined;
  24427. options.tracks[i] = track;
  24428. }
  24429. return options;
  24430. }
  24431. /**
  24432. * Creates a simple modal dialog (an instance of the {@link ModalDialog}
  24433. * component) that immediately overlays the player with arbitrary
  24434. * content and removes itself when closed.
  24435. *
  24436. * @param {string|Function|Element|Array|null} content
  24437. * Same as {@link ModalDialog#content}'s param of the same name.
  24438. * The most straight-forward usage is to provide a string or DOM
  24439. * element.
  24440. *
  24441. * @param {Object} [options]
  24442. * Extra options which will be passed on to the {@link ModalDialog}.
  24443. *
  24444. * @return {ModalDialog}
  24445. * the {@link ModalDialog} that was created
  24446. */
  24447. createModal(content, options) {
  24448. options = options || {};
  24449. options.content = content || '';
  24450. const modal = new ModalDialog(this, options);
  24451. this.addChild(modal);
  24452. modal.on('dispose', () => {
  24453. this.removeChild(modal);
  24454. });
  24455. modal.open();
  24456. return modal;
  24457. }
  24458. /**
  24459. * Change breakpoint classes when the player resizes.
  24460. *
  24461. * @private
  24462. */
  24463. updateCurrentBreakpoint_() {
  24464. if (!this.responsive()) {
  24465. return;
  24466. }
  24467. const currentBreakpoint = this.currentBreakpoint();
  24468. const currentWidth = this.currentWidth();
  24469. for (let i = 0; i < BREAKPOINT_ORDER.length; i++) {
  24470. const candidateBreakpoint = BREAKPOINT_ORDER[i];
  24471. const maxWidth = this.breakpoints_[candidateBreakpoint];
  24472. if (currentWidth <= maxWidth) {
  24473. // The current breakpoint did not change, nothing to do.
  24474. if (currentBreakpoint === candidateBreakpoint) {
  24475. return;
  24476. }
  24477. // Only remove a class if there is a current breakpoint.
  24478. if (currentBreakpoint) {
  24479. this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
  24480. }
  24481. this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
  24482. this.breakpoint_ = candidateBreakpoint;
  24483. break;
  24484. }
  24485. }
  24486. }
  24487. /**
  24488. * Removes the current breakpoint.
  24489. *
  24490. * @private
  24491. */
  24492. removeCurrentBreakpoint_() {
  24493. const className = this.currentBreakpointClass();
  24494. this.breakpoint_ = '';
  24495. if (className) {
  24496. this.removeClass(className);
  24497. }
  24498. }
  24499. /**
  24500. * Get or set breakpoints on the player.
  24501. *
  24502. * Calling this method with an object or `true` will remove any previous
  24503. * custom breakpoints and start from the defaults again.
  24504. *
  24505. * @param {Object|boolean} [breakpoints]
  24506. * If an object is given, it can be used to provide custom
  24507. * breakpoints. If `true` is given, will set default breakpoints.
  24508. * If this argument is not given, will simply return the current
  24509. * breakpoints.
  24510. *
  24511. * @param {number} [breakpoints.tiny]
  24512. * The maximum width for the "vjs-layout-tiny" class.
  24513. *
  24514. * @param {number} [breakpoints.xsmall]
  24515. * The maximum width for the "vjs-layout-x-small" class.
  24516. *
  24517. * @param {number} [breakpoints.small]
  24518. * The maximum width for the "vjs-layout-small" class.
  24519. *
  24520. * @param {number} [breakpoints.medium]
  24521. * The maximum width for the "vjs-layout-medium" class.
  24522. *
  24523. * @param {number} [breakpoints.large]
  24524. * The maximum width for the "vjs-layout-large" class.
  24525. *
  24526. * @param {number} [breakpoints.xlarge]
  24527. * The maximum width for the "vjs-layout-x-large" class.
  24528. *
  24529. * @param {number} [breakpoints.huge]
  24530. * The maximum width for the "vjs-layout-huge" class.
  24531. *
  24532. * @return {Object}
  24533. * An object mapping breakpoint names to maximum width values.
  24534. */
  24535. breakpoints(breakpoints) {
  24536. // Used as a getter.
  24537. if (breakpoints === undefined) {
  24538. return Object.assign(this.breakpoints_);
  24539. }
  24540. this.breakpoint_ = '';
  24541. this.breakpoints_ = Object.assign({}, DEFAULT_BREAKPOINTS, breakpoints);
  24542. // When breakpoint definitions change, we need to update the currently
  24543. // selected breakpoint.
  24544. this.updateCurrentBreakpoint_();
  24545. // Clone the breakpoints before returning.
  24546. return Object.assign(this.breakpoints_);
  24547. }
  24548. /**
  24549. * Get or set a flag indicating whether or not this player should adjust
  24550. * its UI based on its dimensions.
  24551. *
  24552. * @param {boolean} value
  24553. * Should be `true` if the player should adjust its UI based on its
  24554. * dimensions; otherwise, should be `false`.
  24555. *
  24556. * @return {boolean}
  24557. * Will be `true` if this player should adjust its UI based on its
  24558. * dimensions; otherwise, will be `false`.
  24559. */
  24560. responsive(value) {
  24561. // Used as a getter.
  24562. if (value === undefined) {
  24563. return this.responsive_;
  24564. }
  24565. value = Boolean(value);
  24566. const current = this.responsive_;
  24567. // Nothing changed.
  24568. if (value === current) {
  24569. return;
  24570. }
  24571. // The value actually changed, set it.
  24572. this.responsive_ = value;
  24573. // Start listening for breakpoints and set the initial breakpoint if the
  24574. // player is now responsive.
  24575. if (value) {
  24576. this.on('playerresize', this.boundUpdateCurrentBreakpoint_);
  24577. this.updateCurrentBreakpoint_();
  24578. // Stop listening for breakpoints if the player is no longer responsive.
  24579. } else {
  24580. this.off('playerresize', this.boundUpdateCurrentBreakpoint_);
  24581. this.removeCurrentBreakpoint_();
  24582. }
  24583. return value;
  24584. }
  24585. /**
  24586. * Get current breakpoint name, if any.
  24587. *
  24588. * @return {string}
  24589. * If there is currently a breakpoint set, returns a the key from the
  24590. * breakpoints object matching it. Otherwise, returns an empty string.
  24591. */
  24592. currentBreakpoint() {
  24593. return this.breakpoint_;
  24594. }
  24595. /**
  24596. * Get the current breakpoint class name.
  24597. *
  24598. * @return {string}
  24599. * The matching class name (e.g. `"vjs-layout-tiny"` or
  24600. * `"vjs-layout-large"`) for the current breakpoint. Empty string if
  24601. * there is no current breakpoint.
  24602. */
  24603. currentBreakpointClass() {
  24604. return BREAKPOINT_CLASSES[this.breakpoint_] || '';
  24605. }
  24606. /**
  24607. * An object that describes a single piece of media.
  24608. *
  24609. * Properties that are not part of this type description will be retained; so,
  24610. * this can be viewed as a generic metadata storage mechanism as well.
  24611. *
  24612. * @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}
  24613. * @typedef {Object} Player~MediaObject
  24614. *
  24615. * @property {string} [album]
  24616. * Unused, except if this object is passed to the `MediaSession`
  24617. * API.
  24618. *
  24619. * @property {string} [artist]
  24620. * Unused, except if this object is passed to the `MediaSession`
  24621. * API.
  24622. *
  24623. * @property {Object[]} [artwork]
  24624. * Unused, except if this object is passed to the `MediaSession`
  24625. * API. If not specified, will be populated via the `poster`, if
  24626. * available.
  24627. *
  24628. * @property {string} [poster]
  24629. * URL to an image that will display before playback.
  24630. *
  24631. * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src]
  24632. * A single source object, an array of source objects, or a string
  24633. * referencing a URL to a media source. It is _highly recommended_
  24634. * that an object or array of objects is used here, so that source
  24635. * selection algorithms can take the `type` into account.
  24636. *
  24637. * @property {string} [title]
  24638. * Unused, except if this object is passed to the `MediaSession`
  24639. * API.
  24640. *
  24641. * @property {Object[]} [textTracks]
  24642. * An array of objects to be used to create text tracks, following
  24643. * the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}.
  24644. * For ease of removal, these will be created as "remote" text
  24645. * tracks and set to automatically clean up on source changes.
  24646. *
  24647. * These objects may have properties like `src`, `kind`, `label`,
  24648. * and `language`, see {@link Tech#createRemoteTextTrack}.
  24649. */
  24650. /**
  24651. * Populate the player using a {@link Player~MediaObject|MediaObject}.
  24652. *
  24653. * @param {Player~MediaObject} media
  24654. * A media object.
  24655. *
  24656. * @param {Function} ready
  24657. * A callback to be called when the player is ready.
  24658. */
  24659. loadMedia(media, ready) {
  24660. if (!media || typeof media !== 'object') {
  24661. return;
  24662. }
  24663. this.reset();
  24664. // Clone the media object so it cannot be mutated from outside.
  24665. this.cache_.media = merge$2(media);
  24666. const {
  24667. artist,
  24668. artwork,
  24669. description,
  24670. poster,
  24671. src,
  24672. textTracks,
  24673. title
  24674. } = this.cache_.media;
  24675. // If `artwork` is not given, create it using `poster`.
  24676. if (!artwork && poster) {
  24677. this.cache_.media.artwork = [{
  24678. src: poster,
  24679. type: getMimetype(poster)
  24680. }];
  24681. }
  24682. if (src) {
  24683. this.src(src);
  24684. }
  24685. if (poster) {
  24686. this.poster(poster);
  24687. }
  24688. if (Array.isArray(textTracks)) {
  24689. textTracks.forEach(tt => this.addRemoteTextTrack(tt, false));
  24690. }
  24691. if (this.titleBar) {
  24692. this.titleBar.update({
  24693. title,
  24694. description: description || artist || ''
  24695. });
  24696. }
  24697. this.ready(ready);
  24698. }
  24699. /**
  24700. * Get a clone of the current {@link Player~MediaObject} for this player.
  24701. *
  24702. * If the `loadMedia` method has not been used, will attempt to return a
  24703. * {@link Player~MediaObject} based on the current state of the player.
  24704. *
  24705. * @return {Player~MediaObject}
  24706. */
  24707. getMedia() {
  24708. if (!this.cache_.media) {
  24709. const poster = this.poster();
  24710. const src = this.currentSources();
  24711. const textTracks = Array.prototype.map.call(this.remoteTextTracks(), tt => ({
  24712. kind: tt.kind,
  24713. label: tt.label,
  24714. language: tt.language,
  24715. src: tt.src
  24716. }));
  24717. const media = {
  24718. src,
  24719. textTracks
  24720. };
  24721. if (poster) {
  24722. media.poster = poster;
  24723. media.artwork = [{
  24724. src: media.poster,
  24725. type: getMimetype(media.poster)
  24726. }];
  24727. }
  24728. return media;
  24729. }
  24730. return merge$2(this.cache_.media);
  24731. }
  24732. /**
  24733. * Gets tag settings
  24734. *
  24735. * @param {Element} tag
  24736. * The player tag
  24737. *
  24738. * @return {Object}
  24739. * An object containing all of the settings
  24740. * for a player tag
  24741. */
  24742. static getTagSettings(tag) {
  24743. const baseOptions = {
  24744. sources: [],
  24745. tracks: []
  24746. };
  24747. const tagOptions = getAttributes(tag);
  24748. const dataSetup = tagOptions['data-setup'];
  24749. if (hasClass(tag, 'vjs-fill')) {
  24750. tagOptions.fill = true;
  24751. }
  24752. if (hasClass(tag, 'vjs-fluid')) {
  24753. tagOptions.fluid = true;
  24754. }
  24755. // Check if data-setup attr exists.
  24756. if (dataSetup !== null) {
  24757. // Parse options JSON
  24758. // If empty string, make it a parsable json object.
  24759. const [err, data] = tuple(dataSetup || '{}');
  24760. if (err) {
  24761. log$1.error(err);
  24762. }
  24763. Object.assign(tagOptions, data);
  24764. }
  24765. Object.assign(baseOptions, tagOptions);
  24766. // Get tag children settings
  24767. if (tag.hasChildNodes()) {
  24768. const children = tag.childNodes;
  24769. for (let i = 0, j = children.length; i < j; i++) {
  24770. const child = children[i];
  24771. // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
  24772. const childName = child.nodeName.toLowerCase();
  24773. if (childName === 'source') {
  24774. baseOptions.sources.push(getAttributes(child));
  24775. } else if (childName === 'track') {
  24776. baseOptions.tracks.push(getAttributes(child));
  24777. }
  24778. }
  24779. }
  24780. return baseOptions;
  24781. }
  24782. /**
  24783. * Set debug mode to enable/disable logs at info level.
  24784. *
  24785. * @param {boolean} enabled
  24786. * @fires Player#debugon
  24787. * @fires Player#debugoff
  24788. */
  24789. debug(enabled) {
  24790. if (enabled === undefined) {
  24791. return this.debugEnabled_;
  24792. }
  24793. if (enabled) {
  24794. this.trigger('debugon');
  24795. this.previousLogLevel_ = this.log.level;
  24796. this.log.level('debug');
  24797. this.debugEnabled_ = true;
  24798. } else {
  24799. this.trigger('debugoff');
  24800. this.log.level(this.previousLogLevel_);
  24801. this.previousLogLevel_ = undefined;
  24802. this.debugEnabled_ = false;
  24803. }
  24804. }
  24805. /**
  24806. * Set or get current playback rates.
  24807. * Takes an array and updates the playback rates menu with the new items.
  24808. * Pass in an empty array to hide the menu.
  24809. * Values other than arrays are ignored.
  24810. *
  24811. * @fires Player#playbackrateschange
  24812. * @param {number[]} newRates
  24813. * The new rates that the playback rates menu should update to.
  24814. * An empty array will hide the menu
  24815. * @return {number[]} When used as a getter will return the current playback rates
  24816. */
  24817. playbackRates(newRates) {
  24818. if (newRates === undefined) {
  24819. return this.cache_.playbackRates;
  24820. }
  24821. // ignore any value that isn't an array
  24822. if (!Array.isArray(newRates)) {
  24823. return;
  24824. }
  24825. // ignore any arrays that don't only contain numbers
  24826. if (!newRates.every(rate => typeof rate === 'number')) {
  24827. return;
  24828. }
  24829. this.cache_.playbackRates = newRates;
  24830. /**
  24831. * fires when the playback rates in a player are changed
  24832. *
  24833. * @event Player#playbackrateschange
  24834. * @type {Event}
  24835. */
  24836. this.trigger('playbackrateschange');
  24837. }
  24838. }
  24839. /**
  24840. * Get the {@link VideoTrackList}
  24841. *
  24842. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
  24843. *
  24844. * @return {VideoTrackList}
  24845. * the current video track list
  24846. *
  24847. * @method Player.prototype.videoTracks
  24848. */
  24849. /**
  24850. * Get the {@link AudioTrackList}
  24851. *
  24852. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
  24853. *
  24854. * @return {AudioTrackList}
  24855. * the current audio track list
  24856. *
  24857. * @method Player.prototype.audioTracks
  24858. */
  24859. /**
  24860. * Get the {@link TextTrackList}
  24861. *
  24862. * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
  24863. *
  24864. * @return {TextTrackList}
  24865. * the current text track list
  24866. *
  24867. * @method Player.prototype.textTracks
  24868. */
  24869. /**
  24870. * Get the remote {@link TextTrackList}
  24871. *
  24872. * @return {TextTrackList}
  24873. * The current remote text track list
  24874. *
  24875. * @method Player.prototype.remoteTextTracks
  24876. */
  24877. /**
  24878. * Get the remote {@link HtmlTrackElementList} tracks.
  24879. *
  24880. * @return {HtmlTrackElementList}
  24881. * The current remote text track element list
  24882. *
  24883. * @method Player.prototype.remoteTextTrackEls
  24884. */
  24885. ALL.names.forEach(function (name) {
  24886. const props = ALL[name];
  24887. Player.prototype[props.getterName] = function () {
  24888. if (this.tech_) {
  24889. return this.tech_[props.getterName]();
  24890. }
  24891. // if we have not yet loadTech_, we create {video,audio,text}Tracks_
  24892. // these will be passed to the tech during loading
  24893. this[props.privateName] = this[props.privateName] || new props.ListClass();
  24894. return this[props.privateName];
  24895. };
  24896. });
  24897. /**
  24898. * Get or set the `Player`'s crossorigin option. For the HTML5 player, this
  24899. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  24900. * behavior.
  24901. *
  24902. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  24903. *
  24904. * @param {string} [value]
  24905. * The value to set the `Player`'s crossorigin to. If an argument is
  24906. * given, must be one of `anonymous` or `use-credentials`.
  24907. *
  24908. * @return {string|undefined}
  24909. * - The current crossorigin value of the `Player` when getting.
  24910. * - undefined when setting
  24911. */
  24912. Player.prototype.crossorigin = Player.prototype.crossOrigin;
  24913. /**
  24914. * Global enumeration of players.
  24915. *
  24916. * The keys are the player IDs and the values are either the {@link Player}
  24917. * instance or `null` for disposed players.
  24918. *
  24919. * @type {Object}
  24920. */
  24921. Player.players = {};
  24922. const navigator = window.navigator;
  24923. /*
  24924. * Player instance options, surfaced using options
  24925. * options = Player.prototype.options_
  24926. * Make changes in options, not here.
  24927. *
  24928. * @type {Object}
  24929. * @private
  24930. */
  24931. Player.prototype.options_ = {
  24932. // Default order of fallback technology
  24933. techOrder: Tech.defaultTechOrder_,
  24934. html5: {},
  24935. // enable sourceset by default
  24936. enableSourceset: true,
  24937. // default inactivity timeout
  24938. inactivityTimeout: 2000,
  24939. // default playback rates
  24940. playbackRates: [],
  24941. // Add playback rate selection by adding rates
  24942. // 'playbackRates': [0.5, 1, 1.5, 2],
  24943. liveui: false,
  24944. // Included control sets
  24945. children: ['mediaLoader', 'posterImage', 'titleBar', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'],
  24946. language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',
  24947. // locales and their language translations
  24948. languages: {},
  24949. // Default message to show when a video cannot be played.
  24950. notSupportedMessage: 'No compatible source was found for this media.',
  24951. normalizeAutoplay: false,
  24952. fullscreen: {
  24953. options: {
  24954. navigationUI: 'hide'
  24955. }
  24956. },
  24957. breakpoints: {},
  24958. responsive: false,
  24959. audioOnlyMode: false,
  24960. audioPosterMode: false
  24961. };
  24962. [
  24963. /**
  24964. * Returns whether or not the player is in the "ended" state.
  24965. *
  24966. * @return {Boolean} True if the player is in the ended state, false if not.
  24967. * @method Player#ended
  24968. */
  24969. 'ended',
  24970. /**
  24971. * Returns whether or not the player is in the "seeking" state.
  24972. *
  24973. * @return {Boolean} True if the player is in the seeking state, false if not.
  24974. * @method Player#seeking
  24975. */
  24976. 'seeking',
  24977. /**
  24978. * Returns the TimeRanges of the media that are currently available
  24979. * for seeking to.
  24980. *
  24981. * @return {TimeRanges} the seekable intervals of the media timeline
  24982. * @method Player#seekable
  24983. */
  24984. 'seekable',
  24985. /**
  24986. * Returns the current state of network activity for the element, from
  24987. * the codes in the list below.
  24988. * - NETWORK_EMPTY (numeric value 0)
  24989. * The element has not yet been initialised. All attributes are in
  24990. * their initial states.
  24991. * - NETWORK_IDLE (numeric value 1)
  24992. * The element's resource selection algorithm is active and has
  24993. * selected a resource, but it is not actually using the network at
  24994. * this time.
  24995. * - NETWORK_LOADING (numeric value 2)
  24996. * The user agent is actively trying to download data.
  24997. * - NETWORK_NO_SOURCE (numeric value 3)
  24998. * The element's resource selection algorithm is active, but it has
  24999. * not yet found a resource to use.
  25000. *
  25001. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
  25002. * @return {number} the current network activity state
  25003. * @method Player#networkState
  25004. */
  25005. 'networkState',
  25006. /**
  25007. * Returns a value that expresses the current state of the element
  25008. * with respect to rendering the current playback position, from the
  25009. * codes in the list below.
  25010. * - HAVE_NOTHING (numeric value 0)
  25011. * No information regarding the media resource is available.
  25012. * - HAVE_METADATA (numeric value 1)
  25013. * Enough of the resource has been obtained that the duration of the
  25014. * resource is available.
  25015. * - HAVE_CURRENT_DATA (numeric value 2)
  25016. * Data for the immediate current playback position is available.
  25017. * - HAVE_FUTURE_DATA (numeric value 3)
  25018. * Data for the immediate current playback position is available, as
  25019. * well as enough data for the user agent to advance the current
  25020. * playback position in the direction of playback.
  25021. * - HAVE_ENOUGH_DATA (numeric value 4)
  25022. * The user agent estimates that enough data is available for
  25023. * playback to proceed uninterrupted.
  25024. *
  25025. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
  25026. * @return {number} the current playback rendering state
  25027. * @method Player#readyState
  25028. */
  25029. 'readyState'].forEach(function (fn) {
  25030. Player.prototype[fn] = function () {
  25031. return this.techGet_(fn);
  25032. };
  25033. });
  25034. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  25035. Player.prototype[`handleTech${toTitleCase$1(event)}_`] = function () {
  25036. return this.trigger(event);
  25037. };
  25038. });
  25039. /**
  25040. * Fired when the player has initial duration and dimension information
  25041. *
  25042. * @event Player#loadedmetadata
  25043. * @type {Event}
  25044. */
  25045. /**
  25046. * Fired when the player has downloaded data at the current playback position
  25047. *
  25048. * @event Player#loadeddata
  25049. * @type {Event}
  25050. */
  25051. /**
  25052. * Fired when the current playback position has changed *
  25053. * During playback this is fired every 15-250 milliseconds, depending on the
  25054. * playback technology in use.
  25055. *
  25056. * @event Player#timeupdate
  25057. * @type {Event}
  25058. */
  25059. /**
  25060. * Fired when the volume changes
  25061. *
  25062. * @event Player#volumechange
  25063. * @type {Event}
  25064. */
  25065. /**
  25066. * Reports whether or not a player has a plugin available.
  25067. *
  25068. * This does not report whether or not the plugin has ever been initialized
  25069. * on this player. For that, [usingPlugin]{@link Player#usingPlugin}.
  25070. *
  25071. * @method Player#hasPlugin
  25072. * @param {string} name
  25073. * The name of a plugin.
  25074. *
  25075. * @return {boolean}
  25076. * Whether or not this player has the requested plugin available.
  25077. */
  25078. /**
  25079. * Reports whether or not a player is using a plugin by name.
  25080. *
  25081. * For basic plugins, this only reports whether the plugin has _ever_ been
  25082. * initialized on this player.
  25083. *
  25084. * @method Player#usingPlugin
  25085. * @param {string} name
  25086. * The name of a plugin.
  25087. *
  25088. * @return {boolean}
  25089. * Whether or not this player is using the requested plugin.
  25090. */
  25091. Component$1.registerComponent('Player', Player);
  25092. /**
  25093. * @file plugin.js
  25094. */
  25095. /**
  25096. * The base plugin name.
  25097. *
  25098. * @private
  25099. * @constant
  25100. * @type {string}
  25101. */
  25102. const BASE_PLUGIN_NAME = 'plugin';
  25103. /**
  25104. * The key on which a player's active plugins cache is stored.
  25105. *
  25106. * @private
  25107. * @constant
  25108. * @type {string}
  25109. */
  25110. const PLUGIN_CACHE_KEY = 'activePlugins_';
  25111. /**
  25112. * Stores registered plugins in a private space.
  25113. *
  25114. * @private
  25115. * @type {Object}
  25116. */
  25117. const pluginStorage = {};
  25118. /**
  25119. * Reports whether or not a plugin has been registered.
  25120. *
  25121. * @private
  25122. * @param {string} name
  25123. * The name of a plugin.
  25124. *
  25125. * @return {boolean}
  25126. * Whether or not the plugin has been registered.
  25127. */
  25128. const pluginExists = name => pluginStorage.hasOwnProperty(name);
  25129. /**
  25130. * Get a single registered plugin by name.
  25131. *
  25132. * @private
  25133. * @param {string} name
  25134. * The name of a plugin.
  25135. *
  25136. * @return {typeof Plugin|Function|undefined}
  25137. * The plugin (or undefined).
  25138. */
  25139. const getPlugin = name => pluginExists(name) ? pluginStorage[name] : undefined;
  25140. /**
  25141. * Marks a plugin as "active" on a player.
  25142. *
  25143. * Also, ensures that the player has an object for tracking active plugins.
  25144. *
  25145. * @private
  25146. * @param {Player} player
  25147. * A Video.js player instance.
  25148. *
  25149. * @param {string} name
  25150. * The name of a plugin.
  25151. */
  25152. const markPluginAsActive = (player, name) => {
  25153. player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
  25154. player[PLUGIN_CACHE_KEY][name] = true;
  25155. };
  25156. /**
  25157. * Triggers a pair of plugin setup events.
  25158. *
  25159. * @private
  25160. * @param {Player} player
  25161. * A Video.js player instance.
  25162. *
  25163. * @param {Plugin~PluginEventHash} hash
  25164. * A plugin event hash.
  25165. *
  25166. * @param {boolean} [before]
  25167. * If true, prefixes the event name with "before". In other words,
  25168. * use this to trigger "beforepluginsetup" instead of "pluginsetup".
  25169. */
  25170. const triggerSetupEvent = (player, hash, before) => {
  25171. const eventName = (before ? 'before' : '') + 'pluginsetup';
  25172. player.trigger(eventName, hash);
  25173. player.trigger(eventName + ':' + hash.name, hash);
  25174. };
  25175. /**
  25176. * Takes a basic plugin function and returns a wrapper function which marks
  25177. * on the player that the plugin has been activated.
  25178. *
  25179. * @private
  25180. * @param {string} name
  25181. * The name of the plugin.
  25182. *
  25183. * @param {Function} plugin
  25184. * The basic plugin.
  25185. *
  25186. * @return {Function}
  25187. * A wrapper function for the given plugin.
  25188. */
  25189. const createBasicPlugin = function (name, plugin) {
  25190. const basicPluginWrapper = function () {
  25191. // We trigger the "beforepluginsetup" and "pluginsetup" events on the player
  25192. // regardless, but we want the hash to be consistent with the hash provided
  25193. // for advanced plugins.
  25194. //
  25195. // The only potentially counter-intuitive thing here is the `instance` in
  25196. // the "pluginsetup" event is the value returned by the `plugin` function.
  25197. triggerSetupEvent(this, {
  25198. name,
  25199. plugin,
  25200. instance: null
  25201. }, true);
  25202. const instance = plugin.apply(this, arguments);
  25203. markPluginAsActive(this, name);
  25204. triggerSetupEvent(this, {
  25205. name,
  25206. plugin,
  25207. instance
  25208. });
  25209. return instance;
  25210. };
  25211. Object.keys(plugin).forEach(function (prop) {
  25212. basicPluginWrapper[prop] = plugin[prop];
  25213. });
  25214. return basicPluginWrapper;
  25215. };
  25216. /**
  25217. * Takes a plugin sub-class and returns a factory function for generating
  25218. * instances of it.
  25219. *
  25220. * This factory function will replace itself with an instance of the requested
  25221. * sub-class of Plugin.
  25222. *
  25223. * @private
  25224. * @param {string} name
  25225. * The name of the plugin.
  25226. *
  25227. * @param {Plugin} PluginSubClass
  25228. * The advanced plugin.
  25229. *
  25230. * @return {Function}
  25231. */
  25232. const createPluginFactory = (name, PluginSubClass) => {
  25233. // Add a `name` property to the plugin prototype so that each plugin can
  25234. // refer to itself by name.
  25235. PluginSubClass.prototype.name = name;
  25236. return function (...args) {
  25237. triggerSetupEvent(this, {
  25238. name,
  25239. plugin: PluginSubClass,
  25240. instance: null
  25241. }, true);
  25242. const instance = new PluginSubClass(...[this, ...args]);
  25243. // The plugin is replaced by a function that returns the current instance.
  25244. this[name] = () => instance;
  25245. triggerSetupEvent(this, instance.getEventHash());
  25246. return instance;
  25247. };
  25248. };
  25249. /**
  25250. * Parent class for all advanced plugins.
  25251. *
  25252. * @mixes module:evented~EventedMixin
  25253. * @mixes module:stateful~StatefulMixin
  25254. * @fires Player#beforepluginsetup
  25255. * @fires Player#beforepluginsetup:$name
  25256. * @fires Player#pluginsetup
  25257. * @fires Player#pluginsetup:$name
  25258. * @listens Player#dispose
  25259. * @throws {Error}
  25260. * If attempting to instantiate the base {@link Plugin} class
  25261. * directly instead of via a sub-class.
  25262. */
  25263. class Plugin {
  25264. /**
  25265. * Creates an instance of this class.
  25266. *
  25267. * Sub-classes should call `super` to ensure plugins are properly initialized.
  25268. *
  25269. * @param {Player} player
  25270. * A Video.js player instance.
  25271. */
  25272. constructor(player) {
  25273. if (this.constructor === Plugin) {
  25274. throw new Error('Plugin must be sub-classed; not directly instantiated.');
  25275. }
  25276. this.player = player;
  25277. if (!this.log) {
  25278. this.log = this.player.log.createLogger(this.name);
  25279. }
  25280. // Make this object evented, but remove the added `trigger` method so we
  25281. // use the prototype version instead.
  25282. evented(this);
  25283. delete this.trigger;
  25284. stateful(this, this.constructor.defaultState);
  25285. markPluginAsActive(player, this.name);
  25286. // Auto-bind the dispose method so we can use it as a listener and unbind
  25287. // it later easily.
  25288. this.dispose = this.dispose.bind(this);
  25289. // If the player is disposed, dispose the plugin.
  25290. player.on('dispose', this.dispose);
  25291. }
  25292. /**
  25293. * Get the version of the plugin that was set on <pluginName>.VERSION
  25294. */
  25295. version() {
  25296. return this.constructor.VERSION;
  25297. }
  25298. /**
  25299. * Each event triggered by plugins includes a hash of additional data with
  25300. * conventional properties.
  25301. *
  25302. * This returns that object or mutates an existing hash.
  25303. *
  25304. * @param {Object} [hash={}]
  25305. * An object to be used as event an event hash.
  25306. *
  25307. * @return {Plugin~PluginEventHash}
  25308. * An event hash object with provided properties mixed-in.
  25309. */
  25310. getEventHash(hash = {}) {
  25311. hash.name = this.name;
  25312. hash.plugin = this.constructor;
  25313. hash.instance = this;
  25314. return hash;
  25315. }
  25316. /**
  25317. * Triggers an event on the plugin object and overrides
  25318. * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.
  25319. *
  25320. * @param {string|Object} event
  25321. * An event type or an object with a type property.
  25322. *
  25323. * @param {Object} [hash={}]
  25324. * Additional data hash to merge with a
  25325. * {@link Plugin~PluginEventHash|PluginEventHash}.
  25326. *
  25327. * @return {boolean}
  25328. * Whether or not default was prevented.
  25329. */
  25330. trigger(event, hash = {}) {
  25331. return trigger(this.eventBusEl_, event, this.getEventHash(hash));
  25332. }
  25333. /**
  25334. * Handles "statechanged" events on the plugin. No-op by default, override by
  25335. * subclassing.
  25336. *
  25337. * @abstract
  25338. * @param {Event} e
  25339. * An event object provided by a "statechanged" event.
  25340. *
  25341. * @param {Object} e.changes
  25342. * An object describing changes that occurred with the "statechanged"
  25343. * event.
  25344. */
  25345. handleStateChanged(e) {}
  25346. /**
  25347. * Disposes a plugin.
  25348. *
  25349. * Subclasses can override this if they want, but for the sake of safety,
  25350. * it's probably best to subscribe the "dispose" event.
  25351. *
  25352. * @fires Plugin#dispose
  25353. */
  25354. dispose() {
  25355. const {
  25356. name,
  25357. player
  25358. } = this;
  25359. /**
  25360. * Signals that a advanced plugin is about to be disposed.
  25361. *
  25362. * @event Plugin#dispose
  25363. * @type {Event}
  25364. */
  25365. this.trigger('dispose');
  25366. this.off();
  25367. player.off('dispose', this.dispose);
  25368. // Eliminate any possible sources of leaking memory by clearing up
  25369. // references between the player and the plugin instance and nulling out
  25370. // the plugin's state and replacing methods with a function that throws.
  25371. player[PLUGIN_CACHE_KEY][name] = false;
  25372. this.player = this.state = null;
  25373. // Finally, replace the plugin name on the player with a new factory
  25374. // function, so that the plugin is ready to be set up again.
  25375. player[name] = createPluginFactory(name, pluginStorage[name]);
  25376. }
  25377. /**
  25378. * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).
  25379. *
  25380. * @param {string|Function} plugin
  25381. * If a string, matches the name of a plugin. If a function, will be
  25382. * tested directly.
  25383. *
  25384. * @return {boolean}
  25385. * Whether or not a plugin is a basic plugin.
  25386. */
  25387. static isBasic(plugin) {
  25388. const p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;
  25389. return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);
  25390. }
  25391. /**
  25392. * Register a Video.js plugin.
  25393. *
  25394. * @param {string} name
  25395. * The name of the plugin to be registered. Must be a string and
  25396. * must not match an existing plugin or a method on the `Player`
  25397. * prototype.
  25398. *
  25399. * @param {typeof Plugin|Function} plugin
  25400. * A sub-class of `Plugin` or a function for basic plugins.
  25401. *
  25402. * @return {typeof Plugin|Function}
  25403. * For advanced plugins, a factory function for that plugin. For
  25404. * basic plugins, a wrapper function that initializes the plugin.
  25405. */
  25406. static registerPlugin(name, plugin) {
  25407. if (typeof name !== 'string') {
  25408. throw new Error(`Illegal plugin name, "${name}", must be a string, was ${typeof name}.`);
  25409. }
  25410. if (pluginExists(name)) {
  25411. log$1.warn(`A plugin named "${name}" already exists. You may want to avoid re-registering plugins!`);
  25412. } else if (Player.prototype.hasOwnProperty(name)) {
  25413. throw new Error(`Illegal plugin name, "${name}", cannot share a name with an existing player method!`);
  25414. }
  25415. if (typeof plugin !== 'function') {
  25416. throw new Error(`Illegal plugin for "${name}", must be a function, was ${typeof plugin}.`);
  25417. }
  25418. pluginStorage[name] = plugin;
  25419. // Add a player prototype method for all sub-classed plugins (but not for
  25420. // the base Plugin class).
  25421. if (name !== BASE_PLUGIN_NAME) {
  25422. if (Plugin.isBasic(plugin)) {
  25423. Player.prototype[name] = createBasicPlugin(name, plugin);
  25424. } else {
  25425. Player.prototype[name] = createPluginFactory(name, plugin);
  25426. }
  25427. }
  25428. return plugin;
  25429. }
  25430. /**
  25431. * De-register a Video.js plugin.
  25432. *
  25433. * @param {string} name
  25434. * The name of the plugin to be de-registered. Must be a string that
  25435. * matches an existing plugin.
  25436. *
  25437. * @throws {Error}
  25438. * If an attempt is made to de-register the base plugin.
  25439. */
  25440. static deregisterPlugin(name) {
  25441. if (name === BASE_PLUGIN_NAME) {
  25442. throw new Error('Cannot de-register base plugin.');
  25443. }
  25444. if (pluginExists(name)) {
  25445. delete pluginStorage[name];
  25446. delete Player.prototype[name];
  25447. }
  25448. }
  25449. /**
  25450. * Gets an object containing multiple Video.js plugins.
  25451. *
  25452. * @param {Array} [names]
  25453. * If provided, should be an array of plugin names. Defaults to _all_
  25454. * plugin names.
  25455. *
  25456. * @return {Object|undefined}
  25457. * An object containing plugin(s) associated with their name(s) or
  25458. * `undefined` if no matching plugins exist).
  25459. */
  25460. static getPlugins(names = Object.keys(pluginStorage)) {
  25461. let result;
  25462. names.forEach(name => {
  25463. const plugin = getPlugin(name);
  25464. if (plugin) {
  25465. result = result || {};
  25466. result[name] = plugin;
  25467. }
  25468. });
  25469. return result;
  25470. }
  25471. /**
  25472. * Gets a plugin's version, if available
  25473. *
  25474. * @param {string} name
  25475. * The name of a plugin.
  25476. *
  25477. * @return {string}
  25478. * The plugin's version or an empty string.
  25479. */
  25480. static getPluginVersion(name) {
  25481. const plugin = getPlugin(name);
  25482. return plugin && plugin.VERSION || '';
  25483. }
  25484. }
  25485. /**
  25486. * Gets a plugin by name if it exists.
  25487. *
  25488. * @static
  25489. * @method getPlugin
  25490. * @memberOf Plugin
  25491. * @param {string} name
  25492. * The name of a plugin.
  25493. *
  25494. * @returns {typeof Plugin|Function|undefined}
  25495. * The plugin (or `undefined`).
  25496. */
  25497. Plugin.getPlugin = getPlugin;
  25498. /**
  25499. * The name of the base plugin class as it is registered.
  25500. *
  25501. * @type {string}
  25502. */
  25503. Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
  25504. Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
  25505. /**
  25506. * Documented in player.js
  25507. *
  25508. * @ignore
  25509. */
  25510. Player.prototype.usingPlugin = function (name) {
  25511. return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
  25512. };
  25513. /**
  25514. * Documented in player.js
  25515. *
  25516. * @ignore
  25517. */
  25518. Player.prototype.hasPlugin = function (name) {
  25519. return !!pluginExists(name);
  25520. };
  25521. /**
  25522. * Signals that a plugin is about to be set up on a player.
  25523. *
  25524. * @event Player#beforepluginsetup
  25525. * @type {Plugin~PluginEventHash}
  25526. */
  25527. /**
  25528. * Signals that a plugin is about to be set up on a player - by name. The name
  25529. * is the name of the plugin.
  25530. *
  25531. * @event Player#beforepluginsetup:$name
  25532. * @type {Plugin~PluginEventHash}
  25533. */
  25534. /**
  25535. * Signals that a plugin has just been set up on a player.
  25536. *
  25537. * @event Player#pluginsetup
  25538. * @type {Plugin~PluginEventHash}
  25539. */
  25540. /**
  25541. * Signals that a plugin has just been set up on a player - by name. The name
  25542. * is the name of the plugin.
  25543. *
  25544. * @event Player#pluginsetup:$name
  25545. * @type {Plugin~PluginEventHash}
  25546. */
  25547. /**
  25548. * @typedef {Object} Plugin~PluginEventHash
  25549. *
  25550. * @property {string} instance
  25551. * For basic plugins, the return value of the plugin function. For
  25552. * advanced plugins, the plugin instance on which the event is fired.
  25553. *
  25554. * @property {string} name
  25555. * The name of the plugin.
  25556. *
  25557. * @property {string} plugin
  25558. * For basic plugins, the plugin function. For advanced plugins, the
  25559. * plugin class/constructor.
  25560. */
  25561. /**
  25562. * @file deprecate.js
  25563. * @module deprecate
  25564. */
  25565. /**
  25566. * Decorate a function with a deprecation message the first time it is called.
  25567. *
  25568. * @param {string} message
  25569. * A deprecation message to log the first time the returned function
  25570. * is called.
  25571. *
  25572. * @param {Function} fn
  25573. * The function to be deprecated.
  25574. *
  25575. * @return {Function}
  25576. * A wrapper function that will log a deprecation warning the first
  25577. * time it is called. The return value will be the return value of
  25578. * the wrapped function.
  25579. */
  25580. function deprecate(message, fn) {
  25581. let warned = false;
  25582. return function (...args) {
  25583. if (!warned) {
  25584. log$1.warn(message);
  25585. }
  25586. warned = true;
  25587. return fn.apply(this, args);
  25588. };
  25589. }
  25590. /**
  25591. * Internal function used to mark a function as deprecated in the next major
  25592. * version with consistent messaging.
  25593. *
  25594. * @param {number} major The major version where it will be removed
  25595. * @param {string} oldName The old function name
  25596. * @param {string} newName The new function name
  25597. * @param {Function} fn The function to deprecate
  25598. * @return {Function} The decorated function
  25599. */
  25600. function deprecateForMajor(major, oldName, newName, fn) {
  25601. return deprecate(`${oldName} is deprecated and will be removed in ${major}.0; please use ${newName} instead.`, fn);
  25602. }
  25603. /**
  25604. * @file video.js
  25605. * @module videojs
  25606. */
  25607. /**
  25608. * Normalize an `id` value by trimming off a leading `#`
  25609. *
  25610. * @private
  25611. * @param {string} id
  25612. * A string, maybe with a leading `#`.
  25613. *
  25614. * @return {string}
  25615. * The string, without any leading `#`.
  25616. */
  25617. const normalizeId = id => id.indexOf('#') === 0 ? id.slice(1) : id;
  25618. /**
  25619. * A callback that is called when a component is ready. Does not have any
  25620. * parameters and any callback value will be ignored. See: {@link Component~ReadyCallback}
  25621. *
  25622. * @callback ReadyCallback
  25623. */
  25624. /**
  25625. * The `videojs()` function doubles as the main function for users to create a
  25626. * {@link Player} instance as well as the main library namespace.
  25627. *
  25628. * It can also be used as a getter for a pre-existing {@link Player} instance.
  25629. * However, we _strongly_ recommend using `videojs.getPlayer()` for this
  25630. * purpose because it avoids any potential for unintended initialization.
  25631. *
  25632. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  25633. * of our JSDoc template, we cannot properly document this as both a function
  25634. * and a namespace, so its function signature is documented here.
  25635. *
  25636. * #### Arguments
  25637. * ##### id
  25638. * string|Element, **required**
  25639. *
  25640. * Video element or video element ID.
  25641. *
  25642. * ##### options
  25643. * Object, optional
  25644. *
  25645. * Options object for providing settings.
  25646. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  25647. *
  25648. * ##### ready
  25649. * {@link Component~ReadyCallback}, optional
  25650. *
  25651. * A function to be called when the {@link Player} and {@link Tech} are ready.
  25652. *
  25653. * #### Return Value
  25654. *
  25655. * The `videojs()` function returns a {@link Player} instance.
  25656. *
  25657. * @namespace
  25658. *
  25659. * @borrows AudioTrack as AudioTrack
  25660. * @borrows Component.getComponent as getComponent
  25661. * @borrows module:events.on as on
  25662. * @borrows module:events.one as one
  25663. * @borrows module:events.off as off
  25664. * @borrows module:events.trigger as trigger
  25665. * @borrows EventTarget as EventTarget
  25666. * @borrows module:middleware.use as use
  25667. * @borrows Player.players as players
  25668. * @borrows Plugin.registerPlugin as registerPlugin
  25669. * @borrows Plugin.deregisterPlugin as deregisterPlugin
  25670. * @borrows Plugin.getPlugins as getPlugins
  25671. * @borrows Plugin.getPlugin as getPlugin
  25672. * @borrows Plugin.getPluginVersion as getPluginVersion
  25673. * @borrows Tech.getTech as getTech
  25674. * @borrows Tech.registerTech as registerTech
  25675. * @borrows TextTrack as TextTrack
  25676. * @borrows VideoTrack as VideoTrack
  25677. *
  25678. * @param {string|Element} id
  25679. * Video element or video element ID.
  25680. *
  25681. * @param {Object} [options]
  25682. * Options object for providing settings.
  25683. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  25684. *
  25685. * @param {ReadyCallback} [ready]
  25686. * A function to be called when the {@link Player} and {@link Tech} are
  25687. * ready.
  25688. *
  25689. * @return {Player}
  25690. * The `videojs()` function returns a {@link Player|Player} instance.
  25691. */
  25692. function videojs(id, options, ready) {
  25693. let player = videojs.getPlayer(id);
  25694. if (player) {
  25695. if (options) {
  25696. log$1.warn(`Player "${id}" is already initialised. Options will not be applied.`);
  25697. }
  25698. if (ready) {
  25699. player.ready(ready);
  25700. }
  25701. return player;
  25702. }
  25703. const el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;
  25704. if (!isEl(el)) {
  25705. throw new TypeError('The element or ID supplied is not valid. (videojs)');
  25706. }
  25707. // document.body.contains(el) will only check if el is contained within that one document.
  25708. // This causes problems for elements in iframes.
  25709. // Instead, use the element's ownerDocument instead of the global document.
  25710. // This will make sure that the element is indeed in the dom of that document.
  25711. // Additionally, check that the document in question has a default view.
  25712. // If the document is no longer attached to the dom, the defaultView of the document will be null.
  25713. if (!el.ownerDocument.defaultView || !el.ownerDocument.body.contains(el)) {
  25714. log$1.warn('The element supplied is not included in the DOM');
  25715. }
  25716. options = options || {};
  25717. // Store a copy of the el before modification, if it is to be restored in destroy()
  25718. // If div ingest, store the parent div
  25719. if (options.restoreEl === true) {
  25720. options.restoreEl = (el.parentNode && el.parentNode.hasAttribute('data-vjs-player') ? el.parentNode : el).cloneNode(true);
  25721. }
  25722. hooks('beforesetup').forEach(hookFunction => {
  25723. const opts = hookFunction(el, merge$2(options));
  25724. if (!isObject$1(opts) || Array.isArray(opts)) {
  25725. log$1.error('please return an object in beforesetup hooks');
  25726. return;
  25727. }
  25728. options = merge$2(options, opts);
  25729. });
  25730. // We get the current "Player" component here in case an integration has
  25731. // replaced it with a custom player.
  25732. const PlayerComponent = Component$1.getComponent('Player');
  25733. player = new PlayerComponent(el, options, ready);
  25734. hooks('setup').forEach(hookFunction => hookFunction(player));
  25735. return player;
  25736. }
  25737. videojs.hooks_ = hooks_;
  25738. videojs.hooks = hooks;
  25739. videojs.hook = hook;
  25740. videojs.hookOnce = hookOnce;
  25741. videojs.removeHook = removeHook;
  25742. // Add default styles
  25743. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
  25744. let style = $('.vjs-styles-defaults');
  25745. if (!style) {
  25746. style = createStyleElement('vjs-styles-defaults');
  25747. const head = $('head');
  25748. if (head) {
  25749. head.insertBefore(style, head.firstChild);
  25750. }
  25751. setTextContent(style, `
  25752. .video-js {
  25753. width: 300px;
  25754. height: 150px;
  25755. }
  25756. .vjs-fluid:not(.vjs-audio-only-mode) {
  25757. padding-top: 56.25%
  25758. }
  25759. `);
  25760. }
  25761. }
  25762. // Run Auto-load players
  25763. // You have to wait at least once in case this script is loaded after your
  25764. // video in the DOM (weird behavior only with minified version)
  25765. autoSetupTimeout(1, videojs);
  25766. /**
  25767. * Current Video.js version. Follows [semantic versioning](https://semver.org/).
  25768. *
  25769. * @type {string}
  25770. */
  25771. videojs.VERSION = version$5;
  25772. /**
  25773. * The global options object. These are the settings that take effect
  25774. * if no overrides are specified when the player is created.
  25775. *
  25776. * @type {Object}
  25777. */
  25778. videojs.options = Player.prototype.options_;
  25779. /**
  25780. * Get an object with the currently created players, keyed by player ID
  25781. *
  25782. * @return {Object}
  25783. * The created players
  25784. */
  25785. videojs.getPlayers = () => Player.players;
  25786. /**
  25787. * Get a single player based on an ID or DOM element.
  25788. *
  25789. * This is useful if you want to check if an element or ID has an associated
  25790. * Video.js player, but not create one if it doesn't.
  25791. *
  25792. * @param {string|Element} id
  25793. * An HTML element - `<video>`, `<audio>`, or `<video-js>` -
  25794. * or a string matching the `id` of such an element.
  25795. *
  25796. * @return {Player|undefined}
  25797. * A player instance or `undefined` if there is no player instance
  25798. * matching the argument.
  25799. */
  25800. videojs.getPlayer = id => {
  25801. const players = Player.players;
  25802. let tag;
  25803. if (typeof id === 'string') {
  25804. const nId = normalizeId(id);
  25805. const player = players[nId];
  25806. if (player) {
  25807. return player;
  25808. }
  25809. tag = $('#' + nId);
  25810. } else {
  25811. tag = id;
  25812. }
  25813. if (isEl(tag)) {
  25814. const {
  25815. player,
  25816. playerId
  25817. } = tag;
  25818. // Element may have a `player` property referring to an already created
  25819. // player instance. If so, return that.
  25820. if (player || players[playerId]) {
  25821. return player || players[playerId];
  25822. }
  25823. }
  25824. };
  25825. /**
  25826. * Returns an array of all current players.
  25827. *
  25828. * @return {Array}
  25829. * An array of all players. The array will be in the order that
  25830. * `Object.keys` provides, which could potentially vary between
  25831. * JavaScript engines.
  25832. *
  25833. */
  25834. videojs.getAllPlayers = () =>
  25835. // Disposed players leave a key with a `null` value, so we need to make sure
  25836. // we filter those out.
  25837. Object.keys(Player.players).map(k => Player.players[k]).filter(Boolean);
  25838. videojs.players = Player.players;
  25839. videojs.getComponent = Component$1.getComponent;
  25840. /**
  25841. * Register a component so it can referred to by name. Used when adding to other
  25842. * components, either through addChild `component.addChild('myComponent')` or through
  25843. * default children options `{ children: ['myComponent'] }`.
  25844. *
  25845. * > NOTE: You could also just initialize the component before adding.
  25846. * `component.addChild(new MyComponent());`
  25847. *
  25848. * @param {string} name
  25849. * The class name of the component
  25850. *
  25851. * @param {Component} comp
  25852. * The component class
  25853. *
  25854. * @return {Component}
  25855. * The newly registered component
  25856. */
  25857. videojs.registerComponent = (name, comp) => {
  25858. if (Tech.isTech(comp)) {
  25859. log$1.warn(`The ${name} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`);
  25860. }
  25861. Component$1.registerComponent.call(Component$1, name, comp);
  25862. };
  25863. videojs.getTech = Tech.getTech;
  25864. videojs.registerTech = Tech.registerTech;
  25865. videojs.use = use;
  25866. /**
  25867. * An object that can be returned by a middleware to signify
  25868. * that the middleware is being terminated.
  25869. *
  25870. * @type {object}
  25871. * @property {object} middleware.TERMINATOR
  25872. */
  25873. Object.defineProperty(videojs, 'middleware', {
  25874. value: {},
  25875. writeable: false,
  25876. enumerable: true
  25877. });
  25878. Object.defineProperty(videojs.middleware, 'TERMINATOR', {
  25879. value: TERMINATOR,
  25880. writeable: false,
  25881. enumerable: true
  25882. });
  25883. /**
  25884. * A reference to the {@link module:browser|browser utility module} as an object.
  25885. *
  25886. * @type {Object}
  25887. * @see {@link module:browser|browser}
  25888. */
  25889. videojs.browser = browser;
  25890. /**
  25891. * A reference to the {@link module:obj|obj utility module} as an object.
  25892. *
  25893. * @type {Object}
  25894. * @see {@link module:obj|obj}
  25895. */
  25896. videojs.obj = Obj;
  25897. /**
  25898. * Deprecated reference to the {@link module:obj.merge|merge function}
  25899. *
  25900. * @type {Function}
  25901. * @see {@link module:obj.merge|merge}
  25902. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.merge instead.
  25903. */
  25904. videojs.mergeOptions = deprecateForMajor(9, 'videojs.mergeOptions', 'videojs.obj.merge', merge$2);
  25905. /**
  25906. * Deprecated reference to the {@link module:obj.defineLazyProperty|defineLazyProperty function}
  25907. *
  25908. * @type {Function}
  25909. * @see {@link module:obj.defineLazyProperty|defineLazyProperty}
  25910. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.defineLazyProperty instead.
  25911. */
  25912. videojs.defineLazyProperty = deprecateForMajor(9, 'videojs.defineLazyProperty', 'videojs.obj.defineLazyProperty', defineLazyProperty);
  25913. /**
  25914. * Deprecated reference to the {@link module:fn.bind_|fn.bind_ function}
  25915. *
  25916. * @type {Function}
  25917. * @see {@link module:fn.bind_|fn.bind_}
  25918. * @deprecated Deprecated and will be removed in 9.0. Please use native Function.prototype.bind instead.
  25919. */
  25920. videojs.bind = deprecateForMajor(9, 'videojs.bind', 'native Function.prototype.bind', bind_);
  25921. videojs.registerPlugin = Plugin.registerPlugin;
  25922. videojs.deregisterPlugin = Plugin.deregisterPlugin;
  25923. /**
  25924. * Deprecated method to register a plugin with Video.js
  25925. *
  25926. * @deprecated Deprecated and will be removed in 9.0. Use videojs.registerPlugin() instead.
  25927. *
  25928. * @param {string} name
  25929. * The plugin name
  25930. *
  25931. * @param {Plugin|Function} plugin
  25932. * The plugin sub-class or function
  25933. */
  25934. videojs.plugin = (name, plugin) => {
  25935. log$1.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');
  25936. return Plugin.registerPlugin(name, plugin);
  25937. };
  25938. videojs.getPlugins = Plugin.getPlugins;
  25939. videojs.getPlugin = Plugin.getPlugin;
  25940. videojs.getPluginVersion = Plugin.getPluginVersion;
  25941. /**
  25942. * Adding languages so that they're available to all players.
  25943. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`
  25944. *
  25945. * @param {string} code
  25946. * The language code or dictionary property
  25947. *
  25948. * @param {Object} data
  25949. * The data values to be translated
  25950. *
  25951. * @return {Object}
  25952. * The resulting language dictionary object
  25953. */
  25954. videojs.addLanguage = function (code, data) {
  25955. code = ('' + code).toLowerCase();
  25956. videojs.options.languages = merge$2(videojs.options.languages, {
  25957. [code]: data
  25958. });
  25959. return videojs.options.languages[code];
  25960. };
  25961. /**
  25962. * A reference to the {@link module:log|log utility module} as an object.
  25963. *
  25964. * @type {Function}
  25965. * @see {@link module:log|log}
  25966. */
  25967. videojs.log = log$1;
  25968. videojs.createLogger = createLogger;
  25969. /**
  25970. * A reference to the {@link module:time|time utility module} as an object.
  25971. *
  25972. * @type {Object}
  25973. * @see {@link module:time|time}
  25974. */
  25975. videojs.time = Time;
  25976. /**
  25977. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  25978. *
  25979. * @type {Function}
  25980. * @see {@link module:time.createTimeRanges|createTimeRanges}
  25981. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  25982. */
  25983. videojs.createTimeRange = deprecateForMajor(9, 'videojs.createTimeRange', 'videojs.time.createTimeRanges', createTimeRanges$1);
  25984. /**
  25985. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  25986. *
  25987. * @type {Function}
  25988. * @see {@link module:time.createTimeRanges|createTimeRanges}
  25989. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  25990. */
  25991. videojs.createTimeRanges = deprecateForMajor(9, 'videojs.createTimeRanges', 'videojs.time.createTimeRanges', createTimeRanges$1);
  25992. /**
  25993. * Deprecated reference to the {@link module:time.formatTime|formatTime function}
  25994. *
  25995. * @type {Function}
  25996. * @see {@link module:time.formatTime|formatTime}
  25997. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.format instead.
  25998. */
  25999. videojs.formatTime = deprecateForMajor(9, 'videojs.formatTime', 'videojs.time.formatTime', formatTime);
  26000. /**
  26001. * Deprecated reference to the {@link module:time.setFormatTime|setFormatTime function}
  26002. *
  26003. * @type {Function}
  26004. * @see {@link module:time.setFormatTime|setFormatTime}
  26005. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.setFormat instead.
  26006. */
  26007. videojs.setFormatTime = deprecateForMajor(9, 'videojs.setFormatTime', 'videojs.time.setFormatTime', setFormatTime);
  26008. /**
  26009. * Deprecated reference to the {@link module:time.resetFormatTime|resetFormatTime function}
  26010. *
  26011. * @type {Function}
  26012. * @see {@link module:time.resetFormatTime|resetFormatTime}
  26013. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.resetFormat instead.
  26014. */
  26015. videojs.resetFormatTime = deprecateForMajor(9, 'videojs.resetFormatTime', 'videojs.time.resetFormatTime', resetFormatTime);
  26016. /**
  26017. * Deprecated reference to the {@link module:url.parseUrl|Url.parseUrl function}
  26018. *
  26019. * @type {Function}
  26020. * @see {@link module:url.parseUrl|parseUrl}
  26021. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.parseUrl instead.
  26022. */
  26023. videojs.parseUrl = deprecateForMajor(9, 'videojs.parseUrl', 'videojs.url.parseUrl', parseUrl);
  26024. /**
  26025. * Deprecated reference to the {@link module:url.isCrossOrigin|Url.isCrossOrigin function}
  26026. *
  26027. * @type {Function}
  26028. * @see {@link module:url.isCrossOrigin|isCrossOrigin}
  26029. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.isCrossOrigin instead.
  26030. */
  26031. videojs.isCrossOrigin = deprecateForMajor(9, 'videojs.isCrossOrigin', 'videojs.url.isCrossOrigin', isCrossOrigin);
  26032. videojs.EventTarget = EventTarget$2;
  26033. videojs.any = any;
  26034. videojs.on = on;
  26035. videojs.one = one;
  26036. videojs.off = off;
  26037. videojs.trigger = trigger;
  26038. /**
  26039. * A cross-browser XMLHttpRequest wrapper.
  26040. *
  26041. * @function
  26042. * @param {Object} options
  26043. * Settings for the request.
  26044. *
  26045. * @return {XMLHttpRequest|XDomainRequest}
  26046. * The request object.
  26047. *
  26048. * @see https://github.com/Raynos/xhr
  26049. */
  26050. videojs.xhr = lib;
  26051. videojs.TextTrack = TextTrack;
  26052. videojs.AudioTrack = AudioTrack;
  26053. videojs.VideoTrack = VideoTrack;
  26054. ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(k => {
  26055. videojs[k] = function () {
  26056. log$1.warn(`videojs.${k}() is deprecated; use videojs.dom.${k}() instead`);
  26057. return Dom[k].apply(null, arguments);
  26058. };
  26059. });
  26060. videojs.computedStyle = deprecateForMajor(9, 'videojs.computedStyle', 'videojs.dom.computedStyle', computedStyle);
  26061. /**
  26062. * A reference to the {@link module:dom|DOM utility module} as an object.
  26063. *
  26064. * @type {Object}
  26065. * @see {@link module:dom|dom}
  26066. */
  26067. videojs.dom = Dom;
  26068. /**
  26069. * A reference to the {@link module:fn|fn utility module} as an object.
  26070. *
  26071. * @type {Object}
  26072. * @see {@link module:fn|fn}
  26073. */
  26074. videojs.fn = Fn;
  26075. /**
  26076. * A reference to the {@link module:num|num utility module} as an object.
  26077. *
  26078. * @type {Object}
  26079. * @see {@link module:num|num}
  26080. */
  26081. videojs.num = Num;
  26082. /**
  26083. * A reference to the {@link module:str|str utility module} as an object.
  26084. *
  26085. * @type {Object}
  26086. * @see {@link module:str|str}
  26087. */
  26088. videojs.str = Str;
  26089. /**
  26090. * A reference to the {@link module:url|URL utility module} as an object.
  26091. *
  26092. * @type {Object}
  26093. * @see {@link module:url|url}
  26094. */
  26095. videojs.url = Url;
  26096. createCommonjsModule(function (module, exports) {
  26097. /*! @name videojs-contrib-quality-levels @version 3.0.0 @license Apache-2.0 */
  26098. (function (global, factory) {
  26099. module.exports = factory(videojs) ;
  26100. })(commonjsGlobal, function (videojs) {
  26101. function _interopDefaultLegacy(e) {
  26102. return e && typeof e === 'object' && 'default' in e ? e : {
  26103. 'default': e
  26104. };
  26105. }
  26106. var videojs__default = /*#__PURE__*/_interopDefaultLegacy(videojs);
  26107. /**
  26108. * A single QualityLevel.
  26109. *
  26110. * interface QualityLevel {
  26111. * readonly attribute DOMString id;
  26112. * attribute DOMString label;
  26113. * readonly attribute long width;
  26114. * readonly attribute long height;
  26115. * readonly attribute long bitrate;
  26116. * attribute boolean enabled;
  26117. * };
  26118. *
  26119. * @class QualityLevel
  26120. */
  26121. class QualityLevel {
  26122. /**
  26123. * Creates a QualityLevel
  26124. *
  26125. * @param {Representation|Object} representation The representation of the quality level
  26126. * @param {string} representation.id Unique id of the QualityLevel
  26127. * @param {number=} representation.width Resolution width of the QualityLevel
  26128. * @param {number=} representation.height Resolution height of the QualityLevel
  26129. * @param {number} representation.bandwidth Bitrate of the QualityLevel
  26130. * @param {number=} representation.frameRate Frame-rate of the QualityLevel
  26131. * @param {Function} representation.enabled Callback to enable/disable QualityLevel
  26132. */
  26133. constructor(representation) {
  26134. let level = this; // eslint-disable-line
  26135. level.id = representation.id;
  26136. level.label = level.id;
  26137. level.width = representation.width;
  26138. level.height = representation.height;
  26139. level.bitrate = representation.bandwidth;
  26140. level.frameRate = representation.frameRate;
  26141. level.enabled_ = representation.enabled;
  26142. Object.defineProperty(level, 'enabled', {
  26143. /**
  26144. * Get whether the QualityLevel is enabled.
  26145. *
  26146. * @return {boolean} True if the QualityLevel is enabled.
  26147. */
  26148. get() {
  26149. return level.enabled_();
  26150. },
  26151. /**
  26152. * Enable or disable the QualityLevel.
  26153. *
  26154. * @param {boolean} enable true to enable QualityLevel, false to disable.
  26155. */
  26156. set(enable) {
  26157. level.enabled_(enable);
  26158. }
  26159. });
  26160. return level;
  26161. }
  26162. }
  26163. /**
  26164. * A list of QualityLevels.
  26165. *
  26166. * interface QualityLevelList : EventTarget {
  26167. * getter QualityLevel (unsigned long index);
  26168. * readonly attribute unsigned long length;
  26169. * readonly attribute long selectedIndex;
  26170. *
  26171. * void addQualityLevel(QualityLevel qualityLevel)
  26172. * void removeQualityLevel(QualityLevel remove)
  26173. * QualityLevel? getQualityLevelById(DOMString id);
  26174. *
  26175. * attribute EventHandler onchange;
  26176. * attribute EventHandler onaddqualitylevel;
  26177. * attribute EventHandler onremovequalitylevel;
  26178. * };
  26179. *
  26180. * @extends videojs.EventTarget
  26181. * @class QualityLevelList
  26182. */
  26183. class QualityLevelList extends videojs__default['default'].EventTarget {
  26184. constructor() {
  26185. super();
  26186. let list = this; // eslint-disable-line
  26187. list.levels_ = [];
  26188. list.selectedIndex_ = -1;
  26189. /**
  26190. * Get the index of the currently selected QualityLevel.
  26191. *
  26192. * @returns {number} The index of the selected QualityLevel. -1 if none selected.
  26193. * @readonly
  26194. */
  26195. Object.defineProperty(list, 'selectedIndex', {
  26196. get() {
  26197. return list.selectedIndex_;
  26198. }
  26199. });
  26200. /**
  26201. * Get the length of the list of QualityLevels.
  26202. *
  26203. * @returns {number} The length of the list.
  26204. * @readonly
  26205. */
  26206. Object.defineProperty(list, 'length', {
  26207. get() {
  26208. return list.levels_.length;
  26209. }
  26210. });
  26211. return list;
  26212. }
  26213. /**
  26214. * Adds a quality level to the list.
  26215. *
  26216. * @param {Representation|Object} representation The representation of the quality level
  26217. * @param {string} representation.id Unique id of the QualityLevel
  26218. * @param {number=} representation.width Resolution width of the QualityLevel
  26219. * @param {number=} representation.height Resolution height of the QualityLevel
  26220. * @param {number} representation.bandwidth Bitrate of the QualityLevel
  26221. * @param {number=} representation.frameRate Frame-rate of the QualityLevel
  26222. * @param {Function} representation.enabled Callback to enable/disable QualityLevel
  26223. * @return {QualityLevel} the QualityLevel added to the list
  26224. * @method addQualityLevel
  26225. */
  26226. addQualityLevel(representation) {
  26227. let qualityLevel = this.getQualityLevelById(representation.id); // Do not add duplicate quality levels
  26228. if (qualityLevel) {
  26229. return qualityLevel;
  26230. }
  26231. const index = this.levels_.length;
  26232. qualityLevel = new QualityLevel(representation);
  26233. if (!('' + index in this)) {
  26234. Object.defineProperty(this, index, {
  26235. get() {
  26236. return this.levels_[index];
  26237. }
  26238. });
  26239. }
  26240. this.levels_.push(qualityLevel);
  26241. this.trigger({
  26242. qualityLevel,
  26243. type: 'addqualitylevel'
  26244. });
  26245. return qualityLevel;
  26246. }
  26247. /**
  26248. * Removes a quality level from the list.
  26249. *
  26250. * @param {QualityLevel} remove QualityLevel to remove to the list.
  26251. * @return {QualityLevel|null} the QualityLevel removed or null if nothing removed
  26252. * @method removeQualityLevel
  26253. */
  26254. removeQualityLevel(qualityLevel) {
  26255. let removed = null;
  26256. for (let i = 0, l = this.length; i < l; i++) {
  26257. if (this[i] === qualityLevel) {
  26258. removed = this.levels_.splice(i, 1)[0];
  26259. if (this.selectedIndex_ === i) {
  26260. this.selectedIndex_ = -1;
  26261. } else if (this.selectedIndex_ > i) {
  26262. this.selectedIndex_--;
  26263. }
  26264. break;
  26265. }
  26266. }
  26267. if (removed) {
  26268. this.trigger({
  26269. qualityLevel,
  26270. type: 'removequalitylevel'
  26271. });
  26272. }
  26273. return removed;
  26274. }
  26275. /**
  26276. * Searches for a QualityLevel with the given id.
  26277. *
  26278. * @param {string} id The id of the QualityLevel to find.
  26279. * @return {QualityLevel|null} The QualityLevel with id, or null if not found.
  26280. * @method getQualityLevelById
  26281. */
  26282. getQualityLevelById(id) {
  26283. for (let i = 0, l = this.length; i < l; i++) {
  26284. const level = this[i];
  26285. if (level.id === id) {
  26286. return level;
  26287. }
  26288. }
  26289. return null;
  26290. }
  26291. /**
  26292. * Resets the list of QualityLevels to empty
  26293. *
  26294. * @method dispose
  26295. */
  26296. dispose() {
  26297. this.selectedIndex_ = -1;
  26298. this.levels_.length = 0;
  26299. }
  26300. }
  26301. /**
  26302. * change - The selected QualityLevel has changed.
  26303. * addqualitylevel - A QualityLevel has been added to the QualityLevelList.
  26304. * removequalitylevel - A QualityLevel has been removed from the QualityLevelList.
  26305. */
  26306. QualityLevelList.prototype.allowedEvents_ = {
  26307. change: 'change',
  26308. addqualitylevel: 'addqualitylevel',
  26309. removequalitylevel: 'removequalitylevel'
  26310. }; // emulate attribute EventHandler support to allow for feature detection
  26311. for (const event in QualityLevelList.prototype.allowedEvents_) {
  26312. QualityLevelList.prototype['on' + event] = null;
  26313. }
  26314. var version = "3.0.0";
  26315. const registerPlugin = videojs__default['default'].registerPlugin || videojs__default['default'].plugin;
  26316. /**
  26317. * Initialization function for the qualityLevels plugin. Sets up the QualityLevelList and
  26318. * event handlers.
  26319. *
  26320. * @param {Player} player Player object.
  26321. * @param {Object} options Plugin options object.
  26322. * @function initPlugin
  26323. */
  26324. const initPlugin = function (player, options) {
  26325. const originalPluginFn = player.qualityLevels;
  26326. const qualityLevelList = new QualityLevelList();
  26327. const disposeHandler = function () {
  26328. qualityLevelList.dispose();
  26329. player.qualityLevels = originalPluginFn;
  26330. player.off('dispose', disposeHandler);
  26331. };
  26332. player.on('dispose', disposeHandler);
  26333. player.qualityLevels = () => qualityLevelList;
  26334. player.qualityLevels.VERSION = version;
  26335. return qualityLevelList;
  26336. };
  26337. /**
  26338. * A video.js plugin.
  26339. *
  26340. * In the plugin function, the value of `this` is a video.js `Player`
  26341. * instance. You cannot rely on the player being in a "ready" state here,
  26342. * depending on how the plugin is invoked. This may or may not be important
  26343. * to you; if not, remove the wait for "ready"!
  26344. *
  26345. * @param {Object} options Plugin options object
  26346. * @function qualityLevels
  26347. */
  26348. const qualityLevels = function (options) {
  26349. return initPlugin(this, videojs__default['default'].mergeOptions({}, options));
  26350. }; // Register the plugin with video.js.
  26351. registerPlugin('qualityLevels', qualityLevels); // Include the version number.
  26352. qualityLevels.VERSION = version;
  26353. return qualityLevels;
  26354. });
  26355. });
  26356. var urlToolkit = createCommonjsModule(function (module, exports) {
  26357. // see https://tools.ietf.org/html/rfc1808
  26358. (function (root) {
  26359. var URL_REGEX = /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  26360. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  26361. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  26362. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  26363. var URLToolkit = {
  26364. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  26365. // E.g
  26366. // With opts.alwaysNormalize = false (default, spec compliant)
  26367. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  26368. // With opts.alwaysNormalize = true (not spec compliant)
  26369. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  26370. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  26371. opts = opts || {};
  26372. // remove any remaining space and CRLF
  26373. baseURL = baseURL.trim();
  26374. relativeURL = relativeURL.trim();
  26375. if (!relativeURL) {
  26376. // 2a) If the embedded URL is entirely empty, it inherits the
  26377. // entire base URL (i.e., is set equal to the base URL)
  26378. // and we are done.
  26379. if (!opts.alwaysNormalize) {
  26380. return baseURL;
  26381. }
  26382. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  26383. if (!basePartsForNormalise) {
  26384. throw new Error('Error trying to parse base URL.');
  26385. }
  26386. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  26387. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  26388. }
  26389. var relativeParts = URLToolkit.parseURL(relativeURL);
  26390. if (!relativeParts) {
  26391. throw new Error('Error trying to parse relative URL.');
  26392. }
  26393. if (relativeParts.scheme) {
  26394. // 2b) If the embedded URL starts with a scheme name, it is
  26395. // interpreted as an absolute URL and we are done.
  26396. if (!opts.alwaysNormalize) {
  26397. return relativeURL;
  26398. }
  26399. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  26400. return URLToolkit.buildURLFromParts(relativeParts);
  26401. }
  26402. var baseParts = URLToolkit.parseURL(baseURL);
  26403. if (!baseParts) {
  26404. throw new Error('Error trying to parse base URL.');
  26405. }
  26406. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  26407. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  26408. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  26409. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  26410. baseParts.netLoc = pathParts[1];
  26411. baseParts.path = pathParts[2];
  26412. }
  26413. if (baseParts.netLoc && !baseParts.path) {
  26414. baseParts.path = '/';
  26415. }
  26416. var builtParts = {
  26417. // 2c) Otherwise, the embedded URL inherits the scheme of
  26418. // the base URL.
  26419. scheme: baseParts.scheme,
  26420. netLoc: relativeParts.netLoc,
  26421. path: null,
  26422. params: relativeParts.params,
  26423. query: relativeParts.query,
  26424. fragment: relativeParts.fragment
  26425. };
  26426. if (!relativeParts.netLoc) {
  26427. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  26428. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  26429. // (if any) of the base URL.
  26430. builtParts.netLoc = baseParts.netLoc;
  26431. // 4) If the embedded URL path is preceded by a slash "/", the
  26432. // path is not relative and we skip to Step 7.
  26433. if (relativeParts.path[0] !== '/') {
  26434. if (!relativeParts.path) {
  26435. // 5) If the embedded URL path is empty (and not preceded by a
  26436. // slash), then the embedded URL inherits the base URL path
  26437. builtParts.path = baseParts.path;
  26438. // 5a) if the embedded URL's <params> is non-empty, we skip to
  26439. // step 7; otherwise, it inherits the <params> of the base
  26440. // URL (if any) and
  26441. if (!relativeParts.params) {
  26442. builtParts.params = baseParts.params;
  26443. // 5b) if the embedded URL's <query> is non-empty, we skip to
  26444. // step 7; otherwise, it inherits the <query> of the base
  26445. // URL (if any) and we skip to step 7.
  26446. if (!relativeParts.query) {
  26447. builtParts.query = baseParts.query;
  26448. }
  26449. }
  26450. } else {
  26451. // 6) The last segment of the base URL's path (anything
  26452. // following the rightmost slash "/", or the entire path if no
  26453. // slash is present) is removed and the embedded URL's path is
  26454. // appended in its place.
  26455. var baseURLPath = baseParts.path;
  26456. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
  26457. builtParts.path = URLToolkit.normalizePath(newPath);
  26458. }
  26459. }
  26460. }
  26461. if (builtParts.path === null) {
  26462. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  26463. }
  26464. return URLToolkit.buildURLFromParts(builtParts);
  26465. },
  26466. parseURL: function (url) {
  26467. var parts = URL_REGEX.exec(url);
  26468. if (!parts) {
  26469. return null;
  26470. }
  26471. return {
  26472. scheme: parts[1] || '',
  26473. netLoc: parts[2] || '',
  26474. path: parts[3] || '',
  26475. params: parts[4] || '',
  26476. query: parts[5] || '',
  26477. fragment: parts[6] || ''
  26478. };
  26479. },
  26480. normalizePath: function (path) {
  26481. // The following operations are
  26482. // then applied, in order, to the new path:
  26483. // 6a) All occurrences of "./", where "." is a complete path
  26484. // segment, are removed.
  26485. // 6b) If the path ends with "." as a complete path segment,
  26486. // that "." is removed.
  26487. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  26488. // 6c) All occurrences of "<segment>/../", where <segment> is a
  26489. // complete path segment not equal to "..", are removed.
  26490. // Removal of these path segments is performed iteratively,
  26491. // removing the leftmost matching pattern on each iteration,
  26492. // until no matching pattern remains.
  26493. // 6d) If the path ends with "<segment>/..", where <segment> is a
  26494. // complete path segment not equal to "..", that
  26495. // "<segment>/.." is removed.
  26496. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {}
  26497. return path.split('').reverse().join('');
  26498. },
  26499. buildURLFromParts: function (parts) {
  26500. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  26501. }
  26502. };
  26503. module.exports = URLToolkit;
  26504. })();
  26505. });
  26506. var DEFAULT_LOCATION$1 = 'http://example.com';
  26507. var resolveUrl$2 = function resolveUrl(baseUrl, relativeUrl) {
  26508. // return early if we don't need to resolve
  26509. if (/^[a-z]+:/i.test(relativeUrl)) {
  26510. return relativeUrl;
  26511. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  26512. if (/^data:/.test(baseUrl)) {
  26513. baseUrl = window.location && window.location.href || '';
  26514. } // IE11 supports URL but not the URL constructor
  26515. // feature detect the behavior we want
  26516. var nativeURL = typeof window.URL === 'function';
  26517. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  26518. // and if baseUrl isn't an absolute url
  26519. var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  26520. if (nativeURL) {
  26521. baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION$1);
  26522. } else if (!/\/\//i.test(baseUrl)) {
  26523. baseUrl = urlToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
  26524. }
  26525. if (nativeURL) {
  26526. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  26527. // and if we're location-less, remove the location
  26528. // otherwise, return the url unmodified
  26529. if (removeLocation) {
  26530. return newUrl.href.slice(DEFAULT_LOCATION$1.length);
  26531. } else if (protocolLess) {
  26532. return newUrl.href.slice(newUrl.protocol.length);
  26533. }
  26534. return newUrl.href;
  26535. }
  26536. return urlToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
  26537. };
  26538. /**
  26539. * @file stream.js
  26540. */
  26541. /**
  26542. * A lightweight readable stream implemention that handles event dispatching.
  26543. *
  26544. * @class Stream
  26545. */
  26546. var Stream = /*#__PURE__*/function () {
  26547. function Stream() {
  26548. this.listeners = {};
  26549. }
  26550. /**
  26551. * Add a listener for a specified event type.
  26552. *
  26553. * @param {string} type the event name
  26554. * @param {Function} listener the callback to be invoked when an event of
  26555. * the specified type occurs
  26556. */
  26557. var _proto = Stream.prototype;
  26558. _proto.on = function on(type, listener) {
  26559. if (!this.listeners[type]) {
  26560. this.listeners[type] = [];
  26561. }
  26562. this.listeners[type].push(listener);
  26563. }
  26564. /**
  26565. * Remove a listener for a specified event type.
  26566. *
  26567. * @param {string} type the event name
  26568. * @param {Function} listener a function previously registered for this
  26569. * type of event through `on`
  26570. * @return {boolean} if we could turn it off or not
  26571. */;
  26572. _proto.off = function off(type, listener) {
  26573. if (!this.listeners[type]) {
  26574. return false;
  26575. }
  26576. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  26577. // In Video.js we slice listener functions
  26578. // on trigger so that it does not mess up the order
  26579. // while we loop through.
  26580. //
  26581. // Here we slice on off so that the loop in trigger
  26582. // can continue using it's old reference to loop without
  26583. // messing up the order.
  26584. this.listeners[type] = this.listeners[type].slice(0);
  26585. this.listeners[type].splice(index, 1);
  26586. return index > -1;
  26587. }
  26588. /**
  26589. * Trigger an event of the specified type on this stream. Any additional
  26590. * arguments to this function are passed as parameters to event listeners.
  26591. *
  26592. * @param {string} type the event name
  26593. */;
  26594. _proto.trigger = function trigger(type) {
  26595. var callbacks = this.listeners[type];
  26596. if (!callbacks) {
  26597. return;
  26598. } // Slicing the arguments on every invocation of this method
  26599. // can add a significant amount of overhead. Avoid the
  26600. // intermediate object creation for the common case of a
  26601. // single callback argument
  26602. if (arguments.length === 2) {
  26603. var length = callbacks.length;
  26604. for (var i = 0; i < length; ++i) {
  26605. callbacks[i].call(this, arguments[1]);
  26606. }
  26607. } else {
  26608. var args = Array.prototype.slice.call(arguments, 1);
  26609. var _length = callbacks.length;
  26610. for (var _i = 0; _i < _length; ++_i) {
  26611. callbacks[_i].apply(this, args);
  26612. }
  26613. }
  26614. }
  26615. /**
  26616. * Destroys the stream and cleans up.
  26617. */;
  26618. _proto.dispose = function dispose() {
  26619. this.listeners = {};
  26620. }
  26621. /**
  26622. * Forwards all `data` events on this stream to the destination stream. The
  26623. * destination stream should provide a method `push` to receive the data
  26624. * events as they arrive.
  26625. *
  26626. * @param {Stream} destination the stream that will receive all `data` events
  26627. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  26628. */;
  26629. _proto.pipe = function pipe(destination) {
  26630. this.on('data', function (data) {
  26631. destination.push(data);
  26632. });
  26633. };
  26634. return Stream;
  26635. }();
  26636. var atob$1 = function atob(s) {
  26637. return window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');
  26638. };
  26639. function decodeB64ToUint8Array$1(b64Text) {
  26640. var decodedString = atob$1(b64Text);
  26641. var array = new Uint8Array(decodedString.length);
  26642. for (var i = 0; i < decodedString.length; i++) {
  26643. array[i] = decodedString.charCodeAt(i);
  26644. }
  26645. return array;
  26646. }
  26647. /*! @name m3u8-parser @version 6.0.0 @license Apache-2.0 */
  26648. /**
  26649. * @file m3u8/line-stream.js
  26650. */
  26651. /**
  26652. * A stream that buffers string input and generates a `data` event for each
  26653. * line.
  26654. *
  26655. * @class LineStream
  26656. * @extends Stream
  26657. */
  26658. class LineStream extends Stream {
  26659. constructor() {
  26660. super();
  26661. this.buffer = '';
  26662. }
  26663. /**
  26664. * Add new data to be parsed.
  26665. *
  26666. * @param {string} data the text to process
  26667. */
  26668. push(data) {
  26669. let nextNewline;
  26670. this.buffer += data;
  26671. nextNewline = this.buffer.indexOf('\n');
  26672. for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
  26673. this.trigger('data', this.buffer.substring(0, nextNewline));
  26674. this.buffer = this.buffer.substring(nextNewline + 1);
  26675. }
  26676. }
  26677. }
  26678. const TAB = String.fromCharCode(0x09);
  26679. const parseByterange = function (byterangeString) {
  26680. // optionally match and capture 0+ digits before `@`
  26681. // optionally match and capture 0+ digits after `@`
  26682. const match = /([0-9.]*)?@?([0-9.]*)?/.exec(byterangeString || '');
  26683. const result = {};
  26684. if (match[1]) {
  26685. result.length = parseInt(match[1], 10);
  26686. }
  26687. if (match[2]) {
  26688. result.offset = parseInt(match[2], 10);
  26689. }
  26690. return result;
  26691. };
  26692. /**
  26693. * "forgiving" attribute list psuedo-grammar:
  26694. * attributes -> keyvalue (',' keyvalue)*
  26695. * keyvalue -> key '=' value
  26696. * key -> [^=]*
  26697. * value -> '"' [^"]* '"' | [^,]*
  26698. */
  26699. const attributeSeparator = function () {
  26700. const key = '[^=]*';
  26701. const value = '"[^"]*"|[^,]*';
  26702. const keyvalue = '(?:' + key + ')=(?:' + value + ')';
  26703. return new RegExp('(?:^|,)(' + keyvalue + ')');
  26704. };
  26705. /**
  26706. * Parse attributes from a line given the separator
  26707. *
  26708. * @param {string} attributes the attribute line to parse
  26709. */
  26710. const parseAttributes$1 = function (attributes) {
  26711. const result = {};
  26712. if (!attributes) {
  26713. return result;
  26714. } // split the string using attributes as the separator
  26715. const attrs = attributes.split(attributeSeparator());
  26716. let i = attrs.length;
  26717. let attr;
  26718. while (i--) {
  26719. // filter out unmatched portions of the string
  26720. if (attrs[i] === '') {
  26721. continue;
  26722. } // split the key and value
  26723. attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1); // trim whitespace and remove optional quotes around the value
  26724. attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
  26725. attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
  26726. attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
  26727. result[attr[0]] = attr[1];
  26728. }
  26729. return result;
  26730. };
  26731. /**
  26732. * A line-level M3U8 parser event stream. It expects to receive input one
  26733. * line at a time and performs a context-free parse of its contents. A stream
  26734. * interpretation of a manifest can be useful if the manifest is expected to
  26735. * be too large to fit comfortably into memory or the entirety of the input
  26736. * is not immediately available. Otherwise, it's probably much easier to work
  26737. * with a regular `Parser` object.
  26738. *
  26739. * Produces `data` events with an object that captures the parser's
  26740. * interpretation of the input. That object has a property `tag` that is one
  26741. * of `uri`, `comment`, or `tag`. URIs only have a single additional
  26742. * property, `line`, which captures the entirety of the input without
  26743. * interpretation. Comments similarly have a single additional property
  26744. * `text` which is the input without the leading `#`.
  26745. *
  26746. * Tags always have a property `tagType` which is the lower-cased version of
  26747. * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
  26748. * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
  26749. * tags are given the tag type `unknown` and a single additional property
  26750. * `data` with the remainder of the input.
  26751. *
  26752. * @class ParseStream
  26753. * @extends Stream
  26754. */
  26755. class ParseStream extends Stream {
  26756. constructor() {
  26757. super();
  26758. this.customParsers = [];
  26759. this.tagMappers = [];
  26760. }
  26761. /**
  26762. * Parses an additional line of input.
  26763. *
  26764. * @param {string} line a single line of an M3U8 file to parse
  26765. */
  26766. push(line) {
  26767. let match;
  26768. let event; // strip whitespace
  26769. line = line.trim();
  26770. if (line.length === 0) {
  26771. // ignore empty lines
  26772. return;
  26773. } // URIs
  26774. if (line[0] !== '#') {
  26775. this.trigger('data', {
  26776. type: 'uri',
  26777. uri: line
  26778. });
  26779. return;
  26780. } // map tags
  26781. const newLines = this.tagMappers.reduce((acc, mapper) => {
  26782. const mappedLine = mapper(line); // skip if unchanged
  26783. if (mappedLine === line) {
  26784. return acc;
  26785. }
  26786. return acc.concat([mappedLine]);
  26787. }, [line]);
  26788. newLines.forEach(newLine => {
  26789. for (let i = 0; i < this.customParsers.length; i++) {
  26790. if (this.customParsers[i].call(this, newLine)) {
  26791. return;
  26792. }
  26793. } // Comments
  26794. if (newLine.indexOf('#EXT') !== 0) {
  26795. this.trigger('data', {
  26796. type: 'comment',
  26797. text: newLine.slice(1)
  26798. });
  26799. return;
  26800. } // strip off any carriage returns here so the regex matching
  26801. // doesn't have to account for them.
  26802. newLine = newLine.replace('\r', ''); // Tags
  26803. match = /^#EXTM3U/.exec(newLine);
  26804. if (match) {
  26805. this.trigger('data', {
  26806. type: 'tag',
  26807. tagType: 'm3u'
  26808. });
  26809. return;
  26810. }
  26811. match = /^#EXTINF:([0-9\.]*)?,?(.*)?$/.exec(newLine);
  26812. if (match) {
  26813. event = {
  26814. type: 'tag',
  26815. tagType: 'inf'
  26816. };
  26817. if (match[1]) {
  26818. event.duration = parseFloat(match[1]);
  26819. }
  26820. if (match[2]) {
  26821. event.title = match[2];
  26822. }
  26823. this.trigger('data', event);
  26824. return;
  26825. }
  26826. match = /^#EXT-X-TARGETDURATION:([0-9.]*)?/.exec(newLine);
  26827. if (match) {
  26828. event = {
  26829. type: 'tag',
  26830. tagType: 'targetduration'
  26831. };
  26832. if (match[1]) {
  26833. event.duration = parseInt(match[1], 10);
  26834. }
  26835. this.trigger('data', event);
  26836. return;
  26837. }
  26838. match = /^#EXT-X-VERSION:([0-9.]*)?/.exec(newLine);
  26839. if (match) {
  26840. event = {
  26841. type: 'tag',
  26842. tagType: 'version'
  26843. };
  26844. if (match[1]) {
  26845. event.version = parseInt(match[1], 10);
  26846. }
  26847. this.trigger('data', event);
  26848. return;
  26849. }
  26850. match = /^#EXT-X-MEDIA-SEQUENCE:(\-?[0-9.]*)?/.exec(newLine);
  26851. if (match) {
  26852. event = {
  26853. type: 'tag',
  26854. tagType: 'media-sequence'
  26855. };
  26856. if (match[1]) {
  26857. event.number = parseInt(match[1], 10);
  26858. }
  26859. this.trigger('data', event);
  26860. return;
  26861. }
  26862. match = /^#EXT-X-DISCONTINUITY-SEQUENCE:(\-?[0-9.]*)?/.exec(newLine);
  26863. if (match) {
  26864. event = {
  26865. type: 'tag',
  26866. tagType: 'discontinuity-sequence'
  26867. };
  26868. if (match[1]) {
  26869. event.number = parseInt(match[1], 10);
  26870. }
  26871. this.trigger('data', event);
  26872. return;
  26873. }
  26874. match = /^#EXT-X-PLAYLIST-TYPE:(.*)?$/.exec(newLine);
  26875. if (match) {
  26876. event = {
  26877. type: 'tag',
  26878. tagType: 'playlist-type'
  26879. };
  26880. if (match[1]) {
  26881. event.playlistType = match[1];
  26882. }
  26883. this.trigger('data', event);
  26884. return;
  26885. }
  26886. match = /^#EXT-X-BYTERANGE:(.*)?$/.exec(newLine);
  26887. if (match) {
  26888. event = _extends$1(parseByterange(match[1]), {
  26889. type: 'tag',
  26890. tagType: 'byterange'
  26891. });
  26892. this.trigger('data', event);
  26893. return;
  26894. }
  26895. match = /^#EXT-X-ALLOW-CACHE:(YES|NO)?/.exec(newLine);
  26896. if (match) {
  26897. event = {
  26898. type: 'tag',
  26899. tagType: 'allow-cache'
  26900. };
  26901. if (match[1]) {
  26902. event.allowed = !/NO/.test(match[1]);
  26903. }
  26904. this.trigger('data', event);
  26905. return;
  26906. }
  26907. match = /^#EXT-X-MAP:(.*)$/.exec(newLine);
  26908. if (match) {
  26909. event = {
  26910. type: 'tag',
  26911. tagType: 'map'
  26912. };
  26913. if (match[1]) {
  26914. const attributes = parseAttributes$1(match[1]);
  26915. if (attributes.URI) {
  26916. event.uri = attributes.URI;
  26917. }
  26918. if (attributes.BYTERANGE) {
  26919. event.byterange = parseByterange(attributes.BYTERANGE);
  26920. }
  26921. }
  26922. this.trigger('data', event);
  26923. return;
  26924. }
  26925. match = /^#EXT-X-STREAM-INF:(.*)$/.exec(newLine);
  26926. if (match) {
  26927. event = {
  26928. type: 'tag',
  26929. tagType: 'stream-inf'
  26930. };
  26931. if (match[1]) {
  26932. event.attributes = parseAttributes$1(match[1]);
  26933. if (event.attributes.RESOLUTION) {
  26934. const split = event.attributes.RESOLUTION.split('x');
  26935. const resolution = {};
  26936. if (split[0]) {
  26937. resolution.width = parseInt(split[0], 10);
  26938. }
  26939. if (split[1]) {
  26940. resolution.height = parseInt(split[1], 10);
  26941. }
  26942. event.attributes.RESOLUTION = resolution;
  26943. }
  26944. if (event.attributes.BANDWIDTH) {
  26945. event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
  26946. }
  26947. if (event.attributes['FRAME-RATE']) {
  26948. event.attributes['FRAME-RATE'] = parseFloat(event.attributes['FRAME-RATE']);
  26949. }
  26950. if (event.attributes['PROGRAM-ID']) {
  26951. event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
  26952. }
  26953. }
  26954. this.trigger('data', event);
  26955. return;
  26956. }
  26957. match = /^#EXT-X-MEDIA:(.*)$/.exec(newLine);
  26958. if (match) {
  26959. event = {
  26960. type: 'tag',
  26961. tagType: 'media'
  26962. };
  26963. if (match[1]) {
  26964. event.attributes = parseAttributes$1(match[1]);
  26965. }
  26966. this.trigger('data', event);
  26967. return;
  26968. }
  26969. match = /^#EXT-X-ENDLIST/.exec(newLine);
  26970. if (match) {
  26971. this.trigger('data', {
  26972. type: 'tag',
  26973. tagType: 'endlist'
  26974. });
  26975. return;
  26976. }
  26977. match = /^#EXT-X-DISCONTINUITY/.exec(newLine);
  26978. if (match) {
  26979. this.trigger('data', {
  26980. type: 'tag',
  26981. tagType: 'discontinuity'
  26982. });
  26983. return;
  26984. }
  26985. match = /^#EXT-X-PROGRAM-DATE-TIME:(.*)$/.exec(newLine);
  26986. if (match) {
  26987. event = {
  26988. type: 'tag',
  26989. tagType: 'program-date-time'
  26990. };
  26991. if (match[1]) {
  26992. event.dateTimeString = match[1];
  26993. event.dateTimeObject = new Date(match[1]);
  26994. }
  26995. this.trigger('data', event);
  26996. return;
  26997. }
  26998. match = /^#EXT-X-KEY:(.*)$/.exec(newLine);
  26999. if (match) {
  27000. event = {
  27001. type: 'tag',
  27002. tagType: 'key'
  27003. };
  27004. if (match[1]) {
  27005. event.attributes = parseAttributes$1(match[1]); // parse the IV string into a Uint32Array
  27006. if (event.attributes.IV) {
  27007. if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
  27008. event.attributes.IV = event.attributes.IV.substring(2);
  27009. }
  27010. event.attributes.IV = event.attributes.IV.match(/.{8}/g);
  27011. event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
  27012. event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
  27013. event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
  27014. event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
  27015. event.attributes.IV = new Uint32Array(event.attributes.IV);
  27016. }
  27017. }
  27018. this.trigger('data', event);
  27019. return;
  27020. }
  27021. match = /^#EXT-X-START:(.*)$/.exec(newLine);
  27022. if (match) {
  27023. event = {
  27024. type: 'tag',
  27025. tagType: 'start'
  27026. };
  27027. if (match[1]) {
  27028. event.attributes = parseAttributes$1(match[1]);
  27029. event.attributes['TIME-OFFSET'] = parseFloat(event.attributes['TIME-OFFSET']);
  27030. event.attributes.PRECISE = /YES/.test(event.attributes.PRECISE);
  27031. }
  27032. this.trigger('data', event);
  27033. return;
  27034. }
  27035. match = /^#EXT-X-CUE-OUT-CONT:(.*)?$/.exec(newLine);
  27036. if (match) {
  27037. event = {
  27038. type: 'tag',
  27039. tagType: 'cue-out-cont'
  27040. };
  27041. if (match[1]) {
  27042. event.data = match[1];
  27043. } else {
  27044. event.data = '';
  27045. }
  27046. this.trigger('data', event);
  27047. return;
  27048. }
  27049. match = /^#EXT-X-CUE-OUT:(.*)?$/.exec(newLine);
  27050. if (match) {
  27051. event = {
  27052. type: 'tag',
  27053. tagType: 'cue-out'
  27054. };
  27055. if (match[1]) {
  27056. event.data = match[1];
  27057. } else {
  27058. event.data = '';
  27059. }
  27060. this.trigger('data', event);
  27061. return;
  27062. }
  27063. match = /^#EXT-X-CUE-IN:(.*)?$/.exec(newLine);
  27064. if (match) {
  27065. event = {
  27066. type: 'tag',
  27067. tagType: 'cue-in'
  27068. };
  27069. if (match[1]) {
  27070. event.data = match[1];
  27071. } else {
  27072. event.data = '';
  27073. }
  27074. this.trigger('data', event);
  27075. return;
  27076. }
  27077. match = /^#EXT-X-SKIP:(.*)$/.exec(newLine);
  27078. if (match && match[1]) {
  27079. event = {
  27080. type: 'tag',
  27081. tagType: 'skip'
  27082. };
  27083. event.attributes = parseAttributes$1(match[1]);
  27084. if (event.attributes.hasOwnProperty('SKIPPED-SEGMENTS')) {
  27085. event.attributes['SKIPPED-SEGMENTS'] = parseInt(event.attributes['SKIPPED-SEGMENTS'], 10);
  27086. }
  27087. if (event.attributes.hasOwnProperty('RECENTLY-REMOVED-DATERANGES')) {
  27088. event.attributes['RECENTLY-REMOVED-DATERANGES'] = event.attributes['RECENTLY-REMOVED-DATERANGES'].split(TAB);
  27089. }
  27090. this.trigger('data', event);
  27091. return;
  27092. }
  27093. match = /^#EXT-X-PART:(.*)$/.exec(newLine);
  27094. if (match && match[1]) {
  27095. event = {
  27096. type: 'tag',
  27097. tagType: 'part'
  27098. };
  27099. event.attributes = parseAttributes$1(match[1]);
  27100. ['DURATION'].forEach(function (key) {
  27101. if (event.attributes.hasOwnProperty(key)) {
  27102. event.attributes[key] = parseFloat(event.attributes[key]);
  27103. }
  27104. });
  27105. ['INDEPENDENT', 'GAP'].forEach(function (key) {
  27106. if (event.attributes.hasOwnProperty(key)) {
  27107. event.attributes[key] = /YES/.test(event.attributes[key]);
  27108. }
  27109. });
  27110. if (event.attributes.hasOwnProperty('BYTERANGE')) {
  27111. event.attributes.byterange = parseByterange(event.attributes.BYTERANGE);
  27112. }
  27113. this.trigger('data', event);
  27114. return;
  27115. }
  27116. match = /^#EXT-X-SERVER-CONTROL:(.*)$/.exec(newLine);
  27117. if (match && match[1]) {
  27118. event = {
  27119. type: 'tag',
  27120. tagType: 'server-control'
  27121. };
  27122. event.attributes = parseAttributes$1(match[1]);
  27123. ['CAN-SKIP-UNTIL', 'PART-HOLD-BACK', 'HOLD-BACK'].forEach(function (key) {
  27124. if (event.attributes.hasOwnProperty(key)) {
  27125. event.attributes[key] = parseFloat(event.attributes[key]);
  27126. }
  27127. });
  27128. ['CAN-SKIP-DATERANGES', 'CAN-BLOCK-RELOAD'].forEach(function (key) {
  27129. if (event.attributes.hasOwnProperty(key)) {
  27130. event.attributes[key] = /YES/.test(event.attributes[key]);
  27131. }
  27132. });
  27133. this.trigger('data', event);
  27134. return;
  27135. }
  27136. match = /^#EXT-X-PART-INF:(.*)$/.exec(newLine);
  27137. if (match && match[1]) {
  27138. event = {
  27139. type: 'tag',
  27140. tagType: 'part-inf'
  27141. };
  27142. event.attributes = parseAttributes$1(match[1]);
  27143. ['PART-TARGET'].forEach(function (key) {
  27144. if (event.attributes.hasOwnProperty(key)) {
  27145. event.attributes[key] = parseFloat(event.attributes[key]);
  27146. }
  27147. });
  27148. this.trigger('data', event);
  27149. return;
  27150. }
  27151. match = /^#EXT-X-PRELOAD-HINT:(.*)$/.exec(newLine);
  27152. if (match && match[1]) {
  27153. event = {
  27154. type: 'tag',
  27155. tagType: 'preload-hint'
  27156. };
  27157. event.attributes = parseAttributes$1(match[1]);
  27158. ['BYTERANGE-START', 'BYTERANGE-LENGTH'].forEach(function (key) {
  27159. if (event.attributes.hasOwnProperty(key)) {
  27160. event.attributes[key] = parseInt(event.attributes[key], 10);
  27161. const subkey = key === 'BYTERANGE-LENGTH' ? 'length' : 'offset';
  27162. event.attributes.byterange = event.attributes.byterange || {};
  27163. event.attributes.byterange[subkey] = event.attributes[key]; // only keep the parsed byterange object.
  27164. delete event.attributes[key];
  27165. }
  27166. });
  27167. this.trigger('data', event);
  27168. return;
  27169. }
  27170. match = /^#EXT-X-RENDITION-REPORT:(.*)$/.exec(newLine);
  27171. if (match && match[1]) {
  27172. event = {
  27173. type: 'tag',
  27174. tagType: 'rendition-report'
  27175. };
  27176. event.attributes = parseAttributes$1(match[1]);
  27177. ['LAST-MSN', 'LAST-PART'].forEach(function (key) {
  27178. if (event.attributes.hasOwnProperty(key)) {
  27179. event.attributes[key] = parseInt(event.attributes[key], 10);
  27180. }
  27181. });
  27182. this.trigger('data', event);
  27183. return;
  27184. } // unknown tag type
  27185. this.trigger('data', {
  27186. type: 'tag',
  27187. data: newLine.slice(4)
  27188. });
  27189. });
  27190. }
  27191. /**
  27192. * Add a parser for custom headers
  27193. *
  27194. * @param {Object} options a map of options for the added parser
  27195. * @param {RegExp} options.expression a regular expression to match the custom header
  27196. * @param {string} options.customType the custom type to register to the output
  27197. * @param {Function} [options.dataParser] function to parse the line into an object
  27198. * @param {boolean} [options.segment] should tag data be attached to the segment object
  27199. */
  27200. addParser({
  27201. expression,
  27202. customType,
  27203. dataParser,
  27204. segment
  27205. }) {
  27206. if (typeof dataParser !== 'function') {
  27207. dataParser = line => line;
  27208. }
  27209. this.customParsers.push(line => {
  27210. const match = expression.exec(line);
  27211. if (match) {
  27212. this.trigger('data', {
  27213. type: 'custom',
  27214. data: dataParser(line),
  27215. customType,
  27216. segment
  27217. });
  27218. return true;
  27219. }
  27220. });
  27221. }
  27222. /**
  27223. * Add a custom header mapper
  27224. *
  27225. * @param {Object} options
  27226. * @param {RegExp} options.expression a regular expression to match the custom header
  27227. * @param {Function} options.map function to translate tag into a different tag
  27228. */
  27229. addTagMapper({
  27230. expression,
  27231. map
  27232. }) {
  27233. const mapFn = line => {
  27234. if (expression.test(line)) {
  27235. return map(line);
  27236. }
  27237. return line;
  27238. };
  27239. this.tagMappers.push(mapFn);
  27240. }
  27241. }
  27242. const camelCase = str => str.toLowerCase().replace(/-(\w)/g, a => a[1].toUpperCase());
  27243. const camelCaseKeys = function (attributes) {
  27244. const result = {};
  27245. Object.keys(attributes).forEach(function (key) {
  27246. result[camelCase(key)] = attributes[key];
  27247. });
  27248. return result;
  27249. }; // set SERVER-CONTROL hold back based upon targetDuration and partTargetDuration
  27250. // we need this helper because defaults are based upon targetDuration and
  27251. // partTargetDuration being set, but they may not be if SERVER-CONTROL appears before
  27252. // target durations are set.
  27253. const setHoldBack = function (manifest) {
  27254. const {
  27255. serverControl,
  27256. targetDuration,
  27257. partTargetDuration
  27258. } = manifest;
  27259. if (!serverControl) {
  27260. return;
  27261. }
  27262. const tag = '#EXT-X-SERVER-CONTROL';
  27263. const hb = 'holdBack';
  27264. const phb = 'partHoldBack';
  27265. const minTargetDuration = targetDuration && targetDuration * 3;
  27266. const minPartDuration = partTargetDuration && partTargetDuration * 2;
  27267. if (targetDuration && !serverControl.hasOwnProperty(hb)) {
  27268. serverControl[hb] = minTargetDuration;
  27269. this.trigger('info', {
  27270. message: `${tag} defaulting HOLD-BACK to targetDuration * 3 (${minTargetDuration}).`
  27271. });
  27272. }
  27273. if (minTargetDuration && serverControl[hb] < minTargetDuration) {
  27274. this.trigger('warn', {
  27275. message: `${tag} clamping HOLD-BACK (${serverControl[hb]}) to targetDuration * 3 (${minTargetDuration})`
  27276. });
  27277. serverControl[hb] = minTargetDuration;
  27278. } // default no part hold back to part target duration * 3
  27279. if (partTargetDuration && !serverControl.hasOwnProperty(phb)) {
  27280. serverControl[phb] = partTargetDuration * 3;
  27281. this.trigger('info', {
  27282. message: `${tag} defaulting PART-HOLD-BACK to partTargetDuration * 3 (${serverControl[phb]}).`
  27283. });
  27284. } // if part hold back is too small default it to part target duration * 2
  27285. if (partTargetDuration && serverControl[phb] < minPartDuration) {
  27286. this.trigger('warn', {
  27287. message: `${tag} clamping PART-HOLD-BACK (${serverControl[phb]}) to partTargetDuration * 2 (${minPartDuration}).`
  27288. });
  27289. serverControl[phb] = minPartDuration;
  27290. }
  27291. };
  27292. /**
  27293. * A parser for M3U8 files. The current interpretation of the input is
  27294. * exposed as a property `manifest` on parser objects. It's just two lines to
  27295. * create and parse a manifest once you have the contents available as a string:
  27296. *
  27297. * ```js
  27298. * var parser = new m3u8.Parser();
  27299. * parser.push(xhr.responseText);
  27300. * ```
  27301. *
  27302. * New input can later be applied to update the manifest object by calling
  27303. * `push` again.
  27304. *
  27305. * The parser attempts to create a usable manifest object even if the
  27306. * underlying input is somewhat nonsensical. It emits `info` and `warning`
  27307. * events during the parse if it encounters input that seems invalid or
  27308. * requires some property of the manifest object to be defaulted.
  27309. *
  27310. * @class Parser
  27311. * @extends Stream
  27312. */
  27313. class Parser extends Stream {
  27314. constructor() {
  27315. super();
  27316. this.lineStream = new LineStream();
  27317. this.parseStream = new ParseStream();
  27318. this.lineStream.pipe(this.parseStream);
  27319. /* eslint-disable consistent-this */
  27320. const self = this;
  27321. /* eslint-enable consistent-this */
  27322. const uris = [];
  27323. let currentUri = {}; // if specified, the active EXT-X-MAP definition
  27324. let currentMap; // if specified, the active decryption key
  27325. let key;
  27326. let hasParts = false;
  27327. const noop = function () {};
  27328. const defaultMediaGroups = {
  27329. 'AUDIO': {},
  27330. 'VIDEO': {},
  27331. 'CLOSED-CAPTIONS': {},
  27332. 'SUBTITLES': {}
  27333. }; // This is the Widevine UUID from DASH IF IOP. The same exact string is
  27334. // used in MPDs with Widevine encrypted streams.
  27335. const widevineUuid = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed'; // group segments into numbered timelines delineated by discontinuities
  27336. let currentTimeline = 0; // the manifest is empty until the parse stream begins delivering data
  27337. this.manifest = {
  27338. allowCache: true,
  27339. discontinuityStarts: [],
  27340. segments: []
  27341. }; // keep track of the last seen segment's byte range end, as segments are not required
  27342. // to provide the offset, in which case it defaults to the next byte after the
  27343. // previous segment
  27344. let lastByterangeEnd = 0; // keep track of the last seen part's byte range end.
  27345. let lastPartByterangeEnd = 0;
  27346. this.on('end', () => {
  27347. // only add preloadSegment if we don't yet have a uri for it.
  27348. // and we actually have parts/preloadHints
  27349. if (currentUri.uri || !currentUri.parts && !currentUri.preloadHints) {
  27350. return;
  27351. }
  27352. if (!currentUri.map && currentMap) {
  27353. currentUri.map = currentMap;
  27354. }
  27355. if (!currentUri.key && key) {
  27356. currentUri.key = key;
  27357. }
  27358. if (!currentUri.timeline && typeof currentTimeline === 'number') {
  27359. currentUri.timeline = currentTimeline;
  27360. }
  27361. this.manifest.preloadSegment = currentUri;
  27362. }); // update the manifest with the m3u8 entry from the parse stream
  27363. this.parseStream.on('data', function (entry) {
  27364. let mediaGroup;
  27365. let rendition;
  27366. ({
  27367. tag() {
  27368. // switch based on the tag type
  27369. (({
  27370. version() {
  27371. if (entry.version) {
  27372. this.manifest.version = entry.version;
  27373. }
  27374. },
  27375. 'allow-cache'() {
  27376. this.manifest.allowCache = entry.allowed;
  27377. if (!('allowed' in entry)) {
  27378. this.trigger('info', {
  27379. message: 'defaulting allowCache to YES'
  27380. });
  27381. this.manifest.allowCache = true;
  27382. }
  27383. },
  27384. byterange() {
  27385. const byterange = {};
  27386. if ('length' in entry) {
  27387. currentUri.byterange = byterange;
  27388. byterange.length = entry.length;
  27389. if (!('offset' in entry)) {
  27390. /*
  27391. * From the latest spec (as of this writing):
  27392. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.2
  27393. *
  27394. * Same text since EXT-X-BYTERANGE's introduction in draft 7:
  27395. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.1)
  27396. *
  27397. * "If o [offset] is not present, the sub-range begins at the next byte
  27398. * following the sub-range of the previous media segment."
  27399. */
  27400. entry.offset = lastByterangeEnd;
  27401. }
  27402. }
  27403. if ('offset' in entry) {
  27404. currentUri.byterange = byterange;
  27405. byterange.offset = entry.offset;
  27406. }
  27407. lastByterangeEnd = byterange.offset + byterange.length;
  27408. },
  27409. endlist() {
  27410. this.manifest.endList = true;
  27411. },
  27412. inf() {
  27413. if (!('mediaSequence' in this.manifest)) {
  27414. this.manifest.mediaSequence = 0;
  27415. this.trigger('info', {
  27416. message: 'defaulting media sequence to zero'
  27417. });
  27418. }
  27419. if (!('discontinuitySequence' in this.manifest)) {
  27420. this.manifest.discontinuitySequence = 0;
  27421. this.trigger('info', {
  27422. message: 'defaulting discontinuity sequence to zero'
  27423. });
  27424. }
  27425. if (entry.duration > 0) {
  27426. currentUri.duration = entry.duration;
  27427. }
  27428. if (entry.duration === 0) {
  27429. currentUri.duration = 0.01;
  27430. this.trigger('info', {
  27431. message: 'updating zero segment duration to a small value'
  27432. });
  27433. }
  27434. this.manifest.segments = uris;
  27435. },
  27436. key() {
  27437. if (!entry.attributes) {
  27438. this.trigger('warn', {
  27439. message: 'ignoring key declaration without attribute list'
  27440. });
  27441. return;
  27442. } // clear the active encryption key
  27443. if (entry.attributes.METHOD === 'NONE') {
  27444. key = null;
  27445. return;
  27446. }
  27447. if (!entry.attributes.URI) {
  27448. this.trigger('warn', {
  27449. message: 'ignoring key declaration without URI'
  27450. });
  27451. return;
  27452. }
  27453. if (entry.attributes.KEYFORMAT === 'com.apple.streamingkeydelivery') {
  27454. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  27455. this.manifest.contentProtection['com.apple.fps.1_0'] = {
  27456. attributes: entry.attributes
  27457. };
  27458. return;
  27459. }
  27460. if (entry.attributes.KEYFORMAT === 'com.microsoft.playready') {
  27461. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  27462. this.manifest.contentProtection['com.microsoft.playready'] = {
  27463. uri: entry.attributes.URI
  27464. };
  27465. return;
  27466. } // check if the content is encrypted for Widevine
  27467. // Widevine/HLS spec: https://storage.googleapis.com/wvdocs/Widevine_DRM_HLS.pdf
  27468. if (entry.attributes.KEYFORMAT === widevineUuid) {
  27469. const VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR', 'SAMPLE-AES-CENC'];
  27470. if (VALID_METHODS.indexOf(entry.attributes.METHOD) === -1) {
  27471. this.trigger('warn', {
  27472. message: 'invalid key method provided for Widevine'
  27473. });
  27474. return;
  27475. }
  27476. if (entry.attributes.METHOD === 'SAMPLE-AES-CENC') {
  27477. this.trigger('warn', {
  27478. message: 'SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead'
  27479. });
  27480. }
  27481. if (entry.attributes.URI.substring(0, 23) !== 'data:text/plain;base64,') {
  27482. this.trigger('warn', {
  27483. message: 'invalid key URI provided for Widevine'
  27484. });
  27485. return;
  27486. }
  27487. if (!(entry.attributes.KEYID && entry.attributes.KEYID.substring(0, 2) === '0x')) {
  27488. this.trigger('warn', {
  27489. message: 'invalid key ID provided for Widevine'
  27490. });
  27491. return;
  27492. } // if Widevine key attributes are valid, store them as `contentProtection`
  27493. // on the manifest to emulate Widevine tag structure in a DASH mpd
  27494. this.manifest.contentProtection = this.manifest.contentProtection || {};
  27495. this.manifest.contentProtection['com.widevine.alpha'] = {
  27496. attributes: {
  27497. schemeIdUri: entry.attributes.KEYFORMAT,
  27498. // remove '0x' from the key id string
  27499. keyId: entry.attributes.KEYID.substring(2)
  27500. },
  27501. // decode the base64-encoded PSSH box
  27502. pssh: decodeB64ToUint8Array$1(entry.attributes.URI.split(',')[1])
  27503. };
  27504. return;
  27505. }
  27506. if (!entry.attributes.METHOD) {
  27507. this.trigger('warn', {
  27508. message: 'defaulting key method to AES-128'
  27509. });
  27510. } // setup an encryption key for upcoming segments
  27511. key = {
  27512. method: entry.attributes.METHOD || 'AES-128',
  27513. uri: entry.attributes.URI
  27514. };
  27515. if (typeof entry.attributes.IV !== 'undefined') {
  27516. key.iv = entry.attributes.IV;
  27517. }
  27518. },
  27519. 'media-sequence'() {
  27520. if (!isFinite(entry.number)) {
  27521. this.trigger('warn', {
  27522. message: 'ignoring invalid media sequence: ' + entry.number
  27523. });
  27524. return;
  27525. }
  27526. this.manifest.mediaSequence = entry.number;
  27527. },
  27528. 'discontinuity-sequence'() {
  27529. if (!isFinite(entry.number)) {
  27530. this.trigger('warn', {
  27531. message: 'ignoring invalid discontinuity sequence: ' + entry.number
  27532. });
  27533. return;
  27534. }
  27535. this.manifest.discontinuitySequence = entry.number;
  27536. currentTimeline = entry.number;
  27537. },
  27538. 'playlist-type'() {
  27539. if (!/VOD|EVENT/.test(entry.playlistType)) {
  27540. this.trigger('warn', {
  27541. message: 'ignoring unknown playlist type: ' + entry.playlist
  27542. });
  27543. return;
  27544. }
  27545. this.manifest.playlistType = entry.playlistType;
  27546. },
  27547. map() {
  27548. currentMap = {};
  27549. if (entry.uri) {
  27550. currentMap.uri = entry.uri;
  27551. }
  27552. if (entry.byterange) {
  27553. currentMap.byterange = entry.byterange;
  27554. }
  27555. if (key) {
  27556. currentMap.key = key;
  27557. }
  27558. },
  27559. 'stream-inf'() {
  27560. this.manifest.playlists = uris;
  27561. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  27562. if (!entry.attributes) {
  27563. this.trigger('warn', {
  27564. message: 'ignoring empty stream-inf attributes'
  27565. });
  27566. return;
  27567. }
  27568. if (!currentUri.attributes) {
  27569. currentUri.attributes = {};
  27570. }
  27571. _extends$1(currentUri.attributes, entry.attributes);
  27572. },
  27573. media() {
  27574. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  27575. if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
  27576. this.trigger('warn', {
  27577. message: 'ignoring incomplete or missing media group'
  27578. });
  27579. return;
  27580. } // find the media group, creating defaults as necessary
  27581. const mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
  27582. mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
  27583. mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']]; // collect the rendition metadata
  27584. rendition = {
  27585. default: /yes/i.test(entry.attributes.DEFAULT)
  27586. };
  27587. if (rendition.default) {
  27588. rendition.autoselect = true;
  27589. } else {
  27590. rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
  27591. }
  27592. if (entry.attributes.LANGUAGE) {
  27593. rendition.language = entry.attributes.LANGUAGE;
  27594. }
  27595. if (entry.attributes.URI) {
  27596. rendition.uri = entry.attributes.URI;
  27597. }
  27598. if (entry.attributes['INSTREAM-ID']) {
  27599. rendition.instreamId = entry.attributes['INSTREAM-ID'];
  27600. }
  27601. if (entry.attributes.CHARACTERISTICS) {
  27602. rendition.characteristics = entry.attributes.CHARACTERISTICS;
  27603. }
  27604. if (entry.attributes.FORCED) {
  27605. rendition.forced = /yes/i.test(entry.attributes.FORCED);
  27606. } // insert the new rendition
  27607. mediaGroup[entry.attributes.NAME] = rendition;
  27608. },
  27609. discontinuity() {
  27610. currentTimeline += 1;
  27611. currentUri.discontinuity = true;
  27612. this.manifest.discontinuityStarts.push(uris.length);
  27613. },
  27614. 'program-date-time'() {
  27615. if (typeof this.manifest.dateTimeString === 'undefined') {
  27616. // PROGRAM-DATE-TIME is a media-segment tag, but for backwards
  27617. // compatibility, we add the first occurence of the PROGRAM-DATE-TIME tag
  27618. // to the manifest object
  27619. // TODO: Consider removing this in future major version
  27620. this.manifest.dateTimeString = entry.dateTimeString;
  27621. this.manifest.dateTimeObject = entry.dateTimeObject;
  27622. }
  27623. currentUri.dateTimeString = entry.dateTimeString;
  27624. currentUri.dateTimeObject = entry.dateTimeObject;
  27625. },
  27626. targetduration() {
  27627. if (!isFinite(entry.duration) || entry.duration < 0) {
  27628. this.trigger('warn', {
  27629. message: 'ignoring invalid target duration: ' + entry.duration
  27630. });
  27631. return;
  27632. }
  27633. this.manifest.targetDuration = entry.duration;
  27634. setHoldBack.call(this, this.manifest);
  27635. },
  27636. start() {
  27637. if (!entry.attributes || isNaN(entry.attributes['TIME-OFFSET'])) {
  27638. this.trigger('warn', {
  27639. message: 'ignoring start declaration without appropriate attribute list'
  27640. });
  27641. return;
  27642. }
  27643. this.manifest.start = {
  27644. timeOffset: entry.attributes['TIME-OFFSET'],
  27645. precise: entry.attributes.PRECISE
  27646. };
  27647. },
  27648. 'cue-out'() {
  27649. currentUri.cueOut = entry.data;
  27650. },
  27651. 'cue-out-cont'() {
  27652. currentUri.cueOutCont = entry.data;
  27653. },
  27654. 'cue-in'() {
  27655. currentUri.cueIn = entry.data;
  27656. },
  27657. 'skip'() {
  27658. this.manifest.skip = camelCaseKeys(entry.attributes);
  27659. this.warnOnMissingAttributes_('#EXT-X-SKIP', entry.attributes, ['SKIPPED-SEGMENTS']);
  27660. },
  27661. 'part'() {
  27662. hasParts = true; // parts are always specifed before a segment
  27663. const segmentIndex = this.manifest.segments.length;
  27664. const part = camelCaseKeys(entry.attributes);
  27665. currentUri.parts = currentUri.parts || [];
  27666. currentUri.parts.push(part);
  27667. if (part.byterange) {
  27668. if (!part.byterange.hasOwnProperty('offset')) {
  27669. part.byterange.offset = lastPartByterangeEnd;
  27670. }
  27671. lastPartByterangeEnd = part.byterange.offset + part.byterange.length;
  27672. }
  27673. const partIndex = currentUri.parts.length - 1;
  27674. this.warnOnMissingAttributes_(`#EXT-X-PART #${partIndex} for segment #${segmentIndex}`, entry.attributes, ['URI', 'DURATION']);
  27675. if (this.manifest.renditionReports) {
  27676. this.manifest.renditionReports.forEach((r, i) => {
  27677. if (!r.hasOwnProperty('lastPart')) {
  27678. this.trigger('warn', {
  27679. message: `#EXT-X-RENDITION-REPORT #${i} lacks required attribute(s): LAST-PART`
  27680. });
  27681. }
  27682. });
  27683. }
  27684. },
  27685. 'server-control'() {
  27686. const attrs = this.manifest.serverControl = camelCaseKeys(entry.attributes);
  27687. if (!attrs.hasOwnProperty('canBlockReload')) {
  27688. attrs.canBlockReload = false;
  27689. this.trigger('info', {
  27690. message: '#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false'
  27691. });
  27692. }
  27693. setHoldBack.call(this, this.manifest);
  27694. if (attrs.canSkipDateranges && !attrs.hasOwnProperty('canSkipUntil')) {
  27695. this.trigger('warn', {
  27696. message: '#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set'
  27697. });
  27698. }
  27699. },
  27700. 'preload-hint'() {
  27701. // parts are always specifed before a segment
  27702. const segmentIndex = this.manifest.segments.length;
  27703. const hint = camelCaseKeys(entry.attributes);
  27704. const isPart = hint.type && hint.type === 'PART';
  27705. currentUri.preloadHints = currentUri.preloadHints || [];
  27706. currentUri.preloadHints.push(hint);
  27707. if (hint.byterange) {
  27708. if (!hint.byterange.hasOwnProperty('offset')) {
  27709. // use last part byterange end or zero if not a part.
  27710. hint.byterange.offset = isPart ? lastPartByterangeEnd : 0;
  27711. if (isPart) {
  27712. lastPartByterangeEnd = hint.byterange.offset + hint.byterange.length;
  27713. }
  27714. }
  27715. }
  27716. const index = currentUri.preloadHints.length - 1;
  27717. this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex}`, entry.attributes, ['TYPE', 'URI']);
  27718. if (!hint.type) {
  27719. return;
  27720. } // search through all preload hints except for the current one for
  27721. // a duplicate type.
  27722. for (let i = 0; i < currentUri.preloadHints.length - 1; i++) {
  27723. const otherHint = currentUri.preloadHints[i];
  27724. if (!otherHint.type) {
  27725. continue;
  27726. }
  27727. if (otherHint.type === hint.type) {
  27728. this.trigger('warn', {
  27729. message: `#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex} has the same TYPE ${hint.type} as preload hint #${i}`
  27730. });
  27731. }
  27732. }
  27733. },
  27734. 'rendition-report'() {
  27735. const report = camelCaseKeys(entry.attributes);
  27736. this.manifest.renditionReports = this.manifest.renditionReports || [];
  27737. this.manifest.renditionReports.push(report);
  27738. const index = this.manifest.renditionReports.length - 1;
  27739. const required = ['LAST-MSN', 'URI'];
  27740. if (hasParts) {
  27741. required.push('LAST-PART');
  27742. }
  27743. this.warnOnMissingAttributes_(`#EXT-X-RENDITION-REPORT #${index}`, entry.attributes, required);
  27744. },
  27745. 'part-inf'() {
  27746. this.manifest.partInf = camelCaseKeys(entry.attributes);
  27747. this.warnOnMissingAttributes_('#EXT-X-PART-INF', entry.attributes, ['PART-TARGET']);
  27748. if (this.manifest.partInf.partTarget) {
  27749. this.manifest.partTargetDuration = this.manifest.partInf.partTarget;
  27750. }
  27751. setHoldBack.call(this, this.manifest);
  27752. }
  27753. })[entry.tagType] || noop).call(self);
  27754. },
  27755. uri() {
  27756. currentUri.uri = entry.uri;
  27757. uris.push(currentUri); // if no explicit duration was declared, use the target duration
  27758. if (this.manifest.targetDuration && !('duration' in currentUri)) {
  27759. this.trigger('warn', {
  27760. message: 'defaulting segment duration to the target duration'
  27761. });
  27762. currentUri.duration = this.manifest.targetDuration;
  27763. } // annotate with encryption information, if necessary
  27764. if (key) {
  27765. currentUri.key = key;
  27766. }
  27767. currentUri.timeline = currentTimeline; // annotate with initialization segment information, if necessary
  27768. if (currentMap) {
  27769. currentUri.map = currentMap;
  27770. } // reset the last byterange end as it needs to be 0 between parts
  27771. lastPartByterangeEnd = 0; // prepare for the next URI
  27772. currentUri = {};
  27773. },
  27774. comment() {// comments are not important for playback
  27775. },
  27776. custom() {
  27777. // if this is segment-level data attach the output to the segment
  27778. if (entry.segment) {
  27779. currentUri.custom = currentUri.custom || {};
  27780. currentUri.custom[entry.customType] = entry.data; // if this is manifest-level data attach to the top level manifest object
  27781. } else {
  27782. this.manifest.custom = this.manifest.custom || {};
  27783. this.manifest.custom[entry.customType] = entry.data;
  27784. }
  27785. }
  27786. })[entry.type].call(self);
  27787. });
  27788. }
  27789. warnOnMissingAttributes_(identifier, attributes, required) {
  27790. const missing = [];
  27791. required.forEach(function (key) {
  27792. if (!attributes.hasOwnProperty(key)) {
  27793. missing.push(key);
  27794. }
  27795. });
  27796. if (missing.length) {
  27797. this.trigger('warn', {
  27798. message: `${identifier} lacks required attribute(s): ${missing.join(', ')}`
  27799. });
  27800. }
  27801. }
  27802. /**
  27803. * Parse the input string and update the manifest object.
  27804. *
  27805. * @param {string} chunk a potentially incomplete portion of the manifest
  27806. */
  27807. push(chunk) {
  27808. this.lineStream.push(chunk);
  27809. }
  27810. /**
  27811. * Flush any remaining input. This can be handy if the last line of an M3U8
  27812. * manifest did not contain a trailing newline but the file has been
  27813. * completely received.
  27814. */
  27815. end() {
  27816. // flush any buffered input
  27817. this.lineStream.push('\n');
  27818. this.trigger('end');
  27819. }
  27820. /**
  27821. * Add an additional parser for non-standard tags
  27822. *
  27823. * @param {Object} options a map of options for the added parser
  27824. * @param {RegExp} options.expression a regular expression to match the custom header
  27825. * @param {string} options.type the type to register to the output
  27826. * @param {Function} [options.dataParser] function to parse the line into an object
  27827. * @param {boolean} [options.segment] should tag data be attached to the segment object
  27828. */
  27829. addParser(options) {
  27830. this.parseStream.addParser(options);
  27831. }
  27832. /**
  27833. * Add a custom header mapper
  27834. *
  27835. * @param {Object} options
  27836. * @param {RegExp} options.expression a regular expression to match the custom header
  27837. * @param {Function} options.map function to translate tag into a different tag
  27838. */
  27839. addTagMapper(options) {
  27840. this.parseStream.addTagMapper(options);
  27841. }
  27842. }
  27843. var regexs = {
  27844. // to determine mime types
  27845. mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
  27846. webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
  27847. ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
  27848. // to determine if a codec is audio or video
  27849. video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
  27850. audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
  27851. text: /^(stpp.ttml.im1t)/,
  27852. // mux.js support regex
  27853. muxerVideo: /^(avc0?1)/,
  27854. muxerAudio: /^(mp4a)/,
  27855. // match nothing as muxer does not support text right now.
  27856. // there cannot never be a character before the start of a string
  27857. // so this matches nothing.
  27858. muxerText: /a^/
  27859. };
  27860. var mediaTypes = ['video', 'audio', 'text'];
  27861. var upperMediaTypes = ['Video', 'Audio', 'Text'];
  27862. /**
  27863. * Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard
  27864. * `avc1.<hhhhhh>`
  27865. *
  27866. * @param {string} codec
  27867. * Codec string to translate
  27868. * @return {string}
  27869. * The translated codec string
  27870. */
  27871. var translateLegacyCodec = function translateLegacyCodec(codec) {
  27872. if (!codec) {
  27873. return codec;
  27874. }
  27875. return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
  27876. var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
  27877. var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
  27878. return 'avc1.' + profileHex + '00' + avcLevelHex;
  27879. });
  27880. };
  27881. /**
  27882. * @typedef {Object} ParsedCodecInfo
  27883. * @property {number} codecCount
  27884. * Number of codecs parsed
  27885. * @property {string} [videoCodec]
  27886. * Parsed video codec (if found)
  27887. * @property {string} [videoObjectTypeIndicator]
  27888. * Video object type indicator (if found)
  27889. * @property {string|null} audioProfile
  27890. * Audio profile
  27891. */
  27892. /**
  27893. * Parses a codec string to retrieve the number of codecs specified, the video codec and
  27894. * object type indicator, and the audio profile.
  27895. *
  27896. * @param {string} [codecString]
  27897. * The codec string to parse
  27898. * @return {ParsedCodecInfo}
  27899. * Parsed codec info
  27900. */
  27901. var parseCodecs = function parseCodecs(codecString) {
  27902. if (codecString === void 0) {
  27903. codecString = '';
  27904. }
  27905. var codecs = codecString.split(',');
  27906. var result = [];
  27907. codecs.forEach(function (codec) {
  27908. codec = codec.trim();
  27909. var codecType;
  27910. mediaTypes.forEach(function (name) {
  27911. var match = regexs[name].exec(codec.toLowerCase());
  27912. if (!match || match.length <= 1) {
  27913. return;
  27914. }
  27915. codecType = name; // maintain codec case
  27916. var type = codec.substring(0, match[1].length);
  27917. var details = codec.replace(type, '');
  27918. result.push({
  27919. type: type,
  27920. details: details,
  27921. mediaType: name
  27922. });
  27923. });
  27924. if (!codecType) {
  27925. result.push({
  27926. type: codec,
  27927. details: '',
  27928. mediaType: 'unknown'
  27929. });
  27930. }
  27931. });
  27932. return result;
  27933. };
  27934. /**
  27935. * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
  27936. * a default alternate audio playlist for the provided audio group.
  27937. *
  27938. * @param {Object} master
  27939. * The master playlist
  27940. * @param {string} audioGroupId
  27941. * ID of the audio group for which to find the default codec info
  27942. * @return {ParsedCodecInfo}
  27943. * Parsed codec info
  27944. */
  27945. var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {
  27946. if (!master.mediaGroups.AUDIO || !audioGroupId) {
  27947. return null;
  27948. }
  27949. var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
  27950. if (!audioGroup) {
  27951. return null;
  27952. }
  27953. for (var name in audioGroup) {
  27954. var audioType = audioGroup[name];
  27955. if (audioType.default && audioType.playlists) {
  27956. // codec should be the same for all playlists within the audio type
  27957. return parseCodecs(audioType.playlists[0].attributes.CODECS);
  27958. }
  27959. }
  27960. return null;
  27961. };
  27962. var isAudioCodec = function isAudioCodec(codec) {
  27963. if (codec === void 0) {
  27964. codec = '';
  27965. }
  27966. return regexs.audio.test(codec.trim().toLowerCase());
  27967. };
  27968. var isTextCodec = function isTextCodec(codec) {
  27969. if (codec === void 0) {
  27970. codec = '';
  27971. }
  27972. return regexs.text.test(codec.trim().toLowerCase());
  27973. };
  27974. var getMimeForCodec = function getMimeForCodec(codecString) {
  27975. if (!codecString || typeof codecString !== 'string') {
  27976. return;
  27977. }
  27978. var codecs = codecString.toLowerCase().split(',').map(function (c) {
  27979. return translateLegacyCodec(c.trim());
  27980. }); // default to video type
  27981. var type = 'video'; // only change to audio type if the only codec we have is
  27982. // audio
  27983. if (codecs.length === 1 && isAudioCodec(codecs[0])) {
  27984. type = 'audio';
  27985. } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
  27986. // text uses application/<container> for now
  27987. type = 'application';
  27988. } // default the container to mp4
  27989. var container = 'mp4'; // every codec must be able to go into the container
  27990. // for that container to be the correct one
  27991. if (codecs.every(function (c) {
  27992. return regexs.mp4.test(c);
  27993. })) {
  27994. container = 'mp4';
  27995. } else if (codecs.every(function (c) {
  27996. return regexs.webm.test(c);
  27997. })) {
  27998. container = 'webm';
  27999. } else if (codecs.every(function (c) {
  28000. return regexs.ogg.test(c);
  28001. })) {
  28002. container = 'ogg';
  28003. }
  28004. return type + "/" + container + ";codecs=\"" + codecString + "\"";
  28005. };
  28006. var browserSupportsCodec = function browserSupportsCodec(codecString) {
  28007. if (codecString === void 0) {
  28008. codecString = '';
  28009. }
  28010. return window.MediaSource && window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
  28011. };
  28012. var muxerSupportsCodec = function muxerSupportsCodec(codecString) {
  28013. if (codecString === void 0) {
  28014. codecString = '';
  28015. }
  28016. return codecString.toLowerCase().split(',').every(function (codec) {
  28017. codec = codec.trim(); // any match is supported.
  28018. for (var i = 0; i < upperMediaTypes.length; i++) {
  28019. var type = upperMediaTypes[i];
  28020. if (regexs["muxer" + type].test(codec)) {
  28021. return true;
  28022. }
  28023. }
  28024. return false;
  28025. });
  28026. };
  28027. var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
  28028. var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
  28029. var MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
  28030. var DASH_REGEX = /^application\/dash\+xml/i;
  28031. /**
  28032. * Returns a string that describes the type of source based on a video source object's
  28033. * media type.
  28034. *
  28035. * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}
  28036. *
  28037. * @param {string} type
  28038. * Video source object media type
  28039. * @return {('hls'|'dash'|'vhs-json'|null)}
  28040. * VHS source type string
  28041. */
  28042. var simpleTypeFromSourceType = function simpleTypeFromSourceType(type) {
  28043. if (MPEGURL_REGEX.test(type)) {
  28044. return 'hls';
  28045. }
  28046. if (DASH_REGEX.test(type)) {
  28047. return 'dash';
  28048. } // Denotes the special case of a manifest object passed to http-streaming instead of a
  28049. // source URL.
  28050. //
  28051. // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.
  28052. //
  28053. // In this case, vnd stands for vendor, video.js for the organization, VHS for this
  28054. // project, and the +json suffix identifies the structure of the media type.
  28055. if (type === 'application/vnd.videojs.vhs+json') {
  28056. return 'vhs-json';
  28057. }
  28058. return null;
  28059. };
  28060. // const log2 = Math.log2 ? Math.log2 : (x) => (Math.log(x) / Math.log(2));
  28061. // we used to do this with log2 but BigInt does not support builtin math
  28062. // Math.ceil(log2(x));
  28063. var countBits = function countBits(x) {
  28064. return x.toString(2).length;
  28065. }; // count the number of whole bytes it would take to represent a number
  28066. var countBytes = function countBytes(x) {
  28067. return Math.ceil(countBits(x) / 8);
  28068. };
  28069. var isArrayBufferView = function isArrayBufferView(obj) {
  28070. if (ArrayBuffer.isView === 'function') {
  28071. return ArrayBuffer.isView(obj);
  28072. }
  28073. return obj && obj.buffer instanceof ArrayBuffer;
  28074. };
  28075. var isTypedArray = function isTypedArray(obj) {
  28076. return isArrayBufferView(obj);
  28077. };
  28078. var toUint8 = function toUint8(bytes) {
  28079. if (bytes instanceof Uint8Array) {
  28080. return bytes;
  28081. }
  28082. if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
  28083. // any non-number or NaN leads to empty uint8array
  28084. // eslint-disable-next-line
  28085. if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
  28086. bytes = 0;
  28087. } else {
  28088. bytes = [bytes];
  28089. }
  28090. }
  28091. return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
  28092. };
  28093. var BigInt = window.BigInt || Number;
  28094. var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  28095. (function () {
  28096. var a = new Uint16Array([0xFFCC]);
  28097. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  28098. if (b[0] === 0xFF) {
  28099. return 'big';
  28100. }
  28101. if (b[0] === 0xCC) {
  28102. return 'little';
  28103. }
  28104. return 'unknown';
  28105. })();
  28106. var bytesToNumber = function bytesToNumber(bytes, _temp) {
  28107. var _ref = _temp === void 0 ? {} : _temp,
  28108. _ref$signed = _ref.signed,
  28109. signed = _ref$signed === void 0 ? false : _ref$signed,
  28110. _ref$le = _ref.le,
  28111. le = _ref$le === void 0 ? false : _ref$le;
  28112. bytes = toUint8(bytes);
  28113. var fn = le ? 'reduce' : 'reduceRight';
  28114. var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
  28115. var number = obj.call(bytes, function (total, byte, i) {
  28116. var exponent = le ? i : Math.abs(i + 1 - bytes.length);
  28117. return total + BigInt(byte) * BYTE_TABLE[exponent];
  28118. }, BigInt(0));
  28119. if (signed) {
  28120. var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
  28121. number = BigInt(number);
  28122. if (number > max) {
  28123. number -= max;
  28124. number -= max;
  28125. number -= BigInt(2);
  28126. }
  28127. }
  28128. return Number(number);
  28129. };
  28130. var numberToBytes = function numberToBytes(number, _temp2) {
  28131. var _ref2 = _temp2 === void 0 ? {} : _temp2,
  28132. _ref2$le = _ref2.le,
  28133. le = _ref2$le === void 0 ? false : _ref2$le;
  28134. // eslint-disable-next-line
  28135. if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
  28136. number = 0;
  28137. }
  28138. number = BigInt(number);
  28139. var byteCount = countBytes(number);
  28140. var bytes = new Uint8Array(new ArrayBuffer(byteCount));
  28141. for (var i = 0; i < byteCount; i++) {
  28142. var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
  28143. bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
  28144. if (number < 0) {
  28145. bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
  28146. bytes[byteIndex] -= i === 0 ? 1 : 2;
  28147. }
  28148. }
  28149. return bytes;
  28150. };
  28151. var stringToBytes = function stringToBytes(string, stringIsBytes) {
  28152. if (typeof string !== 'string' && string && typeof string.toString === 'function') {
  28153. string = string.toString();
  28154. }
  28155. if (typeof string !== 'string') {
  28156. return new Uint8Array();
  28157. } // If the string already is bytes, we don't have to do this
  28158. // otherwise we do this so that we split multi length characters
  28159. // into individual bytes
  28160. if (!stringIsBytes) {
  28161. string = unescape(encodeURIComponent(string));
  28162. }
  28163. var view = new Uint8Array(string.length);
  28164. for (var i = 0; i < string.length; i++) {
  28165. view[i] = string.charCodeAt(i);
  28166. }
  28167. return view;
  28168. };
  28169. var concatTypedArrays = function concatTypedArrays() {
  28170. for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
  28171. buffers[_key] = arguments[_key];
  28172. }
  28173. buffers = buffers.filter(function (b) {
  28174. return b && (b.byteLength || b.length) && typeof b !== 'string';
  28175. });
  28176. if (buffers.length <= 1) {
  28177. // for 0 length we will return empty uint8
  28178. // for 1 length we return the first uint8
  28179. return toUint8(buffers[0]);
  28180. }
  28181. var totalLen = buffers.reduce(function (total, buf, i) {
  28182. return total + (buf.byteLength || buf.length);
  28183. }, 0);
  28184. var tempBuffer = new Uint8Array(totalLen);
  28185. var offset = 0;
  28186. buffers.forEach(function (buf) {
  28187. buf = toUint8(buf);
  28188. tempBuffer.set(buf, offset);
  28189. offset += buf.byteLength;
  28190. });
  28191. return tempBuffer;
  28192. };
  28193. /**
  28194. * Check if the bytes "b" are contained within bytes "a".
  28195. *
  28196. * @param {Uint8Array|Array} a
  28197. * Bytes to check in
  28198. *
  28199. * @param {Uint8Array|Array} b
  28200. * Bytes to check for
  28201. *
  28202. * @param {Object} options
  28203. * options
  28204. *
  28205. * @param {Array|Uint8Array} [offset=0]
  28206. * offset to use when looking at bytes in a
  28207. *
  28208. * @param {Array|Uint8Array} [mask=[]]
  28209. * mask to use on bytes before comparison.
  28210. *
  28211. * @return {boolean}
  28212. * If all bytes in b are inside of a, taking into account
  28213. * bit masks.
  28214. */
  28215. var bytesMatch = function bytesMatch(a, b, _temp3) {
  28216. var _ref3 = _temp3 === void 0 ? {} : _temp3,
  28217. _ref3$offset = _ref3.offset,
  28218. offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
  28219. _ref3$mask = _ref3.mask,
  28220. mask = _ref3$mask === void 0 ? [] : _ref3$mask;
  28221. a = toUint8(a);
  28222. b = toUint8(b); // ie 11 does not support uint8 every
  28223. var fn = b.every ? b.every : Array.prototype.every;
  28224. return b.length && a.length - offset >= b.length &&
  28225. // ie 11 doesn't support every on uin8
  28226. fn.call(b, function (bByte, i) {
  28227. var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
  28228. return bByte === aByte;
  28229. });
  28230. };
  28231. var DEFAULT_LOCATION = 'http://example.com';
  28232. var resolveUrl$1 = function resolveUrl(baseUrl, relativeUrl) {
  28233. // return early if we don't need to resolve
  28234. if (/^[a-z]+:/i.test(relativeUrl)) {
  28235. return relativeUrl;
  28236. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  28237. if (/^data:/.test(baseUrl)) {
  28238. baseUrl = window.location && window.location.href || '';
  28239. } // IE11 supports URL but not the URL constructor
  28240. // feature detect the behavior we want
  28241. var nativeURL = typeof window.URL === 'function';
  28242. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  28243. // and if baseUrl isn't an absolute url
  28244. var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  28245. if (nativeURL) {
  28246. baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION);
  28247. } else if (!/\/\//i.test(baseUrl)) {
  28248. baseUrl = urlToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
  28249. }
  28250. if (nativeURL) {
  28251. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  28252. // and if we're location-less, remove the location
  28253. // otherwise, return the url unmodified
  28254. if (removeLocation) {
  28255. return newUrl.href.slice(DEFAULT_LOCATION.length);
  28256. } else if (protocolLess) {
  28257. return newUrl.href.slice(newUrl.protocol.length);
  28258. }
  28259. return newUrl.href;
  28260. }
  28261. return urlToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
  28262. };
  28263. /**
  28264. * Loops through all supported media groups in master and calls the provided
  28265. * callback for each group
  28266. *
  28267. * @param {Object} master
  28268. * The parsed master manifest object
  28269. * @param {string[]} groups
  28270. * The media groups to call the callback for
  28271. * @param {Function} callback
  28272. * Callback to call for each media group
  28273. */
  28274. var forEachMediaGroup$1 = function forEachMediaGroup(master, groups, callback) {
  28275. groups.forEach(function (mediaType) {
  28276. for (var groupKey in master.mediaGroups[mediaType]) {
  28277. for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
  28278. var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
  28279. callback(mediaProperties, mediaType, groupKey, labelKey);
  28280. }
  28281. }
  28282. });
  28283. };
  28284. var atob = function atob(s) {
  28285. return window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');
  28286. };
  28287. function decodeB64ToUint8Array(b64Text) {
  28288. var decodedString = atob(b64Text);
  28289. var array = new Uint8Array(decodedString.length);
  28290. for (var i = 0; i < decodedString.length; i++) {
  28291. array[i] = decodedString.charCodeAt(i);
  28292. }
  28293. return array;
  28294. }
  28295. /**
  28296. * Ponyfill for `Array.prototype.find` which is only available in ES6 runtimes.
  28297. *
  28298. * Works with anything that has a `length` property and index access properties, including NodeList.
  28299. *
  28300. * @template {unknown} T
  28301. * @param {Array<T> | ({length:number, [number]: T})} list
  28302. * @param {function (item: T, index: number, list:Array<T> | ({length:number, [number]: T})):boolean} predicate
  28303. * @param {Partial<Pick<ArrayConstructor['prototype'], 'find'>>?} ac `Array.prototype` by default,
  28304. * allows injecting a custom implementation in tests
  28305. * @returns {T | undefined}
  28306. *
  28307. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
  28308. * @see https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.find
  28309. */
  28310. function find$1(list, predicate, ac) {
  28311. if (ac === undefined) {
  28312. ac = Array.prototype;
  28313. }
  28314. if (list && typeof ac.find === 'function') {
  28315. return ac.find.call(list, predicate);
  28316. }
  28317. for (var i = 0; i < list.length; i++) {
  28318. if (Object.prototype.hasOwnProperty.call(list, i)) {
  28319. var item = list[i];
  28320. if (predicate.call(undefined, item, i, list)) {
  28321. return item;
  28322. }
  28323. }
  28324. }
  28325. }
  28326. /**
  28327. * "Shallow freezes" an object to render it immutable.
  28328. * Uses `Object.freeze` if available,
  28329. * otherwise the immutability is only in the type.
  28330. *
  28331. * Is used to create "enum like" objects.
  28332. *
  28333. * @template T
  28334. * @param {T} object the object to freeze
  28335. * @param {Pick<ObjectConstructor, 'freeze'> = Object} oc `Object` by default,
  28336. * allows to inject custom object constructor for tests
  28337. * @returns {Readonly<T>}
  28338. *
  28339. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
  28340. */
  28341. function freeze(object, oc) {
  28342. if (oc === undefined) {
  28343. oc = Object;
  28344. }
  28345. return oc && typeof oc.freeze === 'function' ? oc.freeze(object) : object;
  28346. }
  28347. /**
  28348. * Since we can not rely on `Object.assign` we provide a simplified version
  28349. * that is sufficient for our needs.
  28350. *
  28351. * @param {Object} target
  28352. * @param {Object | null | undefined} source
  28353. *
  28354. * @returns {Object} target
  28355. * @throws TypeError if target is not an object
  28356. *
  28357. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  28358. * @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign
  28359. */
  28360. function assign(target, source) {
  28361. if (target === null || typeof target !== 'object') {
  28362. throw new TypeError('target is not an object');
  28363. }
  28364. for (var key in source) {
  28365. if (Object.prototype.hasOwnProperty.call(source, key)) {
  28366. target[key] = source[key];
  28367. }
  28368. }
  28369. return target;
  28370. }
  28371. /**
  28372. * All mime types that are allowed as input to `DOMParser.parseFromString`
  28373. *
  28374. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 MDN
  28375. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype WHATWG HTML Spec
  28376. * @see DOMParser.prototype.parseFromString
  28377. */
  28378. var MIME_TYPE = freeze({
  28379. /**
  28380. * `text/html`, the only mime type that triggers treating an XML document as HTML.
  28381. *
  28382. * @see DOMParser.SupportedType.isHTML
  28383. * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
  28384. * @see https://en.wikipedia.org/wiki/HTML Wikipedia
  28385. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
  28386. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring WHATWG HTML Spec
  28387. */
  28388. HTML: 'text/html',
  28389. /**
  28390. * Helper method to check a mime type if it indicates an HTML document
  28391. *
  28392. * @param {string} [value]
  28393. * @returns {boolean}
  28394. *
  28395. * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
  28396. * @see https://en.wikipedia.org/wiki/HTML Wikipedia
  28397. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
  28398. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */
  28399. isHTML: function (value) {
  28400. return value === MIME_TYPE.HTML;
  28401. },
  28402. /**
  28403. * `application/xml`, the standard mime type for XML documents.
  28404. *
  28405. * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType registration
  28406. * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303
  28407. * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
  28408. */
  28409. XML_APPLICATION: 'application/xml',
  28410. /**
  28411. * `text/html`, an alias for `application/xml`.
  28412. *
  28413. * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303
  28414. * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration
  28415. * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
  28416. */
  28417. XML_TEXT: 'text/xml',
  28418. /**
  28419. * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace,
  28420. * but is parsed as an XML document.
  28421. *
  28422. * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType registration
  28423. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec
  28424. * @see https://en.wikipedia.org/wiki/XHTML Wikipedia
  28425. */
  28426. XML_XHTML_APPLICATION: 'application/xhtml+xml',
  28427. /**
  28428. * `image/svg+xml`,
  28429. *
  28430. * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration
  28431. * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1
  28432. * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia
  28433. */
  28434. XML_SVG_IMAGE: 'image/svg+xml'
  28435. });
  28436. /**
  28437. * Namespaces that are used in this code base.
  28438. *
  28439. * @see http://www.w3.org/TR/REC-xml-names
  28440. */
  28441. var NAMESPACE$3 = freeze({
  28442. /**
  28443. * The XHTML namespace.
  28444. *
  28445. * @see http://www.w3.org/1999/xhtml
  28446. */
  28447. HTML: 'http://www.w3.org/1999/xhtml',
  28448. /**
  28449. * Checks if `uri` equals `NAMESPACE.HTML`.
  28450. *
  28451. * @param {string} [uri]
  28452. *
  28453. * @see NAMESPACE.HTML
  28454. */
  28455. isHTML: function (uri) {
  28456. return uri === NAMESPACE$3.HTML;
  28457. },
  28458. /**
  28459. * The SVG namespace.
  28460. *
  28461. * @see http://www.w3.org/2000/svg
  28462. */
  28463. SVG: 'http://www.w3.org/2000/svg',
  28464. /**
  28465. * The `xml:` namespace.
  28466. *
  28467. * @see http://www.w3.org/XML/1998/namespace
  28468. */
  28469. XML: 'http://www.w3.org/XML/1998/namespace',
  28470. /**
  28471. * The `xmlns:` namespace
  28472. *
  28473. * @see https://www.w3.org/2000/xmlns/
  28474. */
  28475. XMLNS: 'http://www.w3.org/2000/xmlns/'
  28476. });
  28477. var assign_1 = assign;
  28478. var find_1 = find$1;
  28479. var freeze_1 = freeze;
  28480. var MIME_TYPE_1 = MIME_TYPE;
  28481. var NAMESPACE_1 = NAMESPACE$3;
  28482. var conventions = {
  28483. assign: assign_1,
  28484. find: find_1,
  28485. freeze: freeze_1,
  28486. MIME_TYPE: MIME_TYPE_1,
  28487. NAMESPACE: NAMESPACE_1
  28488. };
  28489. var find = conventions.find;
  28490. var NAMESPACE$2 = conventions.NAMESPACE;
  28491. /**
  28492. * A prerequisite for `[].filter`, to drop elements that are empty
  28493. * @param {string} input
  28494. * @returns {boolean}
  28495. */
  28496. function notEmptyString(input) {
  28497. return input !== '';
  28498. }
  28499. /**
  28500. * @see https://infra.spec.whatwg.org/#split-on-ascii-whitespace
  28501. * @see https://infra.spec.whatwg.org/#ascii-whitespace
  28502. *
  28503. * @param {string} input
  28504. * @returns {string[]} (can be empty)
  28505. */
  28506. function splitOnASCIIWhitespace(input) {
  28507. // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE
  28508. return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : [];
  28509. }
  28510. /**
  28511. * Adds element as a key to current if it is not already present.
  28512. *
  28513. * @param {Record<string, boolean | undefined>} current
  28514. * @param {string} element
  28515. * @returns {Record<string, boolean | undefined>}
  28516. */
  28517. function orderedSetReducer(current, element) {
  28518. if (!current.hasOwnProperty(element)) {
  28519. current[element] = true;
  28520. }
  28521. return current;
  28522. }
  28523. /**
  28524. * @see https://infra.spec.whatwg.org/#ordered-set
  28525. * @param {string} input
  28526. * @returns {string[]}
  28527. */
  28528. function toOrderedSet(input) {
  28529. if (!input) return [];
  28530. var list = splitOnASCIIWhitespace(input);
  28531. return Object.keys(list.reduce(orderedSetReducer, {}));
  28532. }
  28533. /**
  28534. * Uses `list.indexOf` to implement something like `Array.prototype.includes`,
  28535. * which we can not rely on being available.
  28536. *
  28537. * @param {any[]} list
  28538. * @returns {function(any): boolean}
  28539. */
  28540. function arrayIncludes(list) {
  28541. return function (element) {
  28542. return list && list.indexOf(element) !== -1;
  28543. };
  28544. }
  28545. function copy(src, dest) {
  28546. for (var p in src) {
  28547. if (Object.prototype.hasOwnProperty.call(src, p)) {
  28548. dest[p] = src[p];
  28549. }
  28550. }
  28551. }
  28552. /**
  28553. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  28554. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  28555. */
  28556. function _extends(Class, Super) {
  28557. var pt = Class.prototype;
  28558. if (!(pt instanceof Super)) {
  28559. function t() {}
  28560. t.prototype = Super.prototype;
  28561. t = new t();
  28562. copy(pt, t);
  28563. Class.prototype = pt = t;
  28564. }
  28565. if (pt.constructor != Class) {
  28566. if (typeof Class != 'function') {
  28567. console.error("unknown Class:" + Class);
  28568. }
  28569. pt.constructor = Class;
  28570. }
  28571. }
  28572. // Node Types
  28573. var NodeType = {};
  28574. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  28575. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  28576. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  28577. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  28578. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  28579. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  28580. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  28581. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  28582. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  28583. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  28584. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  28585. var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
  28586. // ExceptionCode
  28587. var ExceptionCode = {};
  28588. var ExceptionMessage = {};
  28589. ExceptionCode.INDEX_SIZE_ERR = (ExceptionMessage[1] = "Index size error", 1);
  28590. ExceptionCode.DOMSTRING_SIZE_ERR = (ExceptionMessage[2] = "DOMString size error", 2);
  28591. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = (ExceptionMessage[3] = "Hierarchy request error", 3);
  28592. ExceptionCode.WRONG_DOCUMENT_ERR = (ExceptionMessage[4] = "Wrong document", 4);
  28593. ExceptionCode.INVALID_CHARACTER_ERR = (ExceptionMessage[5] = "Invalid character", 5);
  28594. ExceptionCode.NO_DATA_ALLOWED_ERR = (ExceptionMessage[6] = "No data allowed", 6);
  28595. ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = (ExceptionMessage[7] = "No modification allowed", 7);
  28596. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = (ExceptionMessage[8] = "Not found", 8);
  28597. ExceptionCode.NOT_SUPPORTED_ERR = (ExceptionMessage[9] = "Not supported", 9);
  28598. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = (ExceptionMessage[10] = "Attribute in use", 10);
  28599. //level2
  28600. ExceptionCode.INVALID_STATE_ERR = (ExceptionMessage[11] = "Invalid state", 11);
  28601. ExceptionCode.SYNTAX_ERR = (ExceptionMessage[12] = "Syntax error", 12);
  28602. ExceptionCode.INVALID_MODIFICATION_ERR = (ExceptionMessage[13] = "Invalid modification", 13);
  28603. ExceptionCode.NAMESPACE_ERR = (ExceptionMessage[14] = "Invalid namespace", 14);
  28604. ExceptionCode.INVALID_ACCESS_ERR = (ExceptionMessage[15] = "Invalid access", 15);
  28605. /**
  28606. * DOM Level 2
  28607. * Object DOMException
  28608. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  28609. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  28610. */
  28611. function DOMException(code, message) {
  28612. if (message instanceof Error) {
  28613. var error = message;
  28614. } else {
  28615. error = this;
  28616. Error.call(this, ExceptionMessage[code]);
  28617. this.message = ExceptionMessage[code];
  28618. if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  28619. }
  28620. error.code = code;
  28621. if (message) this.message = this.message + ": " + message;
  28622. return error;
  28623. }
  28624. DOMException.prototype = Error.prototype;
  28625. copy(ExceptionCode, DOMException);
  28626. /**
  28627. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  28628. * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
  28629. * The items in the NodeList are accessible via an integral index, starting from 0.
  28630. */
  28631. function NodeList() {}
  28632. NodeList.prototype = {
  28633. /**
  28634. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  28635. * @standard level1
  28636. */
  28637. length: 0,
  28638. /**
  28639. * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
  28640. * @standard level1
  28641. * @param index unsigned long
  28642. * Index into the collection.
  28643. * @return Node
  28644. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  28645. */
  28646. item: function (index) {
  28647. return this[index] || null;
  28648. },
  28649. toString: function (isHTML, nodeFilter) {
  28650. for (var buf = [], i = 0; i < this.length; i++) {
  28651. serializeToString(this[i], buf, isHTML, nodeFilter);
  28652. }
  28653. return buf.join('');
  28654. },
  28655. /**
  28656. * @private
  28657. * @param {function (Node):boolean} predicate
  28658. * @returns {Node[]}
  28659. */
  28660. filter: function (predicate) {
  28661. return Array.prototype.filter.call(this, predicate);
  28662. },
  28663. /**
  28664. * @private
  28665. * @param {Node} item
  28666. * @returns {number}
  28667. */
  28668. indexOf: function (item) {
  28669. return Array.prototype.indexOf.call(this, item);
  28670. }
  28671. };
  28672. function LiveNodeList(node, refresh) {
  28673. this._node = node;
  28674. this._refresh = refresh;
  28675. _updateLiveList(this);
  28676. }
  28677. function _updateLiveList(list) {
  28678. var inc = list._node._inc || list._node.ownerDocument._inc;
  28679. if (list._inc != inc) {
  28680. var ls = list._refresh(list._node);
  28681. //console.log(ls.length)
  28682. __set__(list, 'length', ls.length);
  28683. copy(ls, list);
  28684. list._inc = inc;
  28685. }
  28686. }
  28687. LiveNodeList.prototype.item = function (i) {
  28688. _updateLiveList(this);
  28689. return this[i];
  28690. };
  28691. _extends(LiveNodeList, NodeList);
  28692. /**
  28693. * Objects implementing the NamedNodeMap interface are used
  28694. * to represent collections of nodes that can be accessed by name.
  28695. * Note that NamedNodeMap does not inherit from NodeList;
  28696. * NamedNodeMaps are not maintained in any particular order.
  28697. * Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index,
  28698. * but this is simply to allow convenient enumeration of the contents of a NamedNodeMap,
  28699. * and does not imply that the DOM specifies an order to these Nodes.
  28700. * NamedNodeMap objects in the DOM are live.
  28701. * used for attributes or DocumentType entities
  28702. */
  28703. function NamedNodeMap() {}
  28704. function _findNodeIndex(list, node) {
  28705. var i = list.length;
  28706. while (i--) {
  28707. if (list[i] === node) {
  28708. return i;
  28709. }
  28710. }
  28711. }
  28712. function _addNamedNode(el, list, newAttr, oldAttr) {
  28713. if (oldAttr) {
  28714. list[_findNodeIndex(list, oldAttr)] = newAttr;
  28715. } else {
  28716. list[list.length++] = newAttr;
  28717. }
  28718. if (el) {
  28719. newAttr.ownerElement = el;
  28720. var doc = el.ownerDocument;
  28721. if (doc) {
  28722. oldAttr && _onRemoveAttribute(doc, el, oldAttr);
  28723. _onAddAttribute(doc, el, newAttr);
  28724. }
  28725. }
  28726. }
  28727. function _removeNamedNode(el, list, attr) {
  28728. //console.log('remove attr:'+attr)
  28729. var i = _findNodeIndex(list, attr);
  28730. if (i >= 0) {
  28731. var lastIndex = list.length - 1;
  28732. while (i < lastIndex) {
  28733. list[i] = list[++i];
  28734. }
  28735. list.length = lastIndex;
  28736. if (el) {
  28737. var doc = el.ownerDocument;
  28738. if (doc) {
  28739. _onRemoveAttribute(doc, el, attr);
  28740. attr.ownerElement = null;
  28741. }
  28742. }
  28743. } else {
  28744. throw new DOMException(NOT_FOUND_ERR, new Error(el.tagName + '@' + attr));
  28745. }
  28746. }
  28747. NamedNodeMap.prototype = {
  28748. length: 0,
  28749. item: NodeList.prototype.item,
  28750. getNamedItem: function (key) {
  28751. // if(key.indexOf(':')>0 || key == 'xmlns'){
  28752. // return null;
  28753. // }
  28754. //console.log()
  28755. var i = this.length;
  28756. while (i--) {
  28757. var attr = this[i];
  28758. //console.log(attr.nodeName,key)
  28759. if (attr.nodeName == key) {
  28760. return attr;
  28761. }
  28762. }
  28763. },
  28764. setNamedItem: function (attr) {
  28765. var el = attr.ownerElement;
  28766. if (el && el != this._ownerElement) {
  28767. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  28768. }
  28769. var oldAttr = this.getNamedItem(attr.nodeName);
  28770. _addNamedNode(this._ownerElement, this, attr, oldAttr);
  28771. return oldAttr;
  28772. },
  28773. /* returns Node */
  28774. setNamedItemNS: function (attr) {
  28775. // raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  28776. var el = attr.ownerElement,
  28777. oldAttr;
  28778. if (el && el != this._ownerElement) {
  28779. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  28780. }
  28781. oldAttr = this.getNamedItemNS(attr.namespaceURI, attr.localName);
  28782. _addNamedNode(this._ownerElement, this, attr, oldAttr);
  28783. return oldAttr;
  28784. },
  28785. /* returns Node */
  28786. removeNamedItem: function (key) {
  28787. var attr = this.getNamedItem(key);
  28788. _removeNamedNode(this._ownerElement, this, attr);
  28789. return attr;
  28790. },
  28791. // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  28792. //for level2
  28793. removeNamedItemNS: function (namespaceURI, localName) {
  28794. var attr = this.getNamedItemNS(namespaceURI, localName);
  28795. _removeNamedNode(this._ownerElement, this, attr);
  28796. return attr;
  28797. },
  28798. getNamedItemNS: function (namespaceURI, localName) {
  28799. var i = this.length;
  28800. while (i--) {
  28801. var node = this[i];
  28802. if (node.localName == localName && node.namespaceURI == namespaceURI) {
  28803. return node;
  28804. }
  28805. }
  28806. return null;
  28807. }
  28808. };
  28809. /**
  28810. * The DOMImplementation interface represents an object providing methods
  28811. * which are not dependent on any particular document.
  28812. * Such an object is returned by the `Document.implementation` property.
  28813. *
  28814. * __The individual methods describe the differences compared to the specs.__
  28815. *
  28816. * @constructor
  28817. *
  28818. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation MDN
  28819. * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 DOM Level 1 Core (Initial)
  28820. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-102161490 DOM Level 2 Core
  28821. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core
  28822. * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard
  28823. */
  28824. function DOMImplementation$1() {}
  28825. DOMImplementation$1.prototype = {
  28826. /**
  28827. * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given feature is supported.
  28828. * The different implementations fairly diverged in what kind of features were reported.
  28829. * The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use.
  28830. *
  28831. * @deprecated It is deprecated and modern browsers return true in all cases.
  28832. *
  28833. * @param {string} feature
  28834. * @param {string} [version]
  28835. * @returns {boolean} always true
  28836. *
  28837. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN
  28838. * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core
  28839. * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard
  28840. */
  28841. hasFeature: function (feature, version) {
  28842. return true;
  28843. },
  28844. /**
  28845. * Creates an XML Document object of the specified type with its document element.
  28846. *
  28847. * __It behaves slightly different from the description in the living standard__:
  28848. * - There is no interface/class `XMLDocument`, it returns a `Document` instance.
  28849. * - `contentType`, `encoding`, `mode`, `origin`, `url` fields are currently not declared.
  28850. * - this implementation is not validating names or qualified names
  28851. * (when parsing XML strings, the SAX parser takes care of that)
  28852. *
  28853. * @param {string|null} namespaceURI
  28854. * @param {string} qualifiedName
  28855. * @param {DocumentType=null} doctype
  28856. * @returns {Document}
  28857. *
  28858. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN
  28859. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM Level 2 Core (initial)
  28860. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core
  28861. *
  28862. * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
  28863. * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
  28864. * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
  28865. */
  28866. createDocument: function (namespaceURI, qualifiedName, doctype) {
  28867. var doc = new Document();
  28868. doc.implementation = this;
  28869. doc.childNodes = new NodeList();
  28870. doc.doctype = doctype || null;
  28871. if (doctype) {
  28872. doc.appendChild(doctype);
  28873. }
  28874. if (qualifiedName) {
  28875. var root = doc.createElementNS(namespaceURI, qualifiedName);
  28876. doc.appendChild(root);
  28877. }
  28878. return doc;
  28879. },
  28880. /**
  28881. * Returns a doctype, with the given `qualifiedName`, `publicId`, and `systemId`.
  28882. *
  28883. * __This behavior is slightly different from the in the specs__:
  28884. * - this implementation is not validating names or qualified names
  28885. * (when parsing XML strings, the SAX parser takes care of that)
  28886. *
  28887. * @param {string} qualifiedName
  28888. * @param {string} [publicId]
  28889. * @param {string} [systemId]
  28890. * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` upon document creation
  28891. * or can be put into the document via methods like `Node.insertBefore()` or `Node.replaceChild()`
  28892. *
  28893. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType MDN
  28894. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM Level 2 Core
  28895. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living Standard
  28896. *
  28897. * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
  28898. * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
  28899. * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
  28900. */
  28901. createDocumentType: function (qualifiedName, publicId, systemId) {
  28902. var node = new DocumentType();
  28903. node.name = qualifiedName;
  28904. node.nodeName = qualifiedName;
  28905. node.publicId = publicId || '';
  28906. node.systemId = systemId || '';
  28907. return node;
  28908. }
  28909. };
  28910. /**
  28911. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  28912. */
  28913. function Node() {}
  28914. Node.prototype = {
  28915. firstChild: null,
  28916. lastChild: null,
  28917. previousSibling: null,
  28918. nextSibling: null,
  28919. attributes: null,
  28920. parentNode: null,
  28921. childNodes: null,
  28922. ownerDocument: null,
  28923. nodeValue: null,
  28924. namespaceURI: null,
  28925. prefix: null,
  28926. localName: null,
  28927. // Modified in DOM Level 2:
  28928. insertBefore: function (newChild, refChild) {
  28929. //raises
  28930. return _insertBefore(this, newChild, refChild);
  28931. },
  28932. replaceChild: function (newChild, oldChild) {
  28933. //raises
  28934. _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);
  28935. if (oldChild) {
  28936. this.removeChild(oldChild);
  28937. }
  28938. },
  28939. removeChild: function (oldChild) {
  28940. return _removeChild(this, oldChild);
  28941. },
  28942. appendChild: function (newChild) {
  28943. return this.insertBefore(newChild, null);
  28944. },
  28945. hasChildNodes: function () {
  28946. return this.firstChild != null;
  28947. },
  28948. cloneNode: function (deep) {
  28949. return cloneNode(this.ownerDocument || this, this, deep);
  28950. },
  28951. // Modified in DOM Level 2:
  28952. normalize: function () {
  28953. var child = this.firstChild;
  28954. while (child) {
  28955. var next = child.nextSibling;
  28956. if (next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE) {
  28957. this.removeChild(next);
  28958. child.appendData(next.data);
  28959. } else {
  28960. child.normalize();
  28961. child = next;
  28962. }
  28963. }
  28964. },
  28965. // Introduced in DOM Level 2:
  28966. isSupported: function (feature, version) {
  28967. return this.ownerDocument.implementation.hasFeature(feature, version);
  28968. },
  28969. // Introduced in DOM Level 2:
  28970. hasAttributes: function () {
  28971. return this.attributes.length > 0;
  28972. },
  28973. /**
  28974. * Look up the prefix associated to the given namespace URI, starting from this node.
  28975. * **The default namespace declarations are ignored by this method.**
  28976. * See Namespace Prefix Lookup for details on the algorithm used by this method.
  28977. *
  28978. * _Note: The implementation seems to be incomplete when compared to the algorithm described in the specs._
  28979. *
  28980. * @param {string | null} namespaceURI
  28981. * @returns {string | null}
  28982. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix
  28983. * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo
  28984. * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix
  28985. * @see https://github.com/xmldom/xmldom/issues/322
  28986. */
  28987. lookupPrefix: function (namespaceURI) {
  28988. var el = this;
  28989. while (el) {
  28990. var map = el._nsMap;
  28991. //console.dir(map)
  28992. if (map) {
  28993. for (var n in map) {
  28994. if (Object.prototype.hasOwnProperty.call(map, n) && map[n] === namespaceURI) {
  28995. return n;
  28996. }
  28997. }
  28998. }
  28999. el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
  29000. }
  29001. return null;
  29002. },
  29003. // Introduced in DOM Level 3:
  29004. lookupNamespaceURI: function (prefix) {
  29005. var el = this;
  29006. while (el) {
  29007. var map = el._nsMap;
  29008. //console.dir(map)
  29009. if (map) {
  29010. if (Object.prototype.hasOwnProperty.call(map, prefix)) {
  29011. return map[prefix];
  29012. }
  29013. }
  29014. el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
  29015. }
  29016. return null;
  29017. },
  29018. // Introduced in DOM Level 3:
  29019. isDefaultNamespace: function (namespaceURI) {
  29020. var prefix = this.lookupPrefix(namespaceURI);
  29021. return prefix == null;
  29022. }
  29023. };
  29024. function _xmlEncoder(c) {
  29025. return c == '<' && '&lt;' || c == '>' && '&gt;' || c == '&' && '&amp;' || c == '"' && '&quot;' || '&#' + c.charCodeAt() + ';';
  29026. }
  29027. copy(NodeType, Node);
  29028. copy(NodeType, Node.prototype);
  29029. /**
  29030. * @param callback return true for continue,false for break
  29031. * @return boolean true: break visit;
  29032. */
  29033. function _visitNode(node, callback) {
  29034. if (callback(node)) {
  29035. return true;
  29036. }
  29037. if (node = node.firstChild) {
  29038. do {
  29039. if (_visitNode(node, callback)) {
  29040. return true;
  29041. }
  29042. } while (node = node.nextSibling);
  29043. }
  29044. }
  29045. function Document() {
  29046. this.ownerDocument = this;
  29047. }
  29048. function _onAddAttribute(doc, el, newAttr) {
  29049. doc && doc._inc++;
  29050. var ns = newAttr.namespaceURI;
  29051. if (ns === NAMESPACE$2.XMLNS) {
  29052. //update namespace
  29053. el._nsMap[newAttr.prefix ? newAttr.localName : ''] = newAttr.value;
  29054. }
  29055. }
  29056. function _onRemoveAttribute(doc, el, newAttr, remove) {
  29057. doc && doc._inc++;
  29058. var ns = newAttr.namespaceURI;
  29059. if (ns === NAMESPACE$2.XMLNS) {
  29060. //update namespace
  29061. delete el._nsMap[newAttr.prefix ? newAttr.localName : ''];
  29062. }
  29063. }
  29064. /**
  29065. * Updates `el.childNodes`, updating the indexed items and it's `length`.
  29066. * Passing `newChild` means it will be appended.
  29067. * Otherwise it's assumed that an item has been removed,
  29068. * and `el.firstNode` and it's `.nextSibling` are used
  29069. * to walk the current list of child nodes.
  29070. *
  29071. * @param {Document} doc
  29072. * @param {Node} el
  29073. * @param {Node} [newChild]
  29074. * @private
  29075. */
  29076. function _onUpdateChild(doc, el, newChild) {
  29077. if (doc && doc._inc) {
  29078. doc._inc++;
  29079. //update childNodes
  29080. var cs = el.childNodes;
  29081. if (newChild) {
  29082. cs[cs.length++] = newChild;
  29083. } else {
  29084. var child = el.firstChild;
  29085. var i = 0;
  29086. while (child) {
  29087. cs[i++] = child;
  29088. child = child.nextSibling;
  29089. }
  29090. cs.length = i;
  29091. delete cs[cs.length];
  29092. }
  29093. }
  29094. }
  29095. /**
  29096. * Removes the connections between `parentNode` and `child`
  29097. * and any existing `child.previousSibling` or `child.nextSibling`.
  29098. *
  29099. * @see https://github.com/xmldom/xmldom/issues/135
  29100. * @see https://github.com/xmldom/xmldom/issues/145
  29101. *
  29102. * @param {Node} parentNode
  29103. * @param {Node} child
  29104. * @returns {Node} the child that was removed.
  29105. * @private
  29106. */
  29107. function _removeChild(parentNode, child) {
  29108. var previous = child.previousSibling;
  29109. var next = child.nextSibling;
  29110. if (previous) {
  29111. previous.nextSibling = next;
  29112. } else {
  29113. parentNode.firstChild = next;
  29114. }
  29115. if (next) {
  29116. next.previousSibling = previous;
  29117. } else {
  29118. parentNode.lastChild = previous;
  29119. }
  29120. child.parentNode = null;
  29121. child.previousSibling = null;
  29122. child.nextSibling = null;
  29123. _onUpdateChild(parentNode.ownerDocument, parentNode);
  29124. return child;
  29125. }
  29126. /**
  29127. * Returns `true` if `node` can be a parent for insertion.
  29128. * @param {Node} node
  29129. * @returns {boolean}
  29130. */
  29131. function hasValidParentNodeType(node) {
  29132. return node && (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE);
  29133. }
  29134. /**
  29135. * Returns `true` if `node` can be inserted according to it's `nodeType`.
  29136. * @param {Node} node
  29137. * @returns {boolean}
  29138. */
  29139. function hasInsertableNodeType(node) {
  29140. return node && (isElementNode(node) || isTextNode(node) || isDocTypeNode(node) || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.COMMENT_NODE || node.nodeType === Node.PROCESSING_INSTRUCTION_NODE);
  29141. }
  29142. /**
  29143. * Returns true if `node` is a DOCTYPE node
  29144. * @param {Node} node
  29145. * @returns {boolean}
  29146. */
  29147. function isDocTypeNode(node) {
  29148. return node && node.nodeType === Node.DOCUMENT_TYPE_NODE;
  29149. }
  29150. /**
  29151. * Returns true if the node is an element
  29152. * @param {Node} node
  29153. * @returns {boolean}
  29154. */
  29155. function isElementNode(node) {
  29156. return node && node.nodeType === Node.ELEMENT_NODE;
  29157. }
  29158. /**
  29159. * Returns true if `node` is a text node
  29160. * @param {Node} node
  29161. * @returns {boolean}
  29162. */
  29163. function isTextNode(node) {
  29164. return node && node.nodeType === Node.TEXT_NODE;
  29165. }
  29166. /**
  29167. * Check if en element node can be inserted before `child`, or at the end if child is falsy,
  29168. * according to the presence and position of a doctype node on the same level.
  29169. *
  29170. * @param {Document} doc The document node
  29171. * @param {Node} child the node that would become the nextSibling if the element would be inserted
  29172. * @returns {boolean} `true` if an element can be inserted before child
  29173. * @private
  29174. * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  29175. */
  29176. function isElementInsertionPossible(doc, child) {
  29177. var parentChildNodes = doc.childNodes || [];
  29178. if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) {
  29179. return false;
  29180. }
  29181. var docTypeNode = find(parentChildNodes, isDocTypeNode);
  29182. return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));
  29183. }
  29184. /**
  29185. * Check if en element node can be inserted before `child`, or at the end if child is falsy,
  29186. * according to the presence and position of a doctype node on the same level.
  29187. *
  29188. * @param {Node} doc The document node
  29189. * @param {Node} child the node that would become the nextSibling if the element would be inserted
  29190. * @returns {boolean} `true` if an element can be inserted before child
  29191. * @private
  29192. * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  29193. */
  29194. function isElementReplacementPossible(doc, child) {
  29195. var parentChildNodes = doc.childNodes || [];
  29196. function hasElementChildThatIsNotChild(node) {
  29197. return isElementNode(node) && node !== child;
  29198. }
  29199. if (find(parentChildNodes, hasElementChildThatIsNotChild)) {
  29200. return false;
  29201. }
  29202. var docTypeNode = find(parentChildNodes, isDocTypeNode);
  29203. return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));
  29204. }
  29205. /**
  29206. * @private
  29207. * Steps 1-5 of the checks before inserting and before replacing a child are the same.
  29208. *
  29209. * @param {Node} parent the parent node to insert `node` into
  29210. * @param {Node} node the node to insert
  29211. * @param {Node=} child the node that should become the `nextSibling` of `node`
  29212. * @returns {Node}
  29213. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  29214. * @throws DOMException if `child` is provided but is not a child of `parent`.
  29215. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  29216. * @see https://dom.spec.whatwg.org/#concept-node-replace
  29217. */
  29218. function assertPreInsertionValidity1to5(parent, node, child) {
  29219. // 1. If `parent` is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException.
  29220. if (!hasValidParentNodeType(parent)) {
  29221. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Unexpected parent node type ' + parent.nodeType);
  29222. }
  29223. // 2. If `node` is a host-including inclusive ancestor of `parent`, then throw a "HierarchyRequestError" DOMException.
  29224. // not implemented!
  29225. // 3. If `child` is non-null and its parent is not `parent`, then throw a "NotFoundError" DOMException.
  29226. if (child && child.parentNode !== parent) {
  29227. throw new DOMException(NOT_FOUND_ERR, 'child not in parent');
  29228. }
  29229. if (
  29230. // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
  29231. !hasInsertableNodeType(node) ||
  29232. // 5. If either `node` is a Text node and `parent` is a document,
  29233. // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0
  29234. // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE)
  29235. // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException.
  29236. isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE) {
  29237. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Unexpected node type ' + node.nodeType + ' for parent node type ' + parent.nodeType);
  29238. }
  29239. }
  29240. /**
  29241. * @private
  29242. * Step 6 of the checks before inserting and before replacing a child are different.
  29243. *
  29244. * @param {Document} parent the parent node to insert `node` into
  29245. * @param {Node} node the node to insert
  29246. * @param {Node | undefined} child the node that should become the `nextSibling` of `node`
  29247. * @returns {Node}
  29248. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  29249. * @throws DOMException if `child` is provided but is not a child of `parent`.
  29250. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  29251. * @see https://dom.spec.whatwg.org/#concept-node-replace
  29252. */
  29253. function assertPreInsertionValidityInDocument(parent, node, child) {
  29254. var parentChildNodes = parent.childNodes || [];
  29255. var nodeChildNodes = node.childNodes || [];
  29256. // DocumentFragment
  29257. if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
  29258. var nodeChildElements = nodeChildNodes.filter(isElementNode);
  29259. // If node has more than one element child or has a Text node child.
  29260. if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) {
  29261. throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment');
  29262. }
  29263. // Otherwise, if `node` has one element child and either `parent` has an element child,
  29264. // `child` is a doctype, or `child` is non-null and a doctype is following `child`.
  29265. if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) {
  29266. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype');
  29267. }
  29268. }
  29269. // Element
  29270. if (isElementNode(node)) {
  29271. // `parent` has an element child, `child` is a doctype,
  29272. // or `child` is non-null and a doctype is following `child`.
  29273. if (!isElementInsertionPossible(parent, child)) {
  29274. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype');
  29275. }
  29276. }
  29277. // DocumentType
  29278. if (isDocTypeNode(node)) {
  29279. // `parent` has a doctype child,
  29280. if (find(parentChildNodes, isDocTypeNode)) {
  29281. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed');
  29282. }
  29283. var parentElementChild = find(parentChildNodes, isElementNode);
  29284. // `child` is non-null and an element is preceding `child`,
  29285. if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {
  29286. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element');
  29287. }
  29288. // or `child` is null and `parent` has an element child.
  29289. if (!child && parentElementChild) {
  29290. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can not be appended since element is present');
  29291. }
  29292. }
  29293. }
  29294. /**
  29295. * @private
  29296. * Step 6 of the checks before inserting and before replacing a child are different.
  29297. *
  29298. * @param {Document} parent the parent node to insert `node` into
  29299. * @param {Node} node the node to insert
  29300. * @param {Node | undefined} child the node that should become the `nextSibling` of `node`
  29301. * @returns {Node}
  29302. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  29303. * @throws DOMException if `child` is provided but is not a child of `parent`.
  29304. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  29305. * @see https://dom.spec.whatwg.org/#concept-node-replace
  29306. */
  29307. function assertPreReplacementValidityInDocument(parent, node, child) {
  29308. var parentChildNodes = parent.childNodes || [];
  29309. var nodeChildNodes = node.childNodes || [];
  29310. // DocumentFragment
  29311. if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
  29312. var nodeChildElements = nodeChildNodes.filter(isElementNode);
  29313. // If `node` has more than one element child or has a Text node child.
  29314. if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) {
  29315. throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment');
  29316. }
  29317. // Otherwise, if `node` has one element child and either `parent` has an element child that is not `child` or a doctype is following `child`.
  29318. if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) {
  29319. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype');
  29320. }
  29321. }
  29322. // Element
  29323. if (isElementNode(node)) {
  29324. // `parent` has an element child that is not `child` or a doctype is following `child`.
  29325. if (!isElementReplacementPossible(parent, child)) {
  29326. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype');
  29327. }
  29328. }
  29329. // DocumentType
  29330. if (isDocTypeNode(node)) {
  29331. function hasDoctypeChildThatIsNotChild(node) {
  29332. return isDocTypeNode(node) && node !== child;
  29333. }
  29334. // `parent` has a doctype child that is not `child`,
  29335. if (find(parentChildNodes, hasDoctypeChildThatIsNotChild)) {
  29336. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed');
  29337. }
  29338. var parentElementChild = find(parentChildNodes, isElementNode);
  29339. // or an element is preceding `child`.
  29340. if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {
  29341. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element');
  29342. }
  29343. }
  29344. }
  29345. /**
  29346. * @private
  29347. * @param {Node} parent the parent node to insert `node` into
  29348. * @param {Node} node the node to insert
  29349. * @param {Node=} child the node that should become the `nextSibling` of `node`
  29350. * @returns {Node}
  29351. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  29352. * @throws DOMException if `child` is provided but is not a child of `parent`.
  29353. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  29354. */
  29355. function _insertBefore(parent, node, child, _inDocumentAssertion) {
  29356. // To ensure pre-insertion validity of a node into a parent before a child, run these steps:
  29357. assertPreInsertionValidity1to5(parent, node, child);
  29358. // If parent is a document, and any of the statements below, switched on the interface node implements,
  29359. // are true, then throw a "HierarchyRequestError" DOMException.
  29360. if (parent.nodeType === Node.DOCUMENT_NODE) {
  29361. (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child);
  29362. }
  29363. var cp = node.parentNode;
  29364. if (cp) {
  29365. cp.removeChild(node); //remove and update
  29366. }
  29367. if (node.nodeType === DOCUMENT_FRAGMENT_NODE) {
  29368. var newFirst = node.firstChild;
  29369. if (newFirst == null) {
  29370. return node;
  29371. }
  29372. var newLast = node.lastChild;
  29373. } else {
  29374. newFirst = newLast = node;
  29375. }
  29376. var pre = child ? child.previousSibling : parent.lastChild;
  29377. newFirst.previousSibling = pre;
  29378. newLast.nextSibling = child;
  29379. if (pre) {
  29380. pre.nextSibling = newFirst;
  29381. } else {
  29382. parent.firstChild = newFirst;
  29383. }
  29384. if (child == null) {
  29385. parent.lastChild = newLast;
  29386. } else {
  29387. child.previousSibling = newLast;
  29388. }
  29389. do {
  29390. newFirst.parentNode = parent;
  29391. } while (newFirst !== newLast && (newFirst = newFirst.nextSibling));
  29392. _onUpdateChild(parent.ownerDocument || parent, parent);
  29393. //console.log(parent.lastChild.nextSibling == null)
  29394. if (node.nodeType == DOCUMENT_FRAGMENT_NODE) {
  29395. node.firstChild = node.lastChild = null;
  29396. }
  29397. return node;
  29398. }
  29399. /**
  29400. * Appends `newChild` to `parentNode`.
  29401. * If `newChild` is already connected to a `parentNode` it is first removed from it.
  29402. *
  29403. * @see https://github.com/xmldom/xmldom/issues/135
  29404. * @see https://github.com/xmldom/xmldom/issues/145
  29405. * @param {Node} parentNode
  29406. * @param {Node} newChild
  29407. * @returns {Node}
  29408. * @private
  29409. */
  29410. function _appendSingleChild(parentNode, newChild) {
  29411. if (newChild.parentNode) {
  29412. newChild.parentNode.removeChild(newChild);
  29413. }
  29414. newChild.parentNode = parentNode;
  29415. newChild.previousSibling = parentNode.lastChild;
  29416. newChild.nextSibling = null;
  29417. if (newChild.previousSibling) {
  29418. newChild.previousSibling.nextSibling = newChild;
  29419. } else {
  29420. parentNode.firstChild = newChild;
  29421. }
  29422. parentNode.lastChild = newChild;
  29423. _onUpdateChild(parentNode.ownerDocument, parentNode, newChild);
  29424. return newChild;
  29425. }
  29426. Document.prototype = {
  29427. //implementation : null,
  29428. nodeName: '#document',
  29429. nodeType: DOCUMENT_NODE,
  29430. /**
  29431. * The DocumentType node of the document.
  29432. *
  29433. * @readonly
  29434. * @type DocumentType
  29435. */
  29436. doctype: null,
  29437. documentElement: null,
  29438. _inc: 1,
  29439. insertBefore: function (newChild, refChild) {
  29440. //raises
  29441. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  29442. var child = newChild.firstChild;
  29443. while (child) {
  29444. var next = child.nextSibling;
  29445. this.insertBefore(child, refChild);
  29446. child = next;
  29447. }
  29448. return newChild;
  29449. }
  29450. _insertBefore(this, newChild, refChild);
  29451. newChild.ownerDocument = this;
  29452. if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) {
  29453. this.documentElement = newChild;
  29454. }
  29455. return newChild;
  29456. },
  29457. removeChild: function (oldChild) {
  29458. if (this.documentElement == oldChild) {
  29459. this.documentElement = null;
  29460. }
  29461. return _removeChild(this, oldChild);
  29462. },
  29463. replaceChild: function (newChild, oldChild) {
  29464. //raises
  29465. _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);
  29466. newChild.ownerDocument = this;
  29467. if (oldChild) {
  29468. this.removeChild(oldChild);
  29469. }
  29470. if (isElementNode(newChild)) {
  29471. this.documentElement = newChild;
  29472. }
  29473. },
  29474. // Introduced in DOM Level 2:
  29475. importNode: function (importedNode, deep) {
  29476. return importNode(this, importedNode, deep);
  29477. },
  29478. // Introduced in DOM Level 2:
  29479. getElementById: function (id) {
  29480. var rtv = null;
  29481. _visitNode(this.documentElement, function (node) {
  29482. if (node.nodeType == ELEMENT_NODE) {
  29483. if (node.getAttribute('id') == id) {
  29484. rtv = node;
  29485. return true;
  29486. }
  29487. }
  29488. });
  29489. return rtv;
  29490. },
  29491. /**
  29492. * The `getElementsByClassName` method of `Document` interface returns an array-like object
  29493. * of all child elements which have **all** of the given class name(s).
  29494. *
  29495. * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters.
  29496. *
  29497. *
  29498. * Warning: This is a live LiveNodeList.
  29499. * Changes in the DOM will reflect in the array as the changes occur.
  29500. * If an element selected by this array no longer qualifies for the selector,
  29501. * it will automatically be removed. Be aware of this for iteration purposes.
  29502. *
  29503. * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace
  29504. *
  29505. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
  29506. * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname
  29507. */
  29508. getElementsByClassName: function (classNames) {
  29509. var classNamesSet = toOrderedSet(classNames);
  29510. return new LiveNodeList(this, function (base) {
  29511. var ls = [];
  29512. if (classNamesSet.length > 0) {
  29513. _visitNode(base.documentElement, function (node) {
  29514. if (node !== base && node.nodeType === ELEMENT_NODE) {
  29515. var nodeClassNames = node.getAttribute('class');
  29516. // can be null if the attribute does not exist
  29517. if (nodeClassNames) {
  29518. // before splitting and iterating just compare them for the most common case
  29519. var matches = classNames === nodeClassNames;
  29520. if (!matches) {
  29521. var nodeClassNamesSet = toOrderedSet(nodeClassNames);
  29522. matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet));
  29523. }
  29524. if (matches) {
  29525. ls.push(node);
  29526. }
  29527. }
  29528. }
  29529. });
  29530. }
  29531. return ls;
  29532. });
  29533. },
  29534. //document factory method:
  29535. createElement: function (tagName) {
  29536. var node = new Element();
  29537. node.ownerDocument = this;
  29538. node.nodeName = tagName;
  29539. node.tagName = tagName;
  29540. node.localName = tagName;
  29541. node.childNodes = new NodeList();
  29542. var attrs = node.attributes = new NamedNodeMap();
  29543. attrs._ownerElement = node;
  29544. return node;
  29545. },
  29546. createDocumentFragment: function () {
  29547. var node = new DocumentFragment();
  29548. node.ownerDocument = this;
  29549. node.childNodes = new NodeList();
  29550. return node;
  29551. },
  29552. createTextNode: function (data) {
  29553. var node = new Text();
  29554. node.ownerDocument = this;
  29555. node.appendData(data);
  29556. return node;
  29557. },
  29558. createComment: function (data) {
  29559. var node = new Comment();
  29560. node.ownerDocument = this;
  29561. node.appendData(data);
  29562. return node;
  29563. },
  29564. createCDATASection: function (data) {
  29565. var node = new CDATASection();
  29566. node.ownerDocument = this;
  29567. node.appendData(data);
  29568. return node;
  29569. },
  29570. createProcessingInstruction: function (target, data) {
  29571. var node = new ProcessingInstruction();
  29572. node.ownerDocument = this;
  29573. node.tagName = node.target = target;
  29574. node.nodeValue = node.data = data;
  29575. return node;
  29576. },
  29577. createAttribute: function (name) {
  29578. var node = new Attr();
  29579. node.ownerDocument = this;
  29580. node.name = name;
  29581. node.nodeName = name;
  29582. node.localName = name;
  29583. node.specified = true;
  29584. return node;
  29585. },
  29586. createEntityReference: function (name) {
  29587. var node = new EntityReference();
  29588. node.ownerDocument = this;
  29589. node.nodeName = name;
  29590. return node;
  29591. },
  29592. // Introduced in DOM Level 2:
  29593. createElementNS: function (namespaceURI, qualifiedName) {
  29594. var node = new Element();
  29595. var pl = qualifiedName.split(':');
  29596. var attrs = node.attributes = new NamedNodeMap();
  29597. node.childNodes = new NodeList();
  29598. node.ownerDocument = this;
  29599. node.nodeName = qualifiedName;
  29600. node.tagName = qualifiedName;
  29601. node.namespaceURI = namespaceURI;
  29602. if (pl.length == 2) {
  29603. node.prefix = pl[0];
  29604. node.localName = pl[1];
  29605. } else {
  29606. //el.prefix = null;
  29607. node.localName = qualifiedName;
  29608. }
  29609. attrs._ownerElement = node;
  29610. return node;
  29611. },
  29612. // Introduced in DOM Level 2:
  29613. createAttributeNS: function (namespaceURI, qualifiedName) {
  29614. var node = new Attr();
  29615. var pl = qualifiedName.split(':');
  29616. node.ownerDocument = this;
  29617. node.nodeName = qualifiedName;
  29618. node.name = qualifiedName;
  29619. node.namespaceURI = namespaceURI;
  29620. node.specified = true;
  29621. if (pl.length == 2) {
  29622. node.prefix = pl[0];
  29623. node.localName = pl[1];
  29624. } else {
  29625. //el.prefix = null;
  29626. node.localName = qualifiedName;
  29627. }
  29628. return node;
  29629. }
  29630. };
  29631. _extends(Document, Node);
  29632. function Element() {
  29633. this._nsMap = {};
  29634. }
  29635. Element.prototype = {
  29636. nodeType: ELEMENT_NODE,
  29637. hasAttribute: function (name) {
  29638. return this.getAttributeNode(name) != null;
  29639. },
  29640. getAttribute: function (name) {
  29641. var attr = this.getAttributeNode(name);
  29642. return attr && attr.value || '';
  29643. },
  29644. getAttributeNode: function (name) {
  29645. return this.attributes.getNamedItem(name);
  29646. },
  29647. setAttribute: function (name, value) {
  29648. var attr = this.ownerDocument.createAttribute(name);
  29649. attr.value = attr.nodeValue = "" + value;
  29650. this.setAttributeNode(attr);
  29651. },
  29652. removeAttribute: function (name) {
  29653. var attr = this.getAttributeNode(name);
  29654. attr && this.removeAttributeNode(attr);
  29655. },
  29656. //four real opeartion method
  29657. appendChild: function (newChild) {
  29658. if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
  29659. return this.insertBefore(newChild, null);
  29660. } else {
  29661. return _appendSingleChild(this, newChild);
  29662. }
  29663. },
  29664. setAttributeNode: function (newAttr) {
  29665. return this.attributes.setNamedItem(newAttr);
  29666. },
  29667. setAttributeNodeNS: function (newAttr) {
  29668. return this.attributes.setNamedItemNS(newAttr);
  29669. },
  29670. removeAttributeNode: function (oldAttr) {
  29671. //console.log(this == oldAttr.ownerElement)
  29672. return this.attributes.removeNamedItem(oldAttr.nodeName);
  29673. },
  29674. //get real attribute name,and remove it by removeAttributeNode
  29675. removeAttributeNS: function (namespaceURI, localName) {
  29676. var old = this.getAttributeNodeNS(namespaceURI, localName);
  29677. old && this.removeAttributeNode(old);
  29678. },
  29679. hasAttributeNS: function (namespaceURI, localName) {
  29680. return this.getAttributeNodeNS(namespaceURI, localName) != null;
  29681. },
  29682. getAttributeNS: function (namespaceURI, localName) {
  29683. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  29684. return attr && attr.value || '';
  29685. },
  29686. setAttributeNS: function (namespaceURI, qualifiedName, value) {
  29687. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  29688. attr.value = attr.nodeValue = "" + value;
  29689. this.setAttributeNode(attr);
  29690. },
  29691. getAttributeNodeNS: function (namespaceURI, localName) {
  29692. return this.attributes.getNamedItemNS(namespaceURI, localName);
  29693. },
  29694. getElementsByTagName: function (tagName) {
  29695. return new LiveNodeList(this, function (base) {
  29696. var ls = [];
  29697. _visitNode(base, function (node) {
  29698. if (node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)) {
  29699. ls.push(node);
  29700. }
  29701. });
  29702. return ls;
  29703. });
  29704. },
  29705. getElementsByTagNameNS: function (namespaceURI, localName) {
  29706. return new LiveNodeList(this, function (base) {
  29707. var ls = [];
  29708. _visitNode(base, function (node) {
  29709. if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)) {
  29710. ls.push(node);
  29711. }
  29712. });
  29713. return ls;
  29714. });
  29715. }
  29716. };
  29717. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  29718. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  29719. _extends(Element, Node);
  29720. function Attr() {}
  29721. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  29722. _extends(Attr, Node);
  29723. function CharacterData() {}
  29724. CharacterData.prototype = {
  29725. data: '',
  29726. substringData: function (offset, count) {
  29727. return this.data.substring(offset, offset + count);
  29728. },
  29729. appendData: function (text) {
  29730. text = this.data + text;
  29731. this.nodeValue = this.data = text;
  29732. this.length = text.length;
  29733. },
  29734. insertData: function (offset, text) {
  29735. this.replaceData(offset, 0, text);
  29736. },
  29737. appendChild: function (newChild) {
  29738. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]);
  29739. },
  29740. deleteData: function (offset, count) {
  29741. this.replaceData(offset, count, "");
  29742. },
  29743. replaceData: function (offset, count, text) {
  29744. var start = this.data.substring(0, offset);
  29745. var end = this.data.substring(offset + count);
  29746. text = start + text + end;
  29747. this.nodeValue = this.data = text;
  29748. this.length = text.length;
  29749. }
  29750. };
  29751. _extends(CharacterData, Node);
  29752. function Text() {}
  29753. Text.prototype = {
  29754. nodeName: "#text",
  29755. nodeType: TEXT_NODE,
  29756. splitText: function (offset) {
  29757. var text = this.data;
  29758. var newText = text.substring(offset);
  29759. text = text.substring(0, offset);
  29760. this.data = this.nodeValue = text;
  29761. this.length = text.length;
  29762. var newNode = this.ownerDocument.createTextNode(newText);
  29763. if (this.parentNode) {
  29764. this.parentNode.insertBefore(newNode, this.nextSibling);
  29765. }
  29766. return newNode;
  29767. }
  29768. };
  29769. _extends(Text, CharacterData);
  29770. function Comment() {}
  29771. Comment.prototype = {
  29772. nodeName: "#comment",
  29773. nodeType: COMMENT_NODE
  29774. };
  29775. _extends(Comment, CharacterData);
  29776. function CDATASection() {}
  29777. CDATASection.prototype = {
  29778. nodeName: "#cdata-section",
  29779. nodeType: CDATA_SECTION_NODE
  29780. };
  29781. _extends(CDATASection, CharacterData);
  29782. function DocumentType() {}
  29783. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  29784. _extends(DocumentType, Node);
  29785. function Notation() {}
  29786. Notation.prototype.nodeType = NOTATION_NODE;
  29787. _extends(Notation, Node);
  29788. function Entity() {}
  29789. Entity.prototype.nodeType = ENTITY_NODE;
  29790. _extends(Entity, Node);
  29791. function EntityReference() {}
  29792. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  29793. _extends(EntityReference, Node);
  29794. function DocumentFragment() {}
  29795. DocumentFragment.prototype.nodeName = "#document-fragment";
  29796. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  29797. _extends(DocumentFragment, Node);
  29798. function ProcessingInstruction() {}
  29799. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  29800. _extends(ProcessingInstruction, Node);
  29801. function XMLSerializer() {}
  29802. XMLSerializer.prototype.serializeToString = function (node, isHtml, nodeFilter) {
  29803. return nodeSerializeToString.call(node, isHtml, nodeFilter);
  29804. };
  29805. Node.prototype.toString = nodeSerializeToString;
  29806. function nodeSerializeToString(isHtml, nodeFilter) {
  29807. var buf = [];
  29808. var refNode = this.nodeType == 9 && this.documentElement || this;
  29809. var prefix = refNode.prefix;
  29810. var uri = refNode.namespaceURI;
  29811. if (uri && prefix == null) {
  29812. //console.log(prefix)
  29813. var prefix = refNode.lookupPrefix(uri);
  29814. if (prefix == null) {
  29815. //isHTML = true;
  29816. var visibleNamespaces = [{
  29817. namespace: uri,
  29818. prefix: null
  29819. }
  29820. //{namespace:uri,prefix:''}
  29821. ];
  29822. }
  29823. }
  29824. serializeToString(this, buf, isHtml, nodeFilter, visibleNamespaces);
  29825. //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  29826. return buf.join('');
  29827. }
  29828. function needNamespaceDefine(node, isHTML, visibleNamespaces) {
  29829. var prefix = node.prefix || '';
  29830. var uri = node.namespaceURI;
  29831. // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) ,
  29832. // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl :
  29833. // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty.
  29834. // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using)
  29835. // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared :
  29836. // > [...] Furthermore, the attribute value [...] must not be an empty string.
  29837. // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document.
  29838. if (!uri) {
  29839. return false;
  29840. }
  29841. if (prefix === "xml" && uri === NAMESPACE$2.XML || uri === NAMESPACE$2.XMLNS) {
  29842. return false;
  29843. }
  29844. var i = visibleNamespaces.length;
  29845. while (i--) {
  29846. var ns = visibleNamespaces[i];
  29847. // get namespace prefix
  29848. if (ns.prefix === prefix) {
  29849. return ns.namespace !== uri;
  29850. }
  29851. }
  29852. return true;
  29853. }
  29854. /**
  29855. * Well-formed constraint: No < in Attribute Values
  29856. * > The replacement text of any entity referred to directly or indirectly
  29857. * > in an attribute value must not contain a <.
  29858. * @see https://www.w3.org/TR/xml11/#CleanAttrVals
  29859. * @see https://www.w3.org/TR/xml11/#NT-AttValue
  29860. *
  29861. * Literal whitespace other than space that appear in attribute values
  29862. * are serialized as their entity references, so they will be preserved.
  29863. * (In contrast to whitespace literals in the input which are normalized to spaces)
  29864. * @see https://www.w3.org/TR/xml11/#AVNormalize
  29865. * @see https://w3c.github.io/DOM-Parsing/#serializing-an-element-s-attributes
  29866. */
  29867. function addSerializedAttribute(buf, qualifiedName, value) {
  29868. buf.push(' ', qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"');
  29869. }
  29870. function serializeToString(node, buf, isHTML, nodeFilter, visibleNamespaces) {
  29871. if (!visibleNamespaces) {
  29872. visibleNamespaces = [];
  29873. }
  29874. if (nodeFilter) {
  29875. node = nodeFilter(node);
  29876. if (node) {
  29877. if (typeof node == 'string') {
  29878. buf.push(node);
  29879. return;
  29880. }
  29881. } else {
  29882. return;
  29883. }
  29884. //buf.sort.apply(attrs, attributeSorter);
  29885. }
  29886. switch (node.nodeType) {
  29887. case ELEMENT_NODE:
  29888. var attrs = node.attributes;
  29889. var len = attrs.length;
  29890. var child = node.firstChild;
  29891. var nodeName = node.tagName;
  29892. isHTML = NAMESPACE$2.isHTML(node.namespaceURI) || isHTML;
  29893. var prefixedNodeName = nodeName;
  29894. if (!isHTML && !node.prefix && node.namespaceURI) {
  29895. var defaultNS;
  29896. // lookup current default ns from `xmlns` attribute
  29897. for (var ai = 0; ai < attrs.length; ai++) {
  29898. if (attrs.item(ai).name === 'xmlns') {
  29899. defaultNS = attrs.item(ai).value;
  29900. break;
  29901. }
  29902. }
  29903. if (!defaultNS) {
  29904. // lookup current default ns in visibleNamespaces
  29905. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  29906. var namespace = visibleNamespaces[nsi];
  29907. if (namespace.prefix === '' && namespace.namespace === node.namespaceURI) {
  29908. defaultNS = namespace.namespace;
  29909. break;
  29910. }
  29911. }
  29912. }
  29913. if (defaultNS !== node.namespaceURI) {
  29914. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  29915. var namespace = visibleNamespaces[nsi];
  29916. if (namespace.namespace === node.namespaceURI) {
  29917. if (namespace.prefix) {
  29918. prefixedNodeName = namespace.prefix + ':' + nodeName;
  29919. }
  29920. break;
  29921. }
  29922. }
  29923. }
  29924. }
  29925. buf.push('<', prefixedNodeName);
  29926. for (var i = 0; i < len; i++) {
  29927. // add namespaces for attributes
  29928. var attr = attrs.item(i);
  29929. if (attr.prefix == 'xmlns') {
  29930. visibleNamespaces.push({
  29931. prefix: attr.localName,
  29932. namespace: attr.value
  29933. });
  29934. } else if (attr.nodeName == 'xmlns') {
  29935. visibleNamespaces.push({
  29936. prefix: '',
  29937. namespace: attr.value
  29938. });
  29939. }
  29940. }
  29941. for (var i = 0; i < len; i++) {
  29942. var attr = attrs.item(i);
  29943. if (needNamespaceDefine(attr, isHTML, visibleNamespaces)) {
  29944. var prefix = attr.prefix || '';
  29945. var uri = attr.namespaceURI;
  29946. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  29947. visibleNamespaces.push({
  29948. prefix: prefix,
  29949. namespace: uri
  29950. });
  29951. }
  29952. serializeToString(attr, buf, isHTML, nodeFilter, visibleNamespaces);
  29953. }
  29954. // add namespace for current node
  29955. if (nodeName === prefixedNodeName && needNamespaceDefine(node, isHTML, visibleNamespaces)) {
  29956. var prefix = node.prefix || '';
  29957. var uri = node.namespaceURI;
  29958. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  29959. visibleNamespaces.push({
  29960. prefix: prefix,
  29961. namespace: uri
  29962. });
  29963. }
  29964. if (child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)) {
  29965. buf.push('>');
  29966. //if is cdata child node
  29967. if (isHTML && /^script$/i.test(nodeName)) {
  29968. while (child) {
  29969. if (child.data) {
  29970. buf.push(child.data);
  29971. } else {
  29972. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  29973. }
  29974. child = child.nextSibling;
  29975. }
  29976. } else {
  29977. while (child) {
  29978. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  29979. child = child.nextSibling;
  29980. }
  29981. }
  29982. buf.push('</', prefixedNodeName, '>');
  29983. } else {
  29984. buf.push('/>');
  29985. }
  29986. // remove added visible namespaces
  29987. //visibleNamespaces.length = startVisibleNamespaces;
  29988. return;
  29989. case DOCUMENT_NODE:
  29990. case DOCUMENT_FRAGMENT_NODE:
  29991. var child = node.firstChild;
  29992. while (child) {
  29993. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  29994. child = child.nextSibling;
  29995. }
  29996. return;
  29997. case ATTRIBUTE_NODE:
  29998. return addSerializedAttribute(buf, node.name, node.value);
  29999. case TEXT_NODE:
  30000. /**
  30001. * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
  30002. * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
  30003. * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
  30004. * `&amp;` and `&lt;` respectively.
  30005. * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
  30006. * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
  30007. * when that string is not marking the end of a CDATA section.
  30008. *
  30009. * In the content of elements, character data is any string of characters
  30010. * which does not contain the start-delimiter of any markup
  30011. * and does not include the CDATA-section-close delimiter, `]]>`.
  30012. *
  30013. * @see https://www.w3.org/TR/xml/#NT-CharData
  30014. * @see https://w3c.github.io/DOM-Parsing/#xml-serializing-a-text-node
  30015. */
  30016. return buf.push(node.data.replace(/[<&>]/g, _xmlEncoder));
  30017. case CDATA_SECTION_NODE:
  30018. return buf.push('<![CDATA[', node.data, ']]>');
  30019. case COMMENT_NODE:
  30020. return buf.push("<!--", node.data, "-->");
  30021. case DOCUMENT_TYPE_NODE:
  30022. var pubid = node.publicId;
  30023. var sysid = node.systemId;
  30024. buf.push('<!DOCTYPE ', node.name);
  30025. if (pubid) {
  30026. buf.push(' PUBLIC ', pubid);
  30027. if (sysid && sysid != '.') {
  30028. buf.push(' ', sysid);
  30029. }
  30030. buf.push('>');
  30031. } else if (sysid && sysid != '.') {
  30032. buf.push(' SYSTEM ', sysid, '>');
  30033. } else {
  30034. var sub = node.internalSubset;
  30035. if (sub) {
  30036. buf.push(" [", sub, "]");
  30037. }
  30038. buf.push(">");
  30039. }
  30040. return;
  30041. case PROCESSING_INSTRUCTION_NODE:
  30042. return buf.push("<?", node.target, " ", node.data, "?>");
  30043. case ENTITY_REFERENCE_NODE:
  30044. return buf.push('&', node.nodeName, ';');
  30045. //case ENTITY_NODE:
  30046. //case NOTATION_NODE:
  30047. default:
  30048. buf.push('??', node.nodeName);
  30049. }
  30050. }
  30051. function importNode(doc, node, deep) {
  30052. var node2;
  30053. switch (node.nodeType) {
  30054. case ELEMENT_NODE:
  30055. node2 = node.cloneNode(false);
  30056. node2.ownerDocument = doc;
  30057. //var attrs = node2.attributes;
  30058. //var len = attrs.length;
  30059. //for(var i=0;i<len;i++){
  30060. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  30061. //}
  30062. case DOCUMENT_FRAGMENT_NODE:
  30063. break;
  30064. case ATTRIBUTE_NODE:
  30065. deep = true;
  30066. break;
  30067. //case ENTITY_REFERENCE_NODE:
  30068. //case PROCESSING_INSTRUCTION_NODE:
  30069. ////case TEXT_NODE:
  30070. //case CDATA_SECTION_NODE:
  30071. //case COMMENT_NODE:
  30072. // deep = false;
  30073. // break;
  30074. //case DOCUMENT_NODE:
  30075. //case DOCUMENT_TYPE_NODE:
  30076. //cannot be imported.
  30077. //case ENTITY_NODE:
  30078. //case NOTATION_NODE:
  30079. //can not hit in level3
  30080. //default:throw e;
  30081. }
  30082. if (!node2) {
  30083. node2 = node.cloneNode(false); //false
  30084. }
  30085. node2.ownerDocument = doc;
  30086. node2.parentNode = null;
  30087. if (deep) {
  30088. var child = node.firstChild;
  30089. while (child) {
  30090. node2.appendChild(importNode(doc, child, deep));
  30091. child = child.nextSibling;
  30092. }
  30093. }
  30094. return node2;
  30095. }
  30096. //
  30097. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  30098. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  30099. function cloneNode(doc, node, deep) {
  30100. var node2 = new node.constructor();
  30101. for (var n in node) {
  30102. if (Object.prototype.hasOwnProperty.call(node, n)) {
  30103. var v = node[n];
  30104. if (typeof v != "object") {
  30105. if (v != node2[n]) {
  30106. node2[n] = v;
  30107. }
  30108. }
  30109. }
  30110. }
  30111. if (node.childNodes) {
  30112. node2.childNodes = new NodeList();
  30113. }
  30114. node2.ownerDocument = doc;
  30115. switch (node2.nodeType) {
  30116. case ELEMENT_NODE:
  30117. var attrs = node.attributes;
  30118. var attrs2 = node2.attributes = new NamedNodeMap();
  30119. var len = attrs.length;
  30120. attrs2._ownerElement = node2;
  30121. for (var i = 0; i < len; i++) {
  30122. node2.setAttributeNode(cloneNode(doc, attrs.item(i), true));
  30123. }
  30124. break;
  30125. case ATTRIBUTE_NODE:
  30126. deep = true;
  30127. }
  30128. if (deep) {
  30129. var child = node.firstChild;
  30130. while (child) {
  30131. node2.appendChild(cloneNode(doc, child, deep));
  30132. child = child.nextSibling;
  30133. }
  30134. }
  30135. return node2;
  30136. }
  30137. function __set__(object, key, value) {
  30138. object[key] = value;
  30139. }
  30140. //do dynamic
  30141. try {
  30142. if (Object.defineProperty) {
  30143. Object.defineProperty(LiveNodeList.prototype, 'length', {
  30144. get: function () {
  30145. _updateLiveList(this);
  30146. return this.$$length;
  30147. }
  30148. });
  30149. Object.defineProperty(Node.prototype, 'textContent', {
  30150. get: function () {
  30151. return getTextContent(this);
  30152. },
  30153. set: function (data) {
  30154. switch (this.nodeType) {
  30155. case ELEMENT_NODE:
  30156. case DOCUMENT_FRAGMENT_NODE:
  30157. while (this.firstChild) {
  30158. this.removeChild(this.firstChild);
  30159. }
  30160. if (data || String(data)) {
  30161. this.appendChild(this.ownerDocument.createTextNode(data));
  30162. }
  30163. break;
  30164. default:
  30165. this.data = data;
  30166. this.value = data;
  30167. this.nodeValue = data;
  30168. }
  30169. }
  30170. });
  30171. function getTextContent(node) {
  30172. switch (node.nodeType) {
  30173. case ELEMENT_NODE:
  30174. case DOCUMENT_FRAGMENT_NODE:
  30175. var buf = [];
  30176. node = node.firstChild;
  30177. while (node) {
  30178. if (node.nodeType !== 7 && node.nodeType !== 8) {
  30179. buf.push(getTextContent(node));
  30180. }
  30181. node = node.nextSibling;
  30182. }
  30183. return buf.join('');
  30184. default:
  30185. return node.nodeValue;
  30186. }
  30187. }
  30188. __set__ = function (object, key, value) {
  30189. //console.log(value)
  30190. object['$$' + key] = value;
  30191. };
  30192. }
  30193. } catch (e) {//ie8
  30194. }
  30195. //if(typeof require == 'function'){
  30196. var DocumentType_1 = DocumentType;
  30197. var DOMException_1 = DOMException;
  30198. var DOMImplementation_1 = DOMImplementation$1;
  30199. var Element_1 = Element;
  30200. var Node_1 = Node;
  30201. var NodeList_1 = NodeList;
  30202. var XMLSerializer_1 = XMLSerializer;
  30203. //}
  30204. var dom = {
  30205. DocumentType: DocumentType_1,
  30206. DOMException: DOMException_1,
  30207. DOMImplementation: DOMImplementation_1,
  30208. Element: Element_1,
  30209. Node: Node_1,
  30210. NodeList: NodeList_1,
  30211. XMLSerializer: XMLSerializer_1
  30212. };
  30213. var entities = createCommonjsModule(function (module, exports) {
  30214. var freeze = conventions.freeze;
  30215. /**
  30216. * The entities that are predefined in every XML document.
  30217. *
  30218. * @see https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-predefined-ent W3C XML 1.1
  30219. * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent W3C XML 1.0
  30220. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML Wikipedia
  30221. */
  30222. exports.XML_ENTITIES = freeze({
  30223. amp: '&',
  30224. apos: "'",
  30225. gt: '>',
  30226. lt: '<',
  30227. quot: '"'
  30228. });
  30229. /**
  30230. * A map of currently 241 entities that are detected in an HTML document.
  30231. * They contain all entries from `XML_ENTITIES`.
  30232. *
  30233. * @see XML_ENTITIES
  30234. * @see DOMParser.parseFromString
  30235. * @see DOMImplementation.prototype.createHTMLDocument
  30236. * @see https://html.spec.whatwg.org/#named-character-references WHATWG HTML(5) Spec
  30237. * @see https://www.w3.org/TR/xml-entity-names/ W3C XML Entity Names
  30238. * @see https://www.w3.org/TR/html4/sgml/entities.html W3C HTML4/SGML
  30239. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML Wikipedia (HTML)
  30240. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Entities_representing_special_characters_in_XHTML Wikpedia (XHTML)
  30241. */
  30242. exports.HTML_ENTITIES = freeze({
  30243. lt: '<',
  30244. gt: '>',
  30245. amp: '&',
  30246. quot: '"',
  30247. apos: "'",
  30248. Agrave: "À",
  30249. Aacute: "Á",
  30250. Acirc: "Â",
  30251. Atilde: "Ã",
  30252. Auml: "Ä",
  30253. Aring: "Å",
  30254. AElig: "Æ",
  30255. Ccedil: "Ç",
  30256. Egrave: "È",
  30257. Eacute: "É",
  30258. Ecirc: "Ê",
  30259. Euml: "Ë",
  30260. Igrave: "Ì",
  30261. Iacute: "Í",
  30262. Icirc: "Î",
  30263. Iuml: "Ï",
  30264. ETH: "Ð",
  30265. Ntilde: "Ñ",
  30266. Ograve: "Ò",
  30267. Oacute: "Ó",
  30268. Ocirc: "Ô",
  30269. Otilde: "Õ",
  30270. Ouml: "Ö",
  30271. Oslash: "Ø",
  30272. Ugrave: "Ù",
  30273. Uacute: "Ú",
  30274. Ucirc: "Û",
  30275. Uuml: "Ü",
  30276. Yacute: "Ý",
  30277. THORN: "Þ",
  30278. szlig: "ß",
  30279. agrave: "à",
  30280. aacute: "á",
  30281. acirc: "â",
  30282. atilde: "ã",
  30283. auml: "ä",
  30284. aring: "å",
  30285. aelig: "æ",
  30286. ccedil: "ç",
  30287. egrave: "è",
  30288. eacute: "é",
  30289. ecirc: "ê",
  30290. euml: "ë",
  30291. igrave: "ì",
  30292. iacute: "í",
  30293. icirc: "î",
  30294. iuml: "ï",
  30295. eth: "ð",
  30296. ntilde: "ñ",
  30297. ograve: "ò",
  30298. oacute: "ó",
  30299. ocirc: "ô",
  30300. otilde: "õ",
  30301. ouml: "ö",
  30302. oslash: "ø",
  30303. ugrave: "ù",
  30304. uacute: "ú",
  30305. ucirc: "û",
  30306. uuml: "ü",
  30307. yacute: "ý",
  30308. thorn: "þ",
  30309. yuml: "ÿ",
  30310. nbsp: "\u00a0",
  30311. iexcl: "¡",
  30312. cent: "¢",
  30313. pound: "£",
  30314. curren: "¤",
  30315. yen: "¥",
  30316. brvbar: "¦",
  30317. sect: "§",
  30318. uml: "¨",
  30319. copy: "©",
  30320. ordf: "ª",
  30321. laquo: "«",
  30322. not: "¬",
  30323. shy: "­­",
  30324. reg: "®",
  30325. macr: "¯",
  30326. deg: "°",
  30327. plusmn: "±",
  30328. sup2: "²",
  30329. sup3: "³",
  30330. acute: "´",
  30331. micro: "µ",
  30332. para: "¶",
  30333. middot: "·",
  30334. cedil: "¸",
  30335. sup1: "¹",
  30336. ordm: "º",
  30337. raquo: "»",
  30338. frac14: "¼",
  30339. frac12: "½",
  30340. frac34: "¾",
  30341. iquest: "¿",
  30342. times: "×",
  30343. divide: "÷",
  30344. forall: "∀",
  30345. part: "∂",
  30346. exist: "∃",
  30347. empty: "∅",
  30348. nabla: "∇",
  30349. isin: "∈",
  30350. notin: "∉",
  30351. ni: "∋",
  30352. prod: "∏",
  30353. sum: "∑",
  30354. minus: "−",
  30355. lowast: "∗",
  30356. radic: "√",
  30357. prop: "∝",
  30358. infin: "∞",
  30359. ang: "∠",
  30360. and: "∧",
  30361. or: "∨",
  30362. cap: "∩",
  30363. cup: "∪",
  30364. 'int': "∫",
  30365. there4: "∴",
  30366. sim: "∼",
  30367. cong: "≅",
  30368. asymp: "≈",
  30369. ne: "≠",
  30370. equiv: "≡",
  30371. le: "≤",
  30372. ge: "≥",
  30373. sub: "⊂",
  30374. sup: "⊃",
  30375. nsub: "⊄",
  30376. sube: "⊆",
  30377. supe: "⊇",
  30378. oplus: "⊕",
  30379. otimes: "⊗",
  30380. perp: "⊥",
  30381. sdot: "⋅",
  30382. Alpha: "Α",
  30383. Beta: "Β",
  30384. Gamma: "Γ",
  30385. Delta: "Δ",
  30386. Epsilon: "Ε",
  30387. Zeta: "Ζ",
  30388. Eta: "Η",
  30389. Theta: "Θ",
  30390. Iota: "Ι",
  30391. Kappa: "Κ",
  30392. Lambda: "Λ",
  30393. Mu: "Μ",
  30394. Nu: "Ν",
  30395. Xi: "Ξ",
  30396. Omicron: "Ο",
  30397. Pi: "Π",
  30398. Rho: "Ρ",
  30399. Sigma: "Σ",
  30400. Tau: "Τ",
  30401. Upsilon: "Υ",
  30402. Phi: "Φ",
  30403. Chi: "Χ",
  30404. Psi: "Ψ",
  30405. Omega: "Ω",
  30406. alpha: "α",
  30407. beta: "β",
  30408. gamma: "γ",
  30409. delta: "δ",
  30410. epsilon: "ε",
  30411. zeta: "ζ",
  30412. eta: "η",
  30413. theta: "θ",
  30414. iota: "ι",
  30415. kappa: "κ",
  30416. lambda: "λ",
  30417. mu: "μ",
  30418. nu: "ν",
  30419. xi: "ξ",
  30420. omicron: "ο",
  30421. pi: "π",
  30422. rho: "ρ",
  30423. sigmaf: "ς",
  30424. sigma: "σ",
  30425. tau: "τ",
  30426. upsilon: "υ",
  30427. phi: "φ",
  30428. chi: "χ",
  30429. psi: "ψ",
  30430. omega: "ω",
  30431. thetasym: "ϑ",
  30432. upsih: "ϒ",
  30433. piv: "ϖ",
  30434. OElig: "Œ",
  30435. oelig: "œ",
  30436. Scaron: "Š",
  30437. scaron: "š",
  30438. Yuml: "Ÿ",
  30439. fnof: "ƒ",
  30440. circ: "ˆ",
  30441. tilde: "˜",
  30442. ensp: " ",
  30443. emsp: " ",
  30444. thinsp: " ",
  30445. zwnj: "‌",
  30446. zwj: "‍",
  30447. lrm: "‎",
  30448. rlm: "‏",
  30449. ndash: "–",
  30450. mdash: "—",
  30451. lsquo: "‘",
  30452. rsquo: "’",
  30453. sbquo: "‚",
  30454. ldquo: "“",
  30455. rdquo: "”",
  30456. bdquo: "„",
  30457. dagger: "†",
  30458. Dagger: "‡",
  30459. bull: "•",
  30460. hellip: "…",
  30461. permil: "‰",
  30462. prime: "′",
  30463. Prime: "″",
  30464. lsaquo: "‹",
  30465. rsaquo: "›",
  30466. oline: "‾",
  30467. euro: "€",
  30468. trade: "™",
  30469. larr: "←",
  30470. uarr: "↑",
  30471. rarr: "→",
  30472. darr: "↓",
  30473. harr: "↔",
  30474. crarr: "↵",
  30475. lceil: "⌈",
  30476. rceil: "⌉",
  30477. lfloor: "⌊",
  30478. rfloor: "⌋",
  30479. loz: "◊",
  30480. spades: "♠",
  30481. clubs: "♣",
  30482. hearts: "♥",
  30483. diams: "♦"
  30484. });
  30485. /**
  30486. * @deprecated use `HTML_ENTITIES` instead
  30487. * @see HTML_ENTITIES
  30488. */
  30489. exports.entityMap = exports.HTML_ENTITIES;
  30490. });
  30491. entities.XML_ENTITIES;
  30492. entities.HTML_ENTITIES;
  30493. entities.entityMap;
  30494. var NAMESPACE$1 = conventions.NAMESPACE;
  30495. //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
  30496. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  30497. //[5] Name ::= NameStartChar (NameChar)*
  30498. var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; //\u10000-\uEFFFF
  30499. var nameChar = new RegExp("[\\-\\.0-9" + nameStartChar.source.slice(1, -1) + "\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
  30500. var tagNamePattern = new RegExp('^' + nameStartChar.source + nameChar.source + '*(?:\:' + nameStartChar.source + nameChar.source + '*)?$');
  30501. //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  30502. //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
  30503. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  30504. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  30505. var S_TAG = 0; //tag name offerring
  30506. var S_ATTR = 1; //attr name offerring
  30507. var S_ATTR_SPACE = 2; //attr name end and space offer
  30508. var S_EQ = 3; //=space?
  30509. var S_ATTR_NOQUOT_VALUE = 4; //attr value(no quot value only)
  30510. var S_ATTR_END = 5; //attr value end and no space(quot end)
  30511. var S_TAG_SPACE = 6; //(attr value end || tag end ) && (space offer)
  30512. var S_TAG_CLOSE = 7; //closed el<el />
  30513. /**
  30514. * Creates an error that will not be caught by XMLReader aka the SAX parser.
  30515. *
  30516. * @param {string} message
  30517. * @param {any?} locator Optional, can provide details about the location in the source
  30518. * @constructor
  30519. */
  30520. function ParseError$1(message, locator) {
  30521. this.message = message;
  30522. this.locator = locator;
  30523. if (Error.captureStackTrace) Error.captureStackTrace(this, ParseError$1);
  30524. }
  30525. ParseError$1.prototype = new Error();
  30526. ParseError$1.prototype.name = ParseError$1.name;
  30527. function XMLReader$1() {}
  30528. XMLReader$1.prototype = {
  30529. parse: function (source, defaultNSMap, entityMap) {
  30530. var domBuilder = this.domBuilder;
  30531. domBuilder.startDocument();
  30532. _copy(defaultNSMap, defaultNSMap = {});
  30533. parse$1(source, defaultNSMap, entityMap, domBuilder, this.errorHandler);
  30534. domBuilder.endDocument();
  30535. }
  30536. };
  30537. function parse$1(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
  30538. function fixedFromCharCode(code) {
  30539. // String.prototype.fromCharCode does not supports
  30540. // > 2 bytes unicode chars directly
  30541. if (code > 0xffff) {
  30542. code -= 0x10000;
  30543. var surrogate1 = 0xd800 + (code >> 10),
  30544. surrogate2 = 0xdc00 + (code & 0x3ff);
  30545. return String.fromCharCode(surrogate1, surrogate2);
  30546. } else {
  30547. return String.fromCharCode(code);
  30548. }
  30549. }
  30550. function entityReplacer(a) {
  30551. var k = a.slice(1, -1);
  30552. if (Object.hasOwnProperty.call(entityMap, k)) {
  30553. return entityMap[k];
  30554. } else if (k.charAt(0) === '#') {
  30555. return fixedFromCharCode(parseInt(k.substr(1).replace('x', '0x')));
  30556. } else {
  30557. errorHandler.error('entity not found:' + a);
  30558. return a;
  30559. }
  30560. }
  30561. function appendText(end) {
  30562. //has some bugs
  30563. if (end > start) {
  30564. var xt = source.substring(start, end).replace(/&#?\w+;/g, entityReplacer);
  30565. locator && position(start);
  30566. domBuilder.characters(xt, 0, end - start);
  30567. start = end;
  30568. }
  30569. }
  30570. function position(p, m) {
  30571. while (p >= lineEnd && (m = linePattern.exec(source))) {
  30572. lineStart = m.index;
  30573. lineEnd = lineStart + m[0].length;
  30574. locator.lineNumber++;
  30575. //console.log('line++:',locator,startPos,endPos)
  30576. }
  30577. locator.columnNumber = p - lineStart + 1;
  30578. }
  30579. var lineStart = 0;
  30580. var lineEnd = 0;
  30581. var linePattern = /.*(?:\r\n?|\n)|.*$/g;
  30582. var locator = domBuilder.locator;
  30583. var parseStack = [{
  30584. currentNSMap: defaultNSMapCopy
  30585. }];
  30586. var closeMap = {};
  30587. var start = 0;
  30588. while (true) {
  30589. try {
  30590. var tagStart = source.indexOf('<', start);
  30591. if (tagStart < 0) {
  30592. if (!source.substr(start).match(/^\s*$/)) {
  30593. var doc = domBuilder.doc;
  30594. var text = doc.createTextNode(source.substr(start));
  30595. doc.appendChild(text);
  30596. domBuilder.currentElement = text;
  30597. }
  30598. return;
  30599. }
  30600. if (tagStart > start) {
  30601. appendText(tagStart);
  30602. }
  30603. switch (source.charAt(tagStart + 1)) {
  30604. case '/':
  30605. var end = source.indexOf('>', tagStart + 3);
  30606. var tagName = source.substring(tagStart + 2, end).replace(/[ \t\n\r]+$/g, '');
  30607. var config = parseStack.pop();
  30608. if (end < 0) {
  30609. tagName = source.substring(tagStart + 2).replace(/[\s<].*/, '');
  30610. errorHandler.error("end tag name: " + tagName + ' is not complete:' + config.tagName);
  30611. end = tagStart + 1 + tagName.length;
  30612. } else if (tagName.match(/\s</)) {
  30613. tagName = tagName.replace(/[\s<].*/, '');
  30614. errorHandler.error("end tag name: " + tagName + ' maybe not complete');
  30615. end = tagStart + 1 + tagName.length;
  30616. }
  30617. var localNSMap = config.localNSMap;
  30618. var endMatch = config.tagName == tagName;
  30619. var endIgnoreCaseMach = endMatch || config.tagName && config.tagName.toLowerCase() == tagName.toLowerCase();
  30620. if (endIgnoreCaseMach) {
  30621. domBuilder.endElement(config.uri, config.localName, tagName);
  30622. if (localNSMap) {
  30623. for (var prefix in localNSMap) {
  30624. if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) {
  30625. domBuilder.endPrefixMapping(prefix);
  30626. }
  30627. }
  30628. }
  30629. if (!endMatch) {
  30630. errorHandler.fatalError("end tag name: " + tagName + ' is not match the current start tagName:' + config.tagName); // No known test case
  30631. }
  30632. } else {
  30633. parseStack.push(config);
  30634. }
  30635. end++;
  30636. break;
  30637. // end elment
  30638. case '?':
  30639. // <?...?>
  30640. locator && position(tagStart);
  30641. end = parseInstruction(source, tagStart, domBuilder);
  30642. break;
  30643. case '!':
  30644. // <!doctype,<![CDATA,<!--
  30645. locator && position(tagStart);
  30646. end = parseDCC(source, tagStart, domBuilder, errorHandler);
  30647. break;
  30648. default:
  30649. locator && position(tagStart);
  30650. var el = new ElementAttributes();
  30651. var currentNSMap = parseStack[parseStack.length - 1].currentNSMap;
  30652. //elStartEnd
  30653. var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler);
  30654. var len = el.length;
  30655. if (!el.closed && fixSelfClosed(source, end, el.tagName, closeMap)) {
  30656. el.closed = true;
  30657. if (!entityMap.nbsp) {
  30658. errorHandler.warning('unclosed xml attribute');
  30659. }
  30660. }
  30661. if (locator && len) {
  30662. var locator2 = copyLocator(locator, {});
  30663. //try{//attribute position fixed
  30664. for (var i = 0; i < len; i++) {
  30665. var a = el[i];
  30666. position(a.offset);
  30667. a.locator = copyLocator(locator, {});
  30668. }
  30669. domBuilder.locator = locator2;
  30670. if (appendElement$1(el, domBuilder, currentNSMap)) {
  30671. parseStack.push(el);
  30672. }
  30673. domBuilder.locator = locator;
  30674. } else {
  30675. if (appendElement$1(el, domBuilder, currentNSMap)) {
  30676. parseStack.push(el);
  30677. }
  30678. }
  30679. if (NAMESPACE$1.isHTML(el.uri) && !el.closed) {
  30680. end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder);
  30681. } else {
  30682. end++;
  30683. }
  30684. }
  30685. } catch (e) {
  30686. if (e instanceof ParseError$1) {
  30687. throw e;
  30688. }
  30689. errorHandler.error('element parse error: ' + e);
  30690. end = -1;
  30691. }
  30692. if (end > start) {
  30693. start = end;
  30694. } else {
  30695. //TODO: 这里有可能sax回退,有位置错误风险
  30696. appendText(Math.max(tagStart, start) + 1);
  30697. }
  30698. }
  30699. }
  30700. function copyLocator(f, t) {
  30701. t.lineNumber = f.lineNumber;
  30702. t.columnNumber = f.columnNumber;
  30703. return t;
  30704. }
  30705. /**
  30706. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  30707. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  30708. */
  30709. function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler) {
  30710. /**
  30711. * @param {string} qname
  30712. * @param {string} value
  30713. * @param {number} startIndex
  30714. */
  30715. function addAttribute(qname, value, startIndex) {
  30716. if (el.attributeNames.hasOwnProperty(qname)) {
  30717. errorHandler.fatalError('Attribute ' + qname + ' redefined');
  30718. }
  30719. el.addValue(qname,
  30720. // @see https://www.w3.org/TR/xml/#AVNormalize
  30721. // since the xmldom sax parser does not "interpret" DTD the following is not implemented:
  30722. // - recursive replacement of (DTD) entity references
  30723. // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA
  30724. value.replace(/[\t\n\r]/g, ' ').replace(/&#?\w+;/g, entityReplacer), startIndex);
  30725. }
  30726. var attrName;
  30727. var value;
  30728. var p = ++start;
  30729. var s = S_TAG; //status
  30730. while (true) {
  30731. var c = source.charAt(p);
  30732. switch (c) {
  30733. case '=':
  30734. if (s === S_ATTR) {
  30735. //attrName
  30736. attrName = source.slice(start, p);
  30737. s = S_EQ;
  30738. } else if (s === S_ATTR_SPACE) {
  30739. s = S_EQ;
  30740. } else {
  30741. //fatalError: equal must after attrName or space after attrName
  30742. throw new Error('attribute equal must after attrName'); // No known test case
  30743. }
  30744. break;
  30745. case '\'':
  30746. case '"':
  30747. if (s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
  30748. ) {
  30749. //equal
  30750. if (s === S_ATTR) {
  30751. errorHandler.warning('attribute value must after "="');
  30752. attrName = source.slice(start, p);
  30753. }
  30754. start = p + 1;
  30755. p = source.indexOf(c, start);
  30756. if (p > 0) {
  30757. value = source.slice(start, p);
  30758. addAttribute(attrName, value, start - 1);
  30759. s = S_ATTR_END;
  30760. } else {
  30761. //fatalError: no end quot match
  30762. throw new Error('attribute value no end \'' + c + '\' match');
  30763. }
  30764. } else if (s == S_ATTR_NOQUOT_VALUE) {
  30765. value = source.slice(start, p);
  30766. addAttribute(attrName, value, start);
  30767. errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ')!!');
  30768. start = p + 1;
  30769. s = S_ATTR_END;
  30770. } else {
  30771. //fatalError: no equal before
  30772. throw new Error('attribute value must after "="'); // No known test case
  30773. }
  30774. break;
  30775. case '/':
  30776. switch (s) {
  30777. case S_TAG:
  30778. el.setTagName(source.slice(start, p));
  30779. case S_ATTR_END:
  30780. case S_TAG_SPACE:
  30781. case S_TAG_CLOSE:
  30782. s = S_TAG_CLOSE;
  30783. el.closed = true;
  30784. case S_ATTR_NOQUOT_VALUE:
  30785. case S_ATTR:
  30786. case S_ATTR_SPACE:
  30787. break;
  30788. //case S_EQ:
  30789. default:
  30790. throw new Error("attribute invalid close char('/')");
  30791. // No known test case
  30792. }
  30793. break;
  30794. case '':
  30795. //end document
  30796. errorHandler.error('unexpected end of input');
  30797. if (s == S_TAG) {
  30798. el.setTagName(source.slice(start, p));
  30799. }
  30800. return p;
  30801. case '>':
  30802. switch (s) {
  30803. case S_TAG:
  30804. el.setTagName(source.slice(start, p));
  30805. case S_ATTR_END:
  30806. case S_TAG_SPACE:
  30807. case S_TAG_CLOSE:
  30808. break;
  30809. //normal
  30810. case S_ATTR_NOQUOT_VALUE: //Compatible state
  30811. case S_ATTR:
  30812. value = source.slice(start, p);
  30813. if (value.slice(-1) === '/') {
  30814. el.closed = true;
  30815. value = value.slice(0, -1);
  30816. }
  30817. case S_ATTR_SPACE:
  30818. if (s === S_ATTR_SPACE) {
  30819. value = attrName;
  30820. }
  30821. if (s == S_ATTR_NOQUOT_VALUE) {
  30822. errorHandler.warning('attribute "' + value + '" missed quot(")!');
  30823. addAttribute(attrName, value, start);
  30824. } else {
  30825. if (!NAMESPACE$1.isHTML(currentNSMap['']) || !value.match(/^(?:disabled|checked|selected)$/i)) {
  30826. errorHandler.warning('attribute "' + value + '" missed value!! "' + value + '" instead!!');
  30827. }
  30828. addAttribute(value, value, start);
  30829. }
  30830. break;
  30831. case S_EQ:
  30832. throw new Error('attribute value missed!!');
  30833. }
  30834. // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  30835. return p;
  30836. /*xml space '\x20' | #x9 | #xD | #xA; */
  30837. case '\u0080':
  30838. c = ' ';
  30839. default:
  30840. if (c <= ' ') {
  30841. //space
  30842. switch (s) {
  30843. case S_TAG:
  30844. el.setTagName(source.slice(start, p)); //tagName
  30845. s = S_TAG_SPACE;
  30846. break;
  30847. case S_ATTR:
  30848. attrName = source.slice(start, p);
  30849. s = S_ATTR_SPACE;
  30850. break;
  30851. case S_ATTR_NOQUOT_VALUE:
  30852. var value = source.slice(start, p);
  30853. errorHandler.warning('attribute "' + value + '" missed quot(")!!');
  30854. addAttribute(attrName, value, start);
  30855. case S_ATTR_END:
  30856. s = S_TAG_SPACE;
  30857. break;
  30858. //case S_TAG_SPACE:
  30859. //case S_EQ:
  30860. //case S_ATTR_SPACE:
  30861. // void();break;
  30862. //case S_TAG_CLOSE:
  30863. //ignore warning
  30864. }
  30865. } else {
  30866. //not space
  30867. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  30868. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  30869. switch (s) {
  30870. //case S_TAG:void();break;
  30871. //case S_ATTR:void();break;
  30872. //case S_ATTR_NOQUOT_VALUE:void();break;
  30873. case S_ATTR_SPACE:
  30874. el.tagName;
  30875. if (!NAMESPACE$1.isHTML(currentNSMap['']) || !attrName.match(/^(?:disabled|checked|selected)$/i)) {
  30876. errorHandler.warning('attribute "' + attrName + '" missed value!! "' + attrName + '" instead2!!');
  30877. }
  30878. addAttribute(attrName, attrName, start);
  30879. start = p;
  30880. s = S_ATTR;
  30881. break;
  30882. case S_ATTR_END:
  30883. errorHandler.warning('attribute space is required"' + attrName + '"!!');
  30884. case S_TAG_SPACE:
  30885. s = S_ATTR;
  30886. start = p;
  30887. break;
  30888. case S_EQ:
  30889. s = S_ATTR_NOQUOT_VALUE;
  30890. start = p;
  30891. break;
  30892. case S_TAG_CLOSE:
  30893. throw new Error("elements closed character '/' and '>' must be connected to");
  30894. }
  30895. }
  30896. } //end outer switch
  30897. //console.log('p++',p)
  30898. p++;
  30899. }
  30900. }
  30901. /**
  30902. * @return true if has new namespace define
  30903. */
  30904. function appendElement$1(el, domBuilder, currentNSMap) {
  30905. var tagName = el.tagName;
  30906. var localNSMap = null;
  30907. //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  30908. var i = el.length;
  30909. while (i--) {
  30910. var a = el[i];
  30911. var qName = a.qName;
  30912. var value = a.value;
  30913. var nsp = qName.indexOf(':');
  30914. if (nsp > 0) {
  30915. var prefix = a.prefix = qName.slice(0, nsp);
  30916. var localName = qName.slice(nsp + 1);
  30917. var nsPrefix = prefix === 'xmlns' && localName;
  30918. } else {
  30919. localName = qName;
  30920. prefix = null;
  30921. nsPrefix = qName === 'xmlns' && '';
  30922. }
  30923. //can not set prefix,because prefix !== ''
  30924. a.localName = localName;
  30925. //prefix == null for no ns prefix attribute
  30926. if (nsPrefix !== false) {
  30927. //hack!!
  30928. if (localNSMap == null) {
  30929. localNSMap = {};
  30930. //console.log(currentNSMap,0)
  30931. _copy(currentNSMap, currentNSMap = {});
  30932. //console.log(currentNSMap,1)
  30933. }
  30934. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  30935. a.uri = NAMESPACE$1.XMLNS;
  30936. domBuilder.startPrefixMapping(nsPrefix, value);
  30937. }
  30938. }
  30939. var i = el.length;
  30940. while (i--) {
  30941. a = el[i];
  30942. var prefix = a.prefix;
  30943. if (prefix) {
  30944. //no prefix attribute has no namespace
  30945. if (prefix === 'xml') {
  30946. a.uri = NAMESPACE$1.XML;
  30947. }
  30948. if (prefix !== 'xmlns') {
  30949. a.uri = currentNSMap[prefix || ''];
  30950. //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  30951. }
  30952. }
  30953. }
  30954. var nsp = tagName.indexOf(':');
  30955. if (nsp > 0) {
  30956. prefix = el.prefix = tagName.slice(0, nsp);
  30957. localName = el.localName = tagName.slice(nsp + 1);
  30958. } else {
  30959. prefix = null; //important!!
  30960. localName = el.localName = tagName;
  30961. }
  30962. //no prefix element has default namespace
  30963. var ns = el.uri = currentNSMap[prefix || ''];
  30964. domBuilder.startElement(ns, localName, tagName, el);
  30965. //endPrefixMapping and startPrefixMapping have not any help for dom builder
  30966. //localNSMap = null
  30967. if (el.closed) {
  30968. domBuilder.endElement(ns, localName, tagName);
  30969. if (localNSMap) {
  30970. for (prefix in localNSMap) {
  30971. if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) {
  30972. domBuilder.endPrefixMapping(prefix);
  30973. }
  30974. }
  30975. }
  30976. } else {
  30977. el.currentNSMap = currentNSMap;
  30978. el.localNSMap = localNSMap;
  30979. //parseStack.push(el);
  30980. return true;
  30981. }
  30982. }
  30983. function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) {
  30984. if (/^(?:script|textarea)$/i.test(tagName)) {
  30985. var elEndStart = source.indexOf('</' + tagName + '>', elStartEnd);
  30986. var text = source.substring(elStartEnd + 1, elEndStart);
  30987. if (/[&<]/.test(text)) {
  30988. if (/^script$/i.test(tagName)) {
  30989. //if(!/\]\]>/.test(text)){
  30990. //lexHandler.startCDATA();
  30991. domBuilder.characters(text, 0, text.length);
  30992. //lexHandler.endCDATA();
  30993. return elEndStart;
  30994. //}
  30995. } //}else{//text area
  30996. text = text.replace(/&#?\w+;/g, entityReplacer);
  30997. domBuilder.characters(text, 0, text.length);
  30998. return elEndStart;
  30999. //}
  31000. }
  31001. }
  31002. return elStartEnd + 1;
  31003. }
  31004. function fixSelfClosed(source, elStartEnd, tagName, closeMap) {
  31005. //if(tagName in closeMap){
  31006. var pos = closeMap[tagName];
  31007. if (pos == null) {
  31008. //console.log(tagName)
  31009. pos = source.lastIndexOf('</' + tagName + '>');
  31010. if (pos < elStartEnd) {
  31011. //忘记闭合
  31012. pos = source.lastIndexOf('</' + tagName);
  31013. }
  31014. closeMap[tagName] = pos;
  31015. }
  31016. return pos < elStartEnd;
  31017. //}
  31018. }
  31019. function _copy(source, target) {
  31020. for (var n in source) {
  31021. if (Object.prototype.hasOwnProperty.call(source, n)) {
  31022. target[n] = source[n];
  31023. }
  31024. }
  31025. }
  31026. function parseDCC(source, start, domBuilder, errorHandler) {
  31027. //sure start with '<!'
  31028. var next = source.charAt(start + 2);
  31029. switch (next) {
  31030. case '-':
  31031. if (source.charAt(start + 3) === '-') {
  31032. var end = source.indexOf('-->', start + 4);
  31033. //append comment source.substring(4,end)//<!--
  31034. if (end > start) {
  31035. domBuilder.comment(source, start + 4, end - start - 4);
  31036. return end + 3;
  31037. } else {
  31038. errorHandler.error("Unclosed comment");
  31039. return -1;
  31040. }
  31041. } else {
  31042. //error
  31043. return -1;
  31044. }
  31045. default:
  31046. if (source.substr(start + 3, 6) == 'CDATA[') {
  31047. var end = source.indexOf(']]>', start + 9);
  31048. domBuilder.startCDATA();
  31049. domBuilder.characters(source, start + 9, end - start - 9);
  31050. domBuilder.endCDATA();
  31051. return end + 3;
  31052. }
  31053. //<!DOCTYPE
  31054. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  31055. var matchs = split(source, start);
  31056. var len = matchs.length;
  31057. if (len > 1 && /!doctype/i.test(matchs[0][0])) {
  31058. var name = matchs[1][0];
  31059. var pubid = false;
  31060. var sysid = false;
  31061. if (len > 3) {
  31062. if (/^public$/i.test(matchs[2][0])) {
  31063. pubid = matchs[3][0];
  31064. sysid = len > 4 && matchs[4][0];
  31065. } else if (/^system$/i.test(matchs[2][0])) {
  31066. sysid = matchs[3][0];
  31067. }
  31068. }
  31069. var lastMatch = matchs[len - 1];
  31070. domBuilder.startDTD(name, pubid, sysid);
  31071. domBuilder.endDTD();
  31072. return lastMatch.index + lastMatch[0].length;
  31073. }
  31074. }
  31075. return -1;
  31076. }
  31077. function parseInstruction(source, start, domBuilder) {
  31078. var end = source.indexOf('?>', start);
  31079. if (end) {
  31080. var match = source.substring(start, end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  31081. if (match) {
  31082. match[0].length;
  31083. domBuilder.processingInstruction(match[1], match[2]);
  31084. return end + 2;
  31085. } else {
  31086. //error
  31087. return -1;
  31088. }
  31089. }
  31090. return -1;
  31091. }
  31092. function ElementAttributes() {
  31093. this.attributeNames = {};
  31094. }
  31095. ElementAttributes.prototype = {
  31096. setTagName: function (tagName) {
  31097. if (!tagNamePattern.test(tagName)) {
  31098. throw new Error('invalid tagName:' + tagName);
  31099. }
  31100. this.tagName = tagName;
  31101. },
  31102. addValue: function (qName, value, offset) {
  31103. if (!tagNamePattern.test(qName)) {
  31104. throw new Error('invalid attribute:' + qName);
  31105. }
  31106. this.attributeNames[qName] = this.length;
  31107. this[this.length++] = {
  31108. qName: qName,
  31109. value: value,
  31110. offset: offset
  31111. };
  31112. },
  31113. length: 0,
  31114. getLocalName: function (i) {
  31115. return this[i].localName;
  31116. },
  31117. getLocator: function (i) {
  31118. return this[i].locator;
  31119. },
  31120. getQName: function (i) {
  31121. return this[i].qName;
  31122. },
  31123. getURI: function (i) {
  31124. return this[i].uri;
  31125. },
  31126. getValue: function (i) {
  31127. return this[i].value;
  31128. }
  31129. // ,getIndex:function(uri, localName)){
  31130. // if(localName){
  31131. //
  31132. // }else{
  31133. // var qName = uri
  31134. // }
  31135. // },
  31136. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  31137. // getType:function(uri,localName){}
  31138. // getType:function(i){},
  31139. };
  31140. function split(source, start) {
  31141. var match;
  31142. var buf = [];
  31143. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  31144. reg.lastIndex = start;
  31145. reg.exec(source); //skip <
  31146. while (match = reg.exec(source)) {
  31147. buf.push(match);
  31148. if (match[1]) return buf;
  31149. }
  31150. }
  31151. var XMLReader_1 = XMLReader$1;
  31152. var ParseError_1 = ParseError$1;
  31153. var sax = {
  31154. XMLReader: XMLReader_1,
  31155. ParseError: ParseError_1
  31156. };
  31157. var DOMImplementation = dom.DOMImplementation;
  31158. var NAMESPACE = conventions.NAMESPACE;
  31159. var ParseError = sax.ParseError;
  31160. var XMLReader = sax.XMLReader;
  31161. /**
  31162. * Normalizes line ending according to https://www.w3.org/TR/xml11/#sec-line-ends:
  31163. *
  31164. * > XML parsed entities are often stored in computer files which,
  31165. * > for editing convenience, are organized into lines.
  31166. * > These lines are typically separated by some combination
  31167. * > of the characters CARRIAGE RETURN (#xD) and LINE FEED (#xA).
  31168. * >
  31169. * > To simplify the tasks of applications, the XML processor must behave
  31170. * > as if it normalized all line breaks in external parsed entities (including the document entity)
  31171. * > on input, before parsing, by translating all of the following to a single #xA character:
  31172. * >
  31173. * > 1. the two-character sequence #xD #xA
  31174. * > 2. the two-character sequence #xD #x85
  31175. * > 3. the single character #x85
  31176. * > 4. the single character #x2028
  31177. * > 5. any #xD character that is not immediately followed by #xA or #x85.
  31178. *
  31179. * @param {string} input
  31180. * @returns {string}
  31181. */
  31182. function normalizeLineEndings(input) {
  31183. return input.replace(/\r[\n\u0085]/g, '\n').replace(/[\r\u0085\u2028]/g, '\n');
  31184. }
  31185. /**
  31186. * @typedef Locator
  31187. * @property {number} [columnNumber]
  31188. * @property {number} [lineNumber]
  31189. */
  31190. /**
  31191. * @typedef DOMParserOptions
  31192. * @property {DOMHandler} [domBuilder]
  31193. * @property {Function} [errorHandler]
  31194. * @property {(string) => string} [normalizeLineEndings] used to replace line endings before parsing
  31195. * defaults to `normalizeLineEndings`
  31196. * @property {Locator} [locator]
  31197. * @property {Record<string, string>} [xmlns]
  31198. *
  31199. * @see normalizeLineEndings
  31200. */
  31201. /**
  31202. * The DOMParser interface provides the ability to parse XML or HTML source code
  31203. * from a string into a DOM `Document`.
  31204. *
  31205. * _xmldom is different from the spec in that it allows an `options` parameter,
  31206. * to override the default behavior._
  31207. *
  31208. * @param {DOMParserOptions} [options]
  31209. * @constructor
  31210. *
  31211. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
  31212. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization
  31213. */
  31214. function DOMParser$1(options) {
  31215. this.options = options || {
  31216. locator: {}
  31217. };
  31218. }
  31219. DOMParser$1.prototype.parseFromString = function (source, mimeType) {
  31220. var options = this.options;
  31221. var sax = new XMLReader();
  31222. var domBuilder = options.domBuilder || new DOMHandler(); //contentHandler and LexicalHandler
  31223. var errorHandler = options.errorHandler;
  31224. var locator = options.locator;
  31225. var defaultNSMap = options.xmlns || {};
  31226. var isHTML = /\/x?html?$/.test(mimeType); //mimeType.toLowerCase().indexOf('html') > -1;
  31227. var entityMap = isHTML ? entities.HTML_ENTITIES : entities.XML_ENTITIES;
  31228. if (locator) {
  31229. domBuilder.setDocumentLocator(locator);
  31230. }
  31231. sax.errorHandler = buildErrorHandler(errorHandler, domBuilder, locator);
  31232. sax.domBuilder = options.domBuilder || domBuilder;
  31233. if (isHTML) {
  31234. defaultNSMap[''] = NAMESPACE.HTML;
  31235. }
  31236. defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML;
  31237. var normalize = options.normalizeLineEndings || normalizeLineEndings;
  31238. if (source && typeof source === 'string') {
  31239. sax.parse(normalize(source), defaultNSMap, entityMap);
  31240. } else {
  31241. sax.errorHandler.error('invalid doc source');
  31242. }
  31243. return domBuilder.doc;
  31244. };
  31245. function buildErrorHandler(errorImpl, domBuilder, locator) {
  31246. if (!errorImpl) {
  31247. if (domBuilder instanceof DOMHandler) {
  31248. return domBuilder;
  31249. }
  31250. errorImpl = domBuilder;
  31251. }
  31252. var errorHandler = {};
  31253. var isCallback = errorImpl instanceof Function;
  31254. locator = locator || {};
  31255. function build(key) {
  31256. var fn = errorImpl[key];
  31257. if (!fn && isCallback) {
  31258. fn = errorImpl.length == 2 ? function (msg) {
  31259. errorImpl(key, msg);
  31260. } : errorImpl;
  31261. }
  31262. errorHandler[key] = fn && function (msg) {
  31263. fn('[xmldom ' + key + ']\t' + msg + _locator(locator));
  31264. } || function () {};
  31265. }
  31266. build('warning');
  31267. build('error');
  31268. build('fatalError');
  31269. return errorHandler;
  31270. }
  31271. //console.log('#\n\n\n\n\n\n\n####')
  31272. /**
  31273. * +ContentHandler+ErrorHandler
  31274. * +LexicalHandler+EntityResolver2
  31275. * -DeclHandler-DTDHandler
  31276. *
  31277. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  31278. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  31279. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  31280. */
  31281. function DOMHandler() {
  31282. this.cdata = false;
  31283. }
  31284. function position(locator, node) {
  31285. node.lineNumber = locator.lineNumber;
  31286. node.columnNumber = locator.columnNumber;
  31287. }
  31288. /**
  31289. * @see org.xml.sax.ContentHandler#startDocument
  31290. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  31291. */
  31292. DOMHandler.prototype = {
  31293. startDocument: function () {
  31294. this.doc = new DOMImplementation().createDocument(null, null, null);
  31295. if (this.locator) {
  31296. this.doc.documentURI = this.locator.systemId;
  31297. }
  31298. },
  31299. startElement: function (namespaceURI, localName, qName, attrs) {
  31300. var doc = this.doc;
  31301. var el = doc.createElementNS(namespaceURI, qName || localName);
  31302. var len = attrs.length;
  31303. appendElement(this, el);
  31304. this.currentElement = el;
  31305. this.locator && position(this.locator, el);
  31306. for (var i = 0; i < len; i++) {
  31307. var namespaceURI = attrs.getURI(i);
  31308. var value = attrs.getValue(i);
  31309. var qName = attrs.getQName(i);
  31310. var attr = doc.createAttributeNS(namespaceURI, qName);
  31311. this.locator && position(attrs.getLocator(i), attr);
  31312. attr.value = attr.nodeValue = value;
  31313. el.setAttributeNode(attr);
  31314. }
  31315. },
  31316. endElement: function (namespaceURI, localName, qName) {
  31317. var current = this.currentElement;
  31318. current.tagName;
  31319. this.currentElement = current.parentNode;
  31320. },
  31321. startPrefixMapping: function (prefix, uri) {},
  31322. endPrefixMapping: function (prefix) {},
  31323. processingInstruction: function (target, data) {
  31324. var ins = this.doc.createProcessingInstruction(target, data);
  31325. this.locator && position(this.locator, ins);
  31326. appendElement(this, ins);
  31327. },
  31328. ignorableWhitespace: function (ch, start, length) {},
  31329. characters: function (chars, start, length) {
  31330. chars = _toString.apply(this, arguments);
  31331. //console.log(chars)
  31332. if (chars) {
  31333. if (this.cdata) {
  31334. var charNode = this.doc.createCDATASection(chars);
  31335. } else {
  31336. var charNode = this.doc.createTextNode(chars);
  31337. }
  31338. if (this.currentElement) {
  31339. this.currentElement.appendChild(charNode);
  31340. } else if (/^\s*$/.test(chars)) {
  31341. this.doc.appendChild(charNode);
  31342. //process xml
  31343. }
  31344. this.locator && position(this.locator, charNode);
  31345. }
  31346. },
  31347. skippedEntity: function (name) {},
  31348. endDocument: function () {
  31349. this.doc.normalize();
  31350. },
  31351. setDocumentLocator: function (locator) {
  31352. if (this.locator = locator) {
  31353. // && !('lineNumber' in locator)){
  31354. locator.lineNumber = 0;
  31355. }
  31356. },
  31357. //LexicalHandler
  31358. comment: function (chars, start, length) {
  31359. chars = _toString.apply(this, arguments);
  31360. var comm = this.doc.createComment(chars);
  31361. this.locator && position(this.locator, comm);
  31362. appendElement(this, comm);
  31363. },
  31364. startCDATA: function () {
  31365. //used in characters() methods
  31366. this.cdata = true;
  31367. },
  31368. endCDATA: function () {
  31369. this.cdata = false;
  31370. },
  31371. startDTD: function (name, publicId, systemId) {
  31372. var impl = this.doc.implementation;
  31373. if (impl && impl.createDocumentType) {
  31374. var dt = impl.createDocumentType(name, publicId, systemId);
  31375. this.locator && position(this.locator, dt);
  31376. appendElement(this, dt);
  31377. this.doc.doctype = dt;
  31378. }
  31379. },
  31380. /**
  31381. * @see org.xml.sax.ErrorHandler
  31382. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  31383. */
  31384. warning: function (error) {
  31385. console.warn('[xmldom warning]\t' + error, _locator(this.locator));
  31386. },
  31387. error: function (error) {
  31388. console.error('[xmldom error]\t' + error, _locator(this.locator));
  31389. },
  31390. fatalError: function (error) {
  31391. throw new ParseError(error, this.locator);
  31392. }
  31393. };
  31394. function _locator(l) {
  31395. if (l) {
  31396. return '\n@' + (l.systemId || '') + '#[line:' + l.lineNumber + ',col:' + l.columnNumber + ']';
  31397. }
  31398. }
  31399. function _toString(chars, start, length) {
  31400. if (typeof chars == 'string') {
  31401. return chars.substr(start, length);
  31402. } else {
  31403. //java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  31404. if (chars.length >= start + length || start) {
  31405. return new java.lang.String(chars, start, length) + '';
  31406. }
  31407. return chars;
  31408. }
  31409. }
  31410. /*
  31411. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  31412. * used method of org.xml.sax.ext.LexicalHandler:
  31413. * #comment(chars, start, length)
  31414. * #startCDATA()
  31415. * #endCDATA()
  31416. * #startDTD(name, publicId, systemId)
  31417. *
  31418. *
  31419. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  31420. * #endDTD()
  31421. * #startEntity(name)
  31422. * #endEntity(name)
  31423. *
  31424. *
  31425. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  31426. * IGNORED method of org.xml.sax.ext.DeclHandler
  31427. * #attributeDecl(eName, aName, type, mode, value)
  31428. * #elementDecl(name, model)
  31429. * #externalEntityDecl(name, publicId, systemId)
  31430. * #internalEntityDecl(name, value)
  31431. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  31432. * IGNORED method of org.xml.sax.EntityResolver2
  31433. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  31434. * #resolveEntity(publicId, systemId)
  31435. * #getExternalSubset(name, baseURI)
  31436. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  31437. * IGNORED method of org.xml.sax.DTDHandler
  31438. * #notationDecl(name, publicId, systemId) {};
  31439. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  31440. */
  31441. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g, function (key) {
  31442. DOMHandler.prototype[key] = function () {
  31443. return null;
  31444. };
  31445. });
  31446. /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
  31447. function appendElement(hander, node) {
  31448. if (!hander.currentElement) {
  31449. hander.doc.appendChild(node);
  31450. } else {
  31451. hander.currentElement.appendChild(node);
  31452. }
  31453. } //appendChild and setAttributeNS are preformance key
  31454. var __DOMHandler = DOMHandler;
  31455. var normalizeLineEndings_1 = normalizeLineEndings;
  31456. var DOMParser_1 = DOMParser$1;
  31457. var domParser = {
  31458. __DOMHandler: __DOMHandler,
  31459. normalizeLineEndings: normalizeLineEndings_1,
  31460. DOMParser: DOMParser_1
  31461. };
  31462. var DOMParser = domParser.DOMParser;
  31463. /*! @name mpd-parser @version 1.0.1 @license Apache-2.0 */
  31464. const isObject = obj => {
  31465. return !!obj && typeof obj === 'object';
  31466. };
  31467. const merge$1 = (...objects) => {
  31468. return objects.reduce((result, source) => {
  31469. if (typeof source !== 'object') {
  31470. return result;
  31471. }
  31472. Object.keys(source).forEach(key => {
  31473. if (Array.isArray(result[key]) && Array.isArray(source[key])) {
  31474. result[key] = result[key].concat(source[key]);
  31475. } else if (isObject(result[key]) && isObject(source[key])) {
  31476. result[key] = merge$1(result[key], source[key]);
  31477. } else {
  31478. result[key] = source[key];
  31479. }
  31480. });
  31481. return result;
  31482. }, {});
  31483. };
  31484. const values = o => Object.keys(o).map(k => o[k]);
  31485. const range = (start, end) => {
  31486. const result = [];
  31487. for (let i = start; i < end; i++) {
  31488. result.push(i);
  31489. }
  31490. return result;
  31491. };
  31492. const flatten = lists => lists.reduce((x, y) => x.concat(y), []);
  31493. const from = list => {
  31494. if (!list.length) {
  31495. return [];
  31496. }
  31497. const result = [];
  31498. for (let i = 0; i < list.length; i++) {
  31499. result.push(list[i]);
  31500. }
  31501. return result;
  31502. };
  31503. const findIndexes = (l, key) => l.reduce((a, e, i) => {
  31504. if (e[key]) {
  31505. a.push(i);
  31506. }
  31507. return a;
  31508. }, []);
  31509. /**
  31510. * Returns a union of the included lists provided each element can be identified by a key.
  31511. *
  31512. * @param {Array} list - list of lists to get the union of
  31513. * @param {Function} keyFunction - the function to use as a key for each element
  31514. *
  31515. * @return {Array} the union of the arrays
  31516. */
  31517. const union = (lists, keyFunction) => {
  31518. return values(lists.reduce((acc, list) => {
  31519. list.forEach(el => {
  31520. acc[keyFunction(el)] = el;
  31521. });
  31522. return acc;
  31523. }, {}));
  31524. };
  31525. var errors = {
  31526. INVALID_NUMBER_OF_PERIOD: 'INVALID_NUMBER_OF_PERIOD',
  31527. DASH_EMPTY_MANIFEST: 'DASH_EMPTY_MANIFEST',
  31528. DASH_INVALID_XML: 'DASH_INVALID_XML',
  31529. NO_BASE_URL: 'NO_BASE_URL',
  31530. MISSING_SEGMENT_INFORMATION: 'MISSING_SEGMENT_INFORMATION',
  31531. SEGMENT_TIME_UNSPECIFIED: 'SEGMENT_TIME_UNSPECIFIED',
  31532. UNSUPPORTED_UTC_TIMING_SCHEME: 'UNSUPPORTED_UTC_TIMING_SCHEME'
  31533. };
  31534. /**
  31535. * @typedef {Object} SingleUri
  31536. * @property {string} uri - relative location of segment
  31537. * @property {string} resolvedUri - resolved location of segment
  31538. * @property {Object} byterange - Object containing information on how to make byte range
  31539. * requests following byte-range-spec per RFC2616.
  31540. * @property {String} byterange.length - length of range request
  31541. * @property {String} byterange.offset - byte offset of range request
  31542. *
  31543. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1
  31544. */
  31545. /**
  31546. * Converts a URLType node (5.3.9.2.3 Table 13) to a segment object
  31547. * that conforms to how m3u8-parser is structured
  31548. *
  31549. * @see https://github.com/videojs/m3u8-parser
  31550. *
  31551. * @param {string} baseUrl - baseUrl provided by <BaseUrl> nodes
  31552. * @param {string} source - source url for segment
  31553. * @param {string} range - optional range used for range calls,
  31554. * follows RFC 2616, Clause 14.35.1
  31555. * @return {SingleUri} full segment information transformed into a format similar
  31556. * to m3u8-parser
  31557. */
  31558. const urlTypeToSegment = ({
  31559. baseUrl = '',
  31560. source = '',
  31561. range = '',
  31562. indexRange = ''
  31563. }) => {
  31564. const segment = {
  31565. uri: source,
  31566. resolvedUri: resolveUrl$1(baseUrl || '', source)
  31567. };
  31568. if (range || indexRange) {
  31569. const rangeStr = range ? range : indexRange;
  31570. const ranges = rangeStr.split('-'); // default to parsing this as a BigInt if possible
  31571. let startRange = window.BigInt ? window.BigInt(ranges[0]) : parseInt(ranges[0], 10);
  31572. let endRange = window.BigInt ? window.BigInt(ranges[1]) : parseInt(ranges[1], 10); // convert back to a number if less than MAX_SAFE_INTEGER
  31573. if (startRange < Number.MAX_SAFE_INTEGER && typeof startRange === 'bigint') {
  31574. startRange = Number(startRange);
  31575. }
  31576. if (endRange < Number.MAX_SAFE_INTEGER && typeof endRange === 'bigint') {
  31577. endRange = Number(endRange);
  31578. }
  31579. let length;
  31580. if (typeof endRange === 'bigint' || typeof startRange === 'bigint') {
  31581. length = window.BigInt(endRange) - window.BigInt(startRange) + window.BigInt(1);
  31582. } else {
  31583. length = endRange - startRange + 1;
  31584. }
  31585. if (typeof length === 'bigint' && length < Number.MAX_SAFE_INTEGER) {
  31586. length = Number(length);
  31587. } // byterange should be inclusive according to
  31588. // RFC 2616, Clause 14.35.1
  31589. segment.byterange = {
  31590. length,
  31591. offset: startRange
  31592. };
  31593. }
  31594. return segment;
  31595. };
  31596. const byteRangeToString = byterange => {
  31597. // `endRange` is one less than `offset + length` because the HTTP range
  31598. // header uses inclusive ranges
  31599. let endRange;
  31600. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  31601. endRange = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  31602. } else {
  31603. endRange = byterange.offset + byterange.length - 1;
  31604. }
  31605. return `${byterange.offset}-${endRange}`;
  31606. };
  31607. /**
  31608. * parse the end number attribue that can be a string
  31609. * number, or undefined.
  31610. *
  31611. * @param {string|number|undefined} endNumber
  31612. * The end number attribute.
  31613. *
  31614. * @return {number|null}
  31615. * The result of parsing the end number.
  31616. */
  31617. const parseEndNumber = endNumber => {
  31618. if (endNumber && typeof endNumber !== 'number') {
  31619. endNumber = parseInt(endNumber, 10);
  31620. }
  31621. if (isNaN(endNumber)) {
  31622. return null;
  31623. }
  31624. return endNumber;
  31625. };
  31626. /**
  31627. * Functions for calculating the range of available segments in static and dynamic
  31628. * manifests.
  31629. */
  31630. const segmentRange = {
  31631. /**
  31632. * Returns the entire range of available segments for a static MPD
  31633. *
  31634. * @param {Object} attributes
  31635. * Inheritied MPD attributes
  31636. * @return {{ start: number, end: number }}
  31637. * The start and end numbers for available segments
  31638. */
  31639. static(attributes) {
  31640. const {
  31641. duration,
  31642. timescale = 1,
  31643. sourceDuration,
  31644. periodDuration
  31645. } = attributes;
  31646. const endNumber = parseEndNumber(attributes.endNumber);
  31647. const segmentDuration = duration / timescale;
  31648. if (typeof endNumber === 'number') {
  31649. return {
  31650. start: 0,
  31651. end: endNumber
  31652. };
  31653. }
  31654. if (typeof periodDuration === 'number') {
  31655. return {
  31656. start: 0,
  31657. end: periodDuration / segmentDuration
  31658. };
  31659. }
  31660. return {
  31661. start: 0,
  31662. end: sourceDuration / segmentDuration
  31663. };
  31664. },
  31665. /**
  31666. * Returns the current live window range of available segments for a dynamic MPD
  31667. *
  31668. * @param {Object} attributes
  31669. * Inheritied MPD attributes
  31670. * @return {{ start: number, end: number }}
  31671. * The start and end numbers for available segments
  31672. */
  31673. dynamic(attributes) {
  31674. const {
  31675. NOW,
  31676. clientOffset,
  31677. availabilityStartTime,
  31678. timescale = 1,
  31679. duration,
  31680. periodStart = 0,
  31681. minimumUpdatePeriod = 0,
  31682. timeShiftBufferDepth = Infinity
  31683. } = attributes;
  31684. const endNumber = parseEndNumber(attributes.endNumber); // clientOffset is passed in at the top level of mpd-parser and is an offset calculated
  31685. // after retrieving UTC server time.
  31686. const now = (NOW + clientOffset) / 1000; // WC stands for Wall Clock.
  31687. // Convert the period start time to EPOCH.
  31688. const periodStartWC = availabilityStartTime + periodStart; // Period end in EPOCH is manifest's retrieval time + time until next update.
  31689. const periodEndWC = now + minimumUpdatePeriod;
  31690. const periodDuration = periodEndWC - periodStartWC;
  31691. const segmentCount = Math.ceil(periodDuration * timescale / duration);
  31692. const availableStart = Math.floor((now - periodStartWC - timeShiftBufferDepth) * timescale / duration);
  31693. const availableEnd = Math.floor((now - periodStartWC) * timescale / duration);
  31694. return {
  31695. start: Math.max(0, availableStart),
  31696. end: typeof endNumber === 'number' ? endNumber : Math.min(segmentCount, availableEnd)
  31697. };
  31698. }
  31699. };
  31700. /**
  31701. * Maps a range of numbers to objects with information needed to build the corresponding
  31702. * segment list
  31703. *
  31704. * @name toSegmentsCallback
  31705. * @function
  31706. * @param {number} number
  31707. * Number of the segment
  31708. * @param {number} index
  31709. * Index of the number in the range list
  31710. * @return {{ number: Number, duration: Number, timeline: Number, time: Number }}
  31711. * Object with segment timing and duration info
  31712. */
  31713. /**
  31714. * Returns a callback for Array.prototype.map for mapping a range of numbers to
  31715. * information needed to build the segment list.
  31716. *
  31717. * @param {Object} attributes
  31718. * Inherited MPD attributes
  31719. * @return {toSegmentsCallback}
  31720. * Callback map function
  31721. */
  31722. const toSegments = attributes => number => {
  31723. const {
  31724. duration,
  31725. timescale = 1,
  31726. periodStart,
  31727. startNumber = 1
  31728. } = attributes;
  31729. return {
  31730. number: startNumber + number,
  31731. duration: duration / timescale,
  31732. timeline: periodStart,
  31733. time: number * duration
  31734. };
  31735. };
  31736. /**
  31737. * Returns a list of objects containing segment timing and duration info used for
  31738. * building the list of segments. This uses the @duration attribute specified
  31739. * in the MPD manifest to derive the range of segments.
  31740. *
  31741. * @param {Object} attributes
  31742. * Inherited MPD attributes
  31743. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  31744. * List of Objects with segment timing and duration info
  31745. */
  31746. const parseByDuration = attributes => {
  31747. const {
  31748. type,
  31749. duration,
  31750. timescale = 1,
  31751. periodDuration,
  31752. sourceDuration
  31753. } = attributes;
  31754. const {
  31755. start,
  31756. end
  31757. } = segmentRange[type](attributes);
  31758. const segments = range(start, end).map(toSegments(attributes));
  31759. if (type === 'static') {
  31760. const index = segments.length - 1; // section is either a period or the full source
  31761. const sectionDuration = typeof periodDuration === 'number' ? periodDuration : sourceDuration; // final segment may be less than full segment duration
  31762. segments[index].duration = sectionDuration - duration / timescale * index;
  31763. }
  31764. return segments;
  31765. };
  31766. /**
  31767. * Translates SegmentBase into a set of segments.
  31768. * (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  31769. * node should be translated into segment.
  31770. *
  31771. * @param {Object} attributes
  31772. * Object containing all inherited attributes from parent elements with attribute
  31773. * names as keys
  31774. * @return {Object.<Array>} list of segments
  31775. */
  31776. const segmentsFromBase = attributes => {
  31777. const {
  31778. baseUrl,
  31779. initialization = {},
  31780. sourceDuration,
  31781. indexRange = '',
  31782. periodStart,
  31783. presentationTime,
  31784. number = 0,
  31785. duration
  31786. } = attributes; // base url is required for SegmentBase to work, per spec (Section 5.3.9.2.1)
  31787. if (!baseUrl) {
  31788. throw new Error(errors.NO_BASE_URL);
  31789. }
  31790. const initSegment = urlTypeToSegment({
  31791. baseUrl,
  31792. source: initialization.sourceURL,
  31793. range: initialization.range
  31794. });
  31795. const segment = urlTypeToSegment({
  31796. baseUrl,
  31797. source: baseUrl,
  31798. indexRange
  31799. });
  31800. segment.map = initSegment; // If there is a duration, use it, otherwise use the given duration of the source
  31801. // (since SegmentBase is only for one total segment)
  31802. if (duration) {
  31803. const segmentTimeInfo = parseByDuration(attributes);
  31804. if (segmentTimeInfo.length) {
  31805. segment.duration = segmentTimeInfo[0].duration;
  31806. segment.timeline = segmentTimeInfo[0].timeline;
  31807. }
  31808. } else if (sourceDuration) {
  31809. segment.duration = sourceDuration;
  31810. segment.timeline = periodStart;
  31811. } // If presentation time is provided, these segments are being generated by SIDX
  31812. // references, and should use the time provided. For the general case of SegmentBase,
  31813. // there should only be one segment in the period, so its presentation time is the same
  31814. // as its period start.
  31815. segment.presentationTime = presentationTime || periodStart;
  31816. segment.number = number;
  31817. return [segment];
  31818. };
  31819. /**
  31820. * Given a playlist, a sidx box, and a baseUrl, update the segment list of the playlist
  31821. * according to the sidx information given.
  31822. *
  31823. * playlist.sidx has metadadata about the sidx where-as the sidx param
  31824. * is the parsed sidx box itself.
  31825. *
  31826. * @param {Object} playlist the playlist to update the sidx information for
  31827. * @param {Object} sidx the parsed sidx box
  31828. * @return {Object} the playlist object with the updated sidx information
  31829. */
  31830. const addSidxSegmentsToPlaylist$1 = (playlist, sidx, baseUrl) => {
  31831. // Retain init segment information
  31832. const initSegment = playlist.sidx.map ? playlist.sidx.map : null; // Retain source duration from initial main manifest parsing
  31833. const sourceDuration = playlist.sidx.duration; // Retain source timeline
  31834. const timeline = playlist.timeline || 0;
  31835. const sidxByteRange = playlist.sidx.byterange;
  31836. const sidxEnd = sidxByteRange.offset + sidxByteRange.length; // Retain timescale of the parsed sidx
  31837. const timescale = sidx.timescale; // referenceType 1 refers to other sidx boxes
  31838. const mediaReferences = sidx.references.filter(r => r.referenceType !== 1);
  31839. const segments = [];
  31840. const type = playlist.endList ? 'static' : 'dynamic';
  31841. const periodStart = playlist.sidx.timeline;
  31842. let presentationTime = periodStart;
  31843. let number = playlist.mediaSequence || 0; // firstOffset is the offset from the end of the sidx box
  31844. let startIndex; // eslint-disable-next-line
  31845. if (typeof sidx.firstOffset === 'bigint') {
  31846. startIndex = window.BigInt(sidxEnd) + sidx.firstOffset;
  31847. } else {
  31848. startIndex = sidxEnd + sidx.firstOffset;
  31849. }
  31850. for (let i = 0; i < mediaReferences.length; i++) {
  31851. const reference = sidx.references[i]; // size of the referenced (sub)segment
  31852. const size = reference.referencedSize; // duration of the referenced (sub)segment, in the timescale
  31853. // this will be converted to seconds when generating segments
  31854. const duration = reference.subsegmentDuration; // should be an inclusive range
  31855. let endIndex; // eslint-disable-next-line
  31856. if (typeof startIndex === 'bigint') {
  31857. endIndex = startIndex + window.BigInt(size) - window.BigInt(1);
  31858. } else {
  31859. endIndex = startIndex + size - 1;
  31860. }
  31861. const indexRange = `${startIndex}-${endIndex}`;
  31862. const attributes = {
  31863. baseUrl,
  31864. timescale,
  31865. timeline,
  31866. periodStart,
  31867. presentationTime,
  31868. number,
  31869. duration,
  31870. sourceDuration,
  31871. indexRange,
  31872. type
  31873. };
  31874. const segment = segmentsFromBase(attributes)[0];
  31875. if (initSegment) {
  31876. segment.map = initSegment;
  31877. }
  31878. segments.push(segment);
  31879. if (typeof startIndex === 'bigint') {
  31880. startIndex += window.BigInt(size);
  31881. } else {
  31882. startIndex += size;
  31883. }
  31884. presentationTime += duration / timescale;
  31885. number++;
  31886. }
  31887. playlist.segments = segments;
  31888. return playlist;
  31889. };
  31890. const SUPPORTED_MEDIA_TYPES = ['AUDIO', 'SUBTITLES']; // allow one 60fps frame as leniency (arbitrarily chosen)
  31891. const TIME_FUDGE = 1 / 60;
  31892. /**
  31893. * Given a list of timelineStarts, combines, dedupes, and sorts them.
  31894. *
  31895. * @param {TimelineStart[]} timelineStarts - list of timeline starts
  31896. *
  31897. * @return {TimelineStart[]} the combined and deduped timeline starts
  31898. */
  31899. const getUniqueTimelineStarts = timelineStarts => {
  31900. return union(timelineStarts, ({
  31901. timeline
  31902. }) => timeline).sort((a, b) => a.timeline > b.timeline ? 1 : -1);
  31903. };
  31904. /**
  31905. * Finds the playlist with the matching NAME attribute.
  31906. *
  31907. * @param {Array} playlists - playlists to search through
  31908. * @param {string} name - the NAME attribute to search for
  31909. *
  31910. * @return {Object|null} the matching playlist object, or null
  31911. */
  31912. const findPlaylistWithName = (playlists, name) => {
  31913. for (let i = 0; i < playlists.length; i++) {
  31914. if (playlists[i].attributes.NAME === name) {
  31915. return playlists[i];
  31916. }
  31917. }
  31918. return null;
  31919. };
  31920. /**
  31921. * Gets a flattened array of media group playlists.
  31922. *
  31923. * @param {Object} manifest - the main manifest object
  31924. *
  31925. * @return {Array} the media group playlists
  31926. */
  31927. const getMediaGroupPlaylists = manifest => {
  31928. let mediaGroupPlaylists = [];
  31929. forEachMediaGroup$1(manifest, SUPPORTED_MEDIA_TYPES, (properties, type, group, label) => {
  31930. mediaGroupPlaylists = mediaGroupPlaylists.concat(properties.playlists || []);
  31931. });
  31932. return mediaGroupPlaylists;
  31933. };
  31934. /**
  31935. * Updates the playlist's media sequence numbers.
  31936. *
  31937. * @param {Object} config - options object
  31938. * @param {Object} config.playlist - the playlist to update
  31939. * @param {number} config.mediaSequence - the mediaSequence number to start with
  31940. */
  31941. const updateMediaSequenceForPlaylist = ({
  31942. playlist,
  31943. mediaSequence
  31944. }) => {
  31945. playlist.mediaSequence = mediaSequence;
  31946. playlist.segments.forEach((segment, index) => {
  31947. segment.number = playlist.mediaSequence + index;
  31948. });
  31949. };
  31950. /**
  31951. * Updates the media and discontinuity sequence numbers of newPlaylists given oldPlaylists
  31952. * and a complete list of timeline starts.
  31953. *
  31954. * If no matching playlist is found, only the discontinuity sequence number of the playlist
  31955. * will be updated.
  31956. *
  31957. * Since early available timelines are not supported, at least one segment must be present.
  31958. *
  31959. * @param {Object} config - options object
  31960. * @param {Object[]} oldPlaylists - the old playlists to use as a reference
  31961. * @param {Object[]} newPlaylists - the new playlists to update
  31962. * @param {Object} timelineStarts - all timelineStarts seen in the stream to this point
  31963. */
  31964. const updateSequenceNumbers = ({
  31965. oldPlaylists,
  31966. newPlaylists,
  31967. timelineStarts
  31968. }) => {
  31969. newPlaylists.forEach(playlist => {
  31970. playlist.discontinuitySequence = timelineStarts.findIndex(function ({
  31971. timeline
  31972. }) {
  31973. return timeline === playlist.timeline;
  31974. }); // Playlists NAMEs come from DASH Representation IDs, which are mandatory
  31975. // (see ISO_23009-1-2012 5.3.5.2).
  31976. //
  31977. // If the same Representation existed in a prior Period, it will retain the same NAME.
  31978. const oldPlaylist = findPlaylistWithName(oldPlaylists, playlist.attributes.NAME);
  31979. if (!oldPlaylist) {
  31980. // Since this is a new playlist, the media sequence values can start from 0 without
  31981. // consequence.
  31982. return;
  31983. } // TODO better support for live SIDX
  31984. //
  31985. // As of this writing, mpd-parser does not support multiperiod SIDX (in live or VOD).
  31986. // This is evident by a playlist only having a single SIDX reference. In a multiperiod
  31987. // playlist there would need to be multiple SIDX references. In addition, live SIDX is
  31988. // not supported when the SIDX properties change on refreshes.
  31989. //
  31990. // In the future, if support needs to be added, the merging logic here can be called
  31991. // after SIDX references are resolved. For now, exit early to prevent exceptions being
  31992. // thrown due to undefined references.
  31993. if (playlist.sidx) {
  31994. return;
  31995. } // Since we don't yet support early available timelines, we don't need to support
  31996. // playlists with no segments.
  31997. const firstNewSegment = playlist.segments[0];
  31998. const oldMatchingSegmentIndex = oldPlaylist.segments.findIndex(function (oldSegment) {
  31999. return Math.abs(oldSegment.presentationTime - firstNewSegment.presentationTime) < TIME_FUDGE;
  32000. }); // No matching segment from the old playlist means the entire playlist was refreshed.
  32001. // In this case the media sequence should account for this update, and the new segments
  32002. // should be marked as discontinuous from the prior content, since the last prior
  32003. // timeline was removed.
  32004. if (oldMatchingSegmentIndex === -1) {
  32005. updateMediaSequenceForPlaylist({
  32006. playlist,
  32007. mediaSequence: oldPlaylist.mediaSequence + oldPlaylist.segments.length
  32008. });
  32009. playlist.segments[0].discontinuity = true;
  32010. playlist.discontinuityStarts.unshift(0); // No matching segment does not necessarily mean there's missing content.
  32011. //
  32012. // If the new playlist's timeline is the same as the last seen segment's timeline,
  32013. // then a discontinuity can be added to identify that there's potentially missing
  32014. // content. If there's no missing content, the discontinuity should still be rather
  32015. // harmless. It's possible that if segment durations are accurate enough, that the
  32016. // existence of a gap can be determined using the presentation times and durations,
  32017. // but if the segment timing info is off, it may introduce more problems than simply
  32018. // adding the discontinuity.
  32019. //
  32020. // If the new playlist's timeline is different from the last seen segment's timeline,
  32021. // then a discontinuity can be added to identify that this is the first seen segment
  32022. // of a new timeline. However, the logic at the start of this function that
  32023. // determined the disconinuity sequence by timeline index is now off by one (the
  32024. // discontinuity of the newest timeline hasn't yet fallen off the manifest...since
  32025. // we added it), so the disconinuity sequence must be decremented.
  32026. //
  32027. // A period may also have a duration of zero, so the case of no segments is handled
  32028. // here even though we don't yet support early available periods.
  32029. if (!oldPlaylist.segments.length && playlist.timeline > oldPlaylist.timeline || oldPlaylist.segments.length && playlist.timeline > oldPlaylist.segments[oldPlaylist.segments.length - 1].timeline) {
  32030. playlist.discontinuitySequence--;
  32031. }
  32032. return;
  32033. } // If the first segment matched with a prior segment on a discontinuity (it's matching
  32034. // on the first segment of a period), then the discontinuitySequence shouldn't be the
  32035. // timeline's matching one, but instead should be the one prior, and the first segment
  32036. // of the new manifest should be marked with a discontinuity.
  32037. //
  32038. // The reason for this special case is that discontinuity sequence shows how many
  32039. // discontinuities have fallen off of the playlist, and discontinuities are marked on
  32040. // the first segment of a new "timeline." Because of this, while DASH will retain that
  32041. // Period while the "timeline" exists, HLS keeps track of it via the discontinuity
  32042. // sequence, and that first segment is an indicator, but can be removed before that
  32043. // timeline is gone.
  32044. const oldMatchingSegment = oldPlaylist.segments[oldMatchingSegmentIndex];
  32045. if (oldMatchingSegment.discontinuity && !firstNewSegment.discontinuity) {
  32046. firstNewSegment.discontinuity = true;
  32047. playlist.discontinuityStarts.unshift(0);
  32048. playlist.discontinuitySequence--;
  32049. }
  32050. updateMediaSequenceForPlaylist({
  32051. playlist,
  32052. mediaSequence: oldPlaylist.segments[oldMatchingSegmentIndex].number
  32053. });
  32054. });
  32055. };
  32056. /**
  32057. * Given an old parsed manifest object and a new parsed manifest object, updates the
  32058. * sequence and timing values within the new manifest to ensure that it lines up with the
  32059. * old.
  32060. *
  32061. * @param {Array} oldManifest - the old main manifest object
  32062. * @param {Array} newManifest - the new main manifest object
  32063. *
  32064. * @return {Object} the updated new manifest object
  32065. */
  32066. const positionManifestOnTimeline = ({
  32067. oldManifest,
  32068. newManifest
  32069. }) => {
  32070. // Starting from v4.1.2 of the IOP, section 4.4.3.3 states:
  32071. //
  32072. // "MPD@availabilityStartTime and Period@start shall not be changed over MPD updates."
  32073. //
  32074. // This was added from https://github.com/Dash-Industry-Forum/DASH-IF-IOP/issues/160
  32075. //
  32076. // Because of this change, and the difficulty of supporting periods with changing start
  32077. // times, periods with changing start times are not supported. This makes the logic much
  32078. // simpler, since periods with the same start time can be considerred the same period
  32079. // across refreshes.
  32080. //
  32081. // To give an example as to the difficulty of handling periods where the start time may
  32082. // change, if a single period manifest is refreshed with another manifest with a single
  32083. // period, and both the start and end times are increased, then the only way to determine
  32084. // if it's a new period or an old one that has changed is to look through the segments of
  32085. // each playlist and determine the presentation time bounds to find a match. In addition,
  32086. // if the period start changed to exceed the old period end, then there would be no
  32087. // match, and it would not be possible to determine whether the refreshed period is a new
  32088. // one or the old one.
  32089. const oldPlaylists = oldManifest.playlists.concat(getMediaGroupPlaylists(oldManifest));
  32090. const newPlaylists = newManifest.playlists.concat(getMediaGroupPlaylists(newManifest)); // Save all seen timelineStarts to the new manifest. Although this potentially means that
  32091. // there's a "memory leak" in that it will never stop growing, in reality, only a couple
  32092. // of properties are saved for each seen Period. Even long running live streams won't
  32093. // generate too many Periods, unless the stream is watched for decades. In the future,
  32094. // this can be optimized by mapping to discontinuity sequence numbers for each timeline,
  32095. // but it may not become an issue, and the additional info can be useful for debugging.
  32096. newManifest.timelineStarts = getUniqueTimelineStarts([oldManifest.timelineStarts, newManifest.timelineStarts]);
  32097. updateSequenceNumbers({
  32098. oldPlaylists,
  32099. newPlaylists,
  32100. timelineStarts: newManifest.timelineStarts
  32101. });
  32102. return newManifest;
  32103. };
  32104. const generateSidxKey = sidx => sidx && sidx.uri + '-' + byteRangeToString(sidx.byterange);
  32105. const mergeDiscontiguousPlaylists = playlists => {
  32106. const mergedPlaylists = values(playlists.reduce((acc, playlist) => {
  32107. // assuming playlist IDs are the same across periods
  32108. // TODO: handle multiperiod where representation sets are not the same
  32109. // across periods
  32110. const name = playlist.attributes.id + (playlist.attributes.lang || '');
  32111. if (!acc[name]) {
  32112. // First Period
  32113. acc[name] = playlist;
  32114. acc[name].attributes.timelineStarts = [];
  32115. } else {
  32116. // Subsequent Periods
  32117. if (playlist.segments) {
  32118. // first segment of subsequent periods signal a discontinuity
  32119. if (playlist.segments[0]) {
  32120. playlist.segments[0].discontinuity = true;
  32121. }
  32122. acc[name].segments.push(...playlist.segments);
  32123. } // bubble up contentProtection, this assumes all DRM content
  32124. // has the same contentProtection
  32125. if (playlist.attributes.contentProtection) {
  32126. acc[name].attributes.contentProtection = playlist.attributes.contentProtection;
  32127. }
  32128. }
  32129. acc[name].attributes.timelineStarts.push({
  32130. // Although they represent the same number, it's important to have both to make it
  32131. // compatible with HLS potentially having a similar attribute.
  32132. start: playlist.attributes.periodStart,
  32133. timeline: playlist.attributes.periodStart
  32134. });
  32135. return acc;
  32136. }, {}));
  32137. return mergedPlaylists.map(playlist => {
  32138. playlist.discontinuityStarts = findIndexes(playlist.segments || [], 'discontinuity');
  32139. return playlist;
  32140. });
  32141. };
  32142. const addSidxSegmentsToPlaylist = (playlist, sidxMapping) => {
  32143. const sidxKey = generateSidxKey(playlist.sidx);
  32144. const sidxMatch = sidxKey && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx;
  32145. if (sidxMatch) {
  32146. addSidxSegmentsToPlaylist$1(playlist, sidxMatch, playlist.sidx.resolvedUri);
  32147. }
  32148. return playlist;
  32149. };
  32150. const addSidxSegmentsToPlaylists = (playlists, sidxMapping = {}) => {
  32151. if (!Object.keys(sidxMapping).length) {
  32152. return playlists;
  32153. }
  32154. for (const i in playlists) {
  32155. playlists[i] = addSidxSegmentsToPlaylist(playlists[i], sidxMapping);
  32156. }
  32157. return playlists;
  32158. };
  32159. const formatAudioPlaylist = ({
  32160. attributes,
  32161. segments,
  32162. sidx,
  32163. mediaSequence,
  32164. discontinuitySequence,
  32165. discontinuityStarts
  32166. }, isAudioOnly) => {
  32167. const playlist = {
  32168. attributes: {
  32169. NAME: attributes.id,
  32170. BANDWIDTH: attributes.bandwidth,
  32171. CODECS: attributes.codecs,
  32172. ['PROGRAM-ID']: 1
  32173. },
  32174. uri: '',
  32175. endList: attributes.type === 'static',
  32176. timeline: attributes.periodStart,
  32177. resolvedUri: '',
  32178. targetDuration: attributes.duration,
  32179. discontinuitySequence,
  32180. discontinuityStarts,
  32181. timelineStarts: attributes.timelineStarts,
  32182. mediaSequence,
  32183. segments
  32184. };
  32185. if (attributes.contentProtection) {
  32186. playlist.contentProtection = attributes.contentProtection;
  32187. }
  32188. if (sidx) {
  32189. playlist.sidx = sidx;
  32190. }
  32191. if (isAudioOnly) {
  32192. playlist.attributes.AUDIO = 'audio';
  32193. playlist.attributes.SUBTITLES = 'subs';
  32194. }
  32195. return playlist;
  32196. };
  32197. const formatVttPlaylist = ({
  32198. attributes,
  32199. segments,
  32200. mediaSequence,
  32201. discontinuityStarts,
  32202. discontinuitySequence
  32203. }) => {
  32204. if (typeof segments === 'undefined') {
  32205. // vtt tracks may use single file in BaseURL
  32206. segments = [{
  32207. uri: attributes.baseUrl,
  32208. timeline: attributes.periodStart,
  32209. resolvedUri: attributes.baseUrl || '',
  32210. duration: attributes.sourceDuration,
  32211. number: 0
  32212. }]; // targetDuration should be the same duration as the only segment
  32213. attributes.duration = attributes.sourceDuration;
  32214. }
  32215. const m3u8Attributes = {
  32216. NAME: attributes.id,
  32217. BANDWIDTH: attributes.bandwidth,
  32218. ['PROGRAM-ID']: 1
  32219. };
  32220. if (attributes.codecs) {
  32221. m3u8Attributes.CODECS = attributes.codecs;
  32222. }
  32223. return {
  32224. attributes: m3u8Attributes,
  32225. uri: '',
  32226. endList: attributes.type === 'static',
  32227. timeline: attributes.periodStart,
  32228. resolvedUri: attributes.baseUrl || '',
  32229. targetDuration: attributes.duration,
  32230. timelineStarts: attributes.timelineStarts,
  32231. discontinuityStarts,
  32232. discontinuitySequence,
  32233. mediaSequence,
  32234. segments
  32235. };
  32236. };
  32237. const organizeAudioPlaylists = (playlists, sidxMapping = {}, isAudioOnly = false) => {
  32238. let mainPlaylist;
  32239. const formattedPlaylists = playlists.reduce((a, playlist) => {
  32240. const role = playlist.attributes.role && playlist.attributes.role.value || '';
  32241. const language = playlist.attributes.lang || '';
  32242. let label = playlist.attributes.label || 'main';
  32243. if (language && !playlist.attributes.label) {
  32244. const roleLabel = role ? ` (${role})` : '';
  32245. label = `${playlist.attributes.lang}${roleLabel}`;
  32246. }
  32247. if (!a[label]) {
  32248. a[label] = {
  32249. language,
  32250. autoselect: true,
  32251. default: role === 'main',
  32252. playlists: [],
  32253. uri: ''
  32254. };
  32255. }
  32256. const formatted = addSidxSegmentsToPlaylist(formatAudioPlaylist(playlist, isAudioOnly), sidxMapping);
  32257. a[label].playlists.push(formatted);
  32258. if (typeof mainPlaylist === 'undefined' && role === 'main') {
  32259. mainPlaylist = playlist;
  32260. mainPlaylist.default = true;
  32261. }
  32262. return a;
  32263. }, {}); // if no playlists have role "main", mark the first as main
  32264. if (!mainPlaylist) {
  32265. const firstLabel = Object.keys(formattedPlaylists)[0];
  32266. formattedPlaylists[firstLabel].default = true;
  32267. }
  32268. return formattedPlaylists;
  32269. };
  32270. const organizeVttPlaylists = (playlists, sidxMapping = {}) => {
  32271. return playlists.reduce((a, playlist) => {
  32272. const label = playlist.attributes.lang || 'text';
  32273. if (!a[label]) {
  32274. a[label] = {
  32275. language: label,
  32276. default: false,
  32277. autoselect: false,
  32278. playlists: [],
  32279. uri: ''
  32280. };
  32281. }
  32282. a[label].playlists.push(addSidxSegmentsToPlaylist(formatVttPlaylist(playlist), sidxMapping));
  32283. return a;
  32284. }, {});
  32285. };
  32286. const organizeCaptionServices = captionServices => captionServices.reduce((svcObj, svc) => {
  32287. if (!svc) {
  32288. return svcObj;
  32289. }
  32290. svc.forEach(service => {
  32291. const {
  32292. channel,
  32293. language
  32294. } = service;
  32295. svcObj[language] = {
  32296. autoselect: false,
  32297. default: false,
  32298. instreamId: channel,
  32299. language
  32300. };
  32301. if (service.hasOwnProperty('aspectRatio')) {
  32302. svcObj[language].aspectRatio = service.aspectRatio;
  32303. }
  32304. if (service.hasOwnProperty('easyReader')) {
  32305. svcObj[language].easyReader = service.easyReader;
  32306. }
  32307. if (service.hasOwnProperty('3D')) {
  32308. svcObj[language]['3D'] = service['3D'];
  32309. }
  32310. });
  32311. return svcObj;
  32312. }, {});
  32313. const formatVideoPlaylist = ({
  32314. attributes,
  32315. segments,
  32316. sidx,
  32317. discontinuityStarts
  32318. }) => {
  32319. const playlist = {
  32320. attributes: {
  32321. NAME: attributes.id,
  32322. AUDIO: 'audio',
  32323. SUBTITLES: 'subs',
  32324. RESOLUTION: {
  32325. width: attributes.width,
  32326. height: attributes.height
  32327. },
  32328. CODECS: attributes.codecs,
  32329. BANDWIDTH: attributes.bandwidth,
  32330. ['PROGRAM-ID']: 1
  32331. },
  32332. uri: '',
  32333. endList: attributes.type === 'static',
  32334. timeline: attributes.periodStart,
  32335. resolvedUri: '',
  32336. targetDuration: attributes.duration,
  32337. discontinuityStarts,
  32338. timelineStarts: attributes.timelineStarts,
  32339. segments
  32340. };
  32341. if (attributes.frameRate) {
  32342. playlist.attributes['FRAME-RATE'] = attributes.frameRate;
  32343. }
  32344. if (attributes.contentProtection) {
  32345. playlist.contentProtection = attributes.contentProtection;
  32346. }
  32347. if (sidx) {
  32348. playlist.sidx = sidx;
  32349. }
  32350. return playlist;
  32351. };
  32352. const videoOnly = ({
  32353. attributes
  32354. }) => attributes.mimeType === 'video/mp4' || attributes.mimeType === 'video/webm' || attributes.contentType === 'video';
  32355. const audioOnly = ({
  32356. attributes
  32357. }) => attributes.mimeType === 'audio/mp4' || attributes.mimeType === 'audio/webm' || attributes.contentType === 'audio';
  32358. const vttOnly = ({
  32359. attributes
  32360. }) => attributes.mimeType === 'text/vtt' || attributes.contentType === 'text';
  32361. /**
  32362. * Contains start and timeline properties denoting a timeline start. For DASH, these will
  32363. * be the same number.
  32364. *
  32365. * @typedef {Object} TimelineStart
  32366. * @property {number} start - the start time of the timeline
  32367. * @property {number} timeline - the timeline number
  32368. */
  32369. /**
  32370. * Adds appropriate media and discontinuity sequence values to the segments and playlists.
  32371. *
  32372. * Throughout mpd-parser, the `number` attribute is used in relation to `startNumber`, a
  32373. * DASH specific attribute used in constructing segment URI's from templates. However, from
  32374. * an HLS perspective, the `number` attribute on a segment would be its `mediaSequence`
  32375. * value, which should start at the original media sequence value (or 0) and increment by 1
  32376. * for each segment thereafter. Since DASH's `startNumber` values are independent per
  32377. * period, it doesn't make sense to use it for `number`. Instead, assume everything starts
  32378. * from a 0 mediaSequence value and increment from there.
  32379. *
  32380. * Note that VHS currently doesn't use the `number` property, but it can be helpful for
  32381. * debugging and making sense of the manifest.
  32382. *
  32383. * For live playlists, to account for values increasing in manifests when periods are
  32384. * removed on refreshes, merging logic should be used to update the numbers to their
  32385. * appropriate values (to ensure they're sequential and increasing).
  32386. *
  32387. * @param {Object[]} playlists - the playlists to update
  32388. * @param {TimelineStart[]} timelineStarts - the timeline starts for the manifest
  32389. */
  32390. const addMediaSequenceValues = (playlists, timelineStarts) => {
  32391. // increment all segments sequentially
  32392. playlists.forEach(playlist => {
  32393. playlist.mediaSequence = 0;
  32394. playlist.discontinuitySequence = timelineStarts.findIndex(function ({
  32395. timeline
  32396. }) {
  32397. return timeline === playlist.timeline;
  32398. });
  32399. if (!playlist.segments) {
  32400. return;
  32401. }
  32402. playlist.segments.forEach((segment, index) => {
  32403. segment.number = index;
  32404. });
  32405. });
  32406. };
  32407. /**
  32408. * Given a media group object, flattens all playlists within the media group into a single
  32409. * array.
  32410. *
  32411. * @param {Object} mediaGroupObject - the media group object
  32412. *
  32413. * @return {Object[]}
  32414. * The media group playlists
  32415. */
  32416. const flattenMediaGroupPlaylists = mediaGroupObject => {
  32417. if (!mediaGroupObject) {
  32418. return [];
  32419. }
  32420. return Object.keys(mediaGroupObject).reduce((acc, label) => {
  32421. const labelContents = mediaGroupObject[label];
  32422. return acc.concat(labelContents.playlists);
  32423. }, []);
  32424. };
  32425. const toM3u8 = ({
  32426. dashPlaylists,
  32427. locations,
  32428. sidxMapping = {},
  32429. previousManifest
  32430. }) => {
  32431. if (!dashPlaylists.length) {
  32432. return {};
  32433. } // grab all main manifest attributes
  32434. const {
  32435. sourceDuration: duration,
  32436. type,
  32437. suggestedPresentationDelay,
  32438. minimumUpdatePeriod
  32439. } = dashPlaylists[0].attributes;
  32440. const videoPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist);
  32441. const audioPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly));
  32442. const vttPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(vttOnly));
  32443. const captions = dashPlaylists.map(playlist => playlist.attributes.captionServices).filter(Boolean);
  32444. const manifest = {
  32445. allowCache: true,
  32446. discontinuityStarts: [],
  32447. segments: [],
  32448. endList: true,
  32449. mediaGroups: {
  32450. AUDIO: {},
  32451. VIDEO: {},
  32452. ['CLOSED-CAPTIONS']: {},
  32453. SUBTITLES: {}
  32454. },
  32455. uri: '',
  32456. duration,
  32457. playlists: addSidxSegmentsToPlaylists(videoPlaylists, sidxMapping)
  32458. };
  32459. if (minimumUpdatePeriod >= 0) {
  32460. manifest.minimumUpdatePeriod = minimumUpdatePeriod * 1000;
  32461. }
  32462. if (locations) {
  32463. manifest.locations = locations;
  32464. }
  32465. if (type === 'dynamic') {
  32466. manifest.suggestedPresentationDelay = suggestedPresentationDelay;
  32467. }
  32468. const isAudioOnly = manifest.playlists.length === 0;
  32469. const organizedAudioGroup = audioPlaylists.length ? organizeAudioPlaylists(audioPlaylists, sidxMapping, isAudioOnly) : null;
  32470. const organizedVttGroup = vttPlaylists.length ? organizeVttPlaylists(vttPlaylists, sidxMapping) : null;
  32471. const formattedPlaylists = videoPlaylists.concat(flattenMediaGroupPlaylists(organizedAudioGroup), flattenMediaGroupPlaylists(organizedVttGroup));
  32472. const playlistTimelineStarts = formattedPlaylists.map(({
  32473. timelineStarts
  32474. }) => timelineStarts);
  32475. manifest.timelineStarts = getUniqueTimelineStarts(playlistTimelineStarts);
  32476. addMediaSequenceValues(formattedPlaylists, manifest.timelineStarts);
  32477. if (organizedAudioGroup) {
  32478. manifest.mediaGroups.AUDIO.audio = organizedAudioGroup;
  32479. }
  32480. if (organizedVttGroup) {
  32481. manifest.mediaGroups.SUBTITLES.subs = organizedVttGroup;
  32482. }
  32483. if (captions.length) {
  32484. manifest.mediaGroups['CLOSED-CAPTIONS'].cc = organizeCaptionServices(captions);
  32485. }
  32486. if (previousManifest) {
  32487. return positionManifestOnTimeline({
  32488. oldManifest: previousManifest,
  32489. newManifest: manifest
  32490. });
  32491. }
  32492. return manifest;
  32493. };
  32494. /**
  32495. * Calculates the R (repetition) value for a live stream (for the final segment
  32496. * in a manifest where the r value is negative 1)
  32497. *
  32498. * @param {Object} attributes
  32499. * Object containing all inherited attributes from parent elements with attribute
  32500. * names as keys
  32501. * @param {number} time
  32502. * current time (typically the total time up until the final segment)
  32503. * @param {number} duration
  32504. * duration property for the given <S />
  32505. *
  32506. * @return {number}
  32507. * R value to reach the end of the given period
  32508. */
  32509. const getLiveRValue = (attributes, time, duration) => {
  32510. const {
  32511. NOW,
  32512. clientOffset,
  32513. availabilityStartTime,
  32514. timescale = 1,
  32515. periodStart = 0,
  32516. minimumUpdatePeriod = 0
  32517. } = attributes;
  32518. const now = (NOW + clientOffset) / 1000;
  32519. const periodStartWC = availabilityStartTime + periodStart;
  32520. const periodEndWC = now + minimumUpdatePeriod;
  32521. const periodDuration = periodEndWC - periodStartWC;
  32522. return Math.ceil((periodDuration * timescale - time) / duration);
  32523. };
  32524. /**
  32525. * Uses information provided by SegmentTemplate.SegmentTimeline to determine segment
  32526. * timing and duration
  32527. *
  32528. * @param {Object} attributes
  32529. * Object containing all inherited attributes from parent elements with attribute
  32530. * names as keys
  32531. * @param {Object[]} segmentTimeline
  32532. * List of objects representing the attributes of each S element contained within
  32533. *
  32534. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  32535. * List of Objects with segment timing and duration info
  32536. */
  32537. const parseByTimeline = (attributes, segmentTimeline) => {
  32538. const {
  32539. type,
  32540. minimumUpdatePeriod = 0,
  32541. media = '',
  32542. sourceDuration,
  32543. timescale = 1,
  32544. startNumber = 1,
  32545. periodStart: timeline
  32546. } = attributes;
  32547. const segments = [];
  32548. let time = -1;
  32549. for (let sIndex = 0; sIndex < segmentTimeline.length; sIndex++) {
  32550. const S = segmentTimeline[sIndex];
  32551. const duration = S.d;
  32552. const repeat = S.r || 0;
  32553. const segmentTime = S.t || 0;
  32554. if (time < 0) {
  32555. // first segment
  32556. time = segmentTime;
  32557. }
  32558. if (segmentTime && segmentTime > time) {
  32559. // discontinuity
  32560. // TODO: How to handle this type of discontinuity
  32561. // timeline++ here would treat it like HLS discontuity and content would
  32562. // get appended without gap
  32563. // E.G.
  32564. // <S t="0" d="1" />
  32565. // <S d="1" />
  32566. // <S d="1" />
  32567. // <S t="5" d="1" />
  32568. // would have $Time$ values of [0, 1, 2, 5]
  32569. // should this be appened at time positions [0, 1, 2, 3],(#EXT-X-DISCONTINUITY)
  32570. // or [0, 1, 2, gap, gap, 5]? (#EXT-X-GAP)
  32571. // does the value of sourceDuration consider this when calculating arbitrary
  32572. // negative @r repeat value?
  32573. // E.G. Same elements as above with this added at the end
  32574. // <S d="1" r="-1" />
  32575. // with a sourceDuration of 10
  32576. // Would the 2 gaps be included in the time duration calculations resulting in
  32577. // 8 segments with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9] or 10 segments
  32578. // with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9, 10, 11] ?
  32579. time = segmentTime;
  32580. }
  32581. let count;
  32582. if (repeat < 0) {
  32583. const nextS = sIndex + 1;
  32584. if (nextS === segmentTimeline.length) {
  32585. // last segment
  32586. if (type === 'dynamic' && minimumUpdatePeriod > 0 && media.indexOf('$Number$') > 0) {
  32587. count = getLiveRValue(attributes, time, duration);
  32588. } else {
  32589. // TODO: This may be incorrect depending on conclusion of TODO above
  32590. count = (sourceDuration * timescale - time) / duration;
  32591. }
  32592. } else {
  32593. count = (segmentTimeline[nextS].t - time) / duration;
  32594. }
  32595. } else {
  32596. count = repeat + 1;
  32597. }
  32598. const end = startNumber + segments.length + count;
  32599. let number = startNumber + segments.length;
  32600. while (number < end) {
  32601. segments.push({
  32602. number,
  32603. duration: duration / timescale,
  32604. time,
  32605. timeline
  32606. });
  32607. time += duration;
  32608. number++;
  32609. }
  32610. }
  32611. return segments;
  32612. };
  32613. const identifierPattern = /\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g;
  32614. /**
  32615. * Replaces template identifiers with corresponding values. To be used as the callback
  32616. * for String.prototype.replace
  32617. *
  32618. * @name replaceCallback
  32619. * @function
  32620. * @param {string} match
  32621. * Entire match of identifier
  32622. * @param {string} identifier
  32623. * Name of matched identifier
  32624. * @param {string} format
  32625. * Format tag string. Its presence indicates that padding is expected
  32626. * @param {string} width
  32627. * Desired length of the replaced value. Values less than this width shall be left
  32628. * zero padded
  32629. * @return {string}
  32630. * Replacement for the matched identifier
  32631. */
  32632. /**
  32633. * Returns a function to be used as a callback for String.prototype.replace to replace
  32634. * template identifiers
  32635. *
  32636. * @param {Obect} values
  32637. * Object containing values that shall be used to replace known identifiers
  32638. * @param {number} values.RepresentationID
  32639. * Value of the Representation@id attribute
  32640. * @param {number} values.Number
  32641. * Number of the corresponding segment
  32642. * @param {number} values.Bandwidth
  32643. * Value of the Representation@bandwidth attribute.
  32644. * @param {number} values.Time
  32645. * Timestamp value of the corresponding segment
  32646. * @return {replaceCallback}
  32647. * Callback to be used with String.prototype.replace to replace identifiers
  32648. */
  32649. const identifierReplacement = values => (match, identifier, format, width) => {
  32650. if (match === '$$') {
  32651. // escape sequence
  32652. return '$';
  32653. }
  32654. if (typeof values[identifier] === 'undefined') {
  32655. return match;
  32656. }
  32657. const value = '' + values[identifier];
  32658. if (identifier === 'RepresentationID') {
  32659. // Format tag shall not be present with RepresentationID
  32660. return value;
  32661. }
  32662. if (!format) {
  32663. width = 1;
  32664. } else {
  32665. width = parseInt(width, 10);
  32666. }
  32667. if (value.length >= width) {
  32668. return value;
  32669. }
  32670. return `${new Array(width - value.length + 1).join('0')}${value}`;
  32671. };
  32672. /**
  32673. * Constructs a segment url from a template string
  32674. *
  32675. * @param {string} url
  32676. * Template string to construct url from
  32677. * @param {Obect} values
  32678. * Object containing values that shall be used to replace known identifiers
  32679. * @param {number} values.RepresentationID
  32680. * Value of the Representation@id attribute
  32681. * @param {number} values.Number
  32682. * Number of the corresponding segment
  32683. * @param {number} values.Bandwidth
  32684. * Value of the Representation@bandwidth attribute.
  32685. * @param {number} values.Time
  32686. * Timestamp value of the corresponding segment
  32687. * @return {string}
  32688. * Segment url with identifiers replaced
  32689. */
  32690. const constructTemplateUrl = (url, values) => url.replace(identifierPattern, identifierReplacement(values));
  32691. /**
  32692. * Generates a list of objects containing timing and duration information about each
  32693. * segment needed to generate segment uris and the complete segment object
  32694. *
  32695. * @param {Object} attributes
  32696. * Object containing all inherited attributes from parent elements with attribute
  32697. * names as keys
  32698. * @param {Object[]|undefined} segmentTimeline
  32699. * List of objects representing the attributes of each S element contained within
  32700. * the SegmentTimeline element
  32701. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  32702. * List of Objects with segment timing and duration info
  32703. */
  32704. const parseTemplateInfo = (attributes, segmentTimeline) => {
  32705. if (!attributes.duration && !segmentTimeline) {
  32706. // if neither @duration or SegmentTimeline are present, then there shall be exactly
  32707. // one media segment
  32708. return [{
  32709. number: attributes.startNumber || 1,
  32710. duration: attributes.sourceDuration,
  32711. time: 0,
  32712. timeline: attributes.periodStart
  32713. }];
  32714. }
  32715. if (attributes.duration) {
  32716. return parseByDuration(attributes);
  32717. }
  32718. return parseByTimeline(attributes, segmentTimeline);
  32719. };
  32720. /**
  32721. * Generates a list of segments using information provided by the SegmentTemplate element
  32722. *
  32723. * @param {Object} attributes
  32724. * Object containing all inherited attributes from parent elements with attribute
  32725. * names as keys
  32726. * @param {Object[]|undefined} segmentTimeline
  32727. * List of objects representing the attributes of each S element contained within
  32728. * the SegmentTimeline element
  32729. * @return {Object[]}
  32730. * List of segment objects
  32731. */
  32732. const segmentsFromTemplate = (attributes, segmentTimeline) => {
  32733. const templateValues = {
  32734. RepresentationID: attributes.id,
  32735. Bandwidth: attributes.bandwidth || 0
  32736. };
  32737. const {
  32738. initialization = {
  32739. sourceURL: '',
  32740. range: ''
  32741. }
  32742. } = attributes;
  32743. const mapSegment = urlTypeToSegment({
  32744. baseUrl: attributes.baseUrl,
  32745. source: constructTemplateUrl(initialization.sourceURL, templateValues),
  32746. range: initialization.range
  32747. });
  32748. const segments = parseTemplateInfo(attributes, segmentTimeline);
  32749. return segments.map(segment => {
  32750. templateValues.Number = segment.number;
  32751. templateValues.Time = segment.time;
  32752. const uri = constructTemplateUrl(attributes.media || '', templateValues); // See DASH spec section 5.3.9.2.2
  32753. // - if timescale isn't present on any level, default to 1.
  32754. const timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  32755. const presentationTimeOffset = attributes.presentationTimeOffset || 0;
  32756. const presentationTime =
  32757. // Even if the @t attribute is not specified for the segment, segment.time is
  32758. // calculated in mpd-parser prior to this, so it's assumed to be available.
  32759. attributes.periodStart + (segment.time - presentationTimeOffset) / timescale;
  32760. const map = {
  32761. uri,
  32762. timeline: segment.timeline,
  32763. duration: segment.duration,
  32764. resolvedUri: resolveUrl$1(attributes.baseUrl || '', uri),
  32765. map: mapSegment,
  32766. number: segment.number,
  32767. presentationTime
  32768. };
  32769. return map;
  32770. });
  32771. };
  32772. /**
  32773. * Converts a <SegmentUrl> (of type URLType from the DASH spec 5.3.9.2 Table 14)
  32774. * to an object that matches the output of a segment in videojs/mpd-parser
  32775. *
  32776. * @param {Object} attributes
  32777. * Object containing all inherited attributes from parent elements with attribute
  32778. * names as keys
  32779. * @param {Object} segmentUrl
  32780. * <SegmentURL> node to translate into a segment object
  32781. * @return {Object} translated segment object
  32782. */
  32783. const SegmentURLToSegmentObject = (attributes, segmentUrl) => {
  32784. const {
  32785. baseUrl,
  32786. initialization = {}
  32787. } = attributes;
  32788. const initSegment = urlTypeToSegment({
  32789. baseUrl,
  32790. source: initialization.sourceURL,
  32791. range: initialization.range
  32792. });
  32793. const segment = urlTypeToSegment({
  32794. baseUrl,
  32795. source: segmentUrl.media,
  32796. range: segmentUrl.mediaRange
  32797. });
  32798. segment.map = initSegment;
  32799. return segment;
  32800. };
  32801. /**
  32802. * Generates a list of segments using information provided by the SegmentList element
  32803. * SegmentList (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  32804. * node should be translated into segment.
  32805. *
  32806. * @param {Object} attributes
  32807. * Object containing all inherited attributes from parent elements with attribute
  32808. * names as keys
  32809. * @param {Object[]|undefined} segmentTimeline
  32810. * List of objects representing the attributes of each S element contained within
  32811. * the SegmentTimeline element
  32812. * @return {Object.<Array>} list of segments
  32813. */
  32814. const segmentsFromList = (attributes, segmentTimeline) => {
  32815. const {
  32816. duration,
  32817. segmentUrls = [],
  32818. periodStart
  32819. } = attributes; // Per spec (5.3.9.2.1) no way to determine segment duration OR
  32820. // if both SegmentTimeline and @duration are defined, it is outside of spec.
  32821. if (!duration && !segmentTimeline || duration && segmentTimeline) {
  32822. throw new Error(errors.SEGMENT_TIME_UNSPECIFIED);
  32823. }
  32824. const segmentUrlMap = segmentUrls.map(segmentUrlObject => SegmentURLToSegmentObject(attributes, segmentUrlObject));
  32825. let segmentTimeInfo;
  32826. if (duration) {
  32827. segmentTimeInfo = parseByDuration(attributes);
  32828. }
  32829. if (segmentTimeline) {
  32830. segmentTimeInfo = parseByTimeline(attributes, segmentTimeline);
  32831. }
  32832. const segments = segmentTimeInfo.map((segmentTime, index) => {
  32833. if (segmentUrlMap[index]) {
  32834. const segment = segmentUrlMap[index]; // See DASH spec section 5.3.9.2.2
  32835. // - if timescale isn't present on any level, default to 1.
  32836. const timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  32837. const presentationTimeOffset = attributes.presentationTimeOffset || 0;
  32838. segment.timeline = segmentTime.timeline;
  32839. segment.duration = segmentTime.duration;
  32840. segment.number = segmentTime.number;
  32841. segment.presentationTime = periodStart + (segmentTime.time - presentationTimeOffset) / timescale;
  32842. return segment;
  32843. } // Since we're mapping we should get rid of any blank segments (in case
  32844. // the given SegmentTimeline is handling for more elements than we have
  32845. // SegmentURLs for).
  32846. }).filter(segment => segment);
  32847. return segments;
  32848. };
  32849. const generateSegments = ({
  32850. attributes,
  32851. segmentInfo
  32852. }) => {
  32853. let segmentAttributes;
  32854. let segmentsFn;
  32855. if (segmentInfo.template) {
  32856. segmentsFn = segmentsFromTemplate;
  32857. segmentAttributes = merge$1(attributes, segmentInfo.template);
  32858. } else if (segmentInfo.base) {
  32859. segmentsFn = segmentsFromBase;
  32860. segmentAttributes = merge$1(attributes, segmentInfo.base);
  32861. } else if (segmentInfo.list) {
  32862. segmentsFn = segmentsFromList;
  32863. segmentAttributes = merge$1(attributes, segmentInfo.list);
  32864. }
  32865. const segmentsInfo = {
  32866. attributes
  32867. };
  32868. if (!segmentsFn) {
  32869. return segmentsInfo;
  32870. }
  32871. const segments = segmentsFn(segmentAttributes, segmentInfo.segmentTimeline); // The @duration attribute will be used to determin the playlist's targetDuration which
  32872. // must be in seconds. Since we've generated the segment list, we no longer need
  32873. // @duration to be in @timescale units, so we can convert it here.
  32874. if (segmentAttributes.duration) {
  32875. const {
  32876. duration,
  32877. timescale = 1
  32878. } = segmentAttributes;
  32879. segmentAttributes.duration = duration / timescale;
  32880. } else if (segments.length) {
  32881. // if there is no @duration attribute, use the largest segment duration as
  32882. // as target duration
  32883. segmentAttributes.duration = segments.reduce((max, segment) => {
  32884. return Math.max(max, Math.ceil(segment.duration));
  32885. }, 0);
  32886. } else {
  32887. segmentAttributes.duration = 0;
  32888. }
  32889. segmentsInfo.attributes = segmentAttributes;
  32890. segmentsInfo.segments = segments; // This is a sidx box without actual segment information
  32891. if (segmentInfo.base && segmentAttributes.indexRange) {
  32892. segmentsInfo.sidx = segments[0];
  32893. segmentsInfo.segments = [];
  32894. }
  32895. return segmentsInfo;
  32896. };
  32897. const toPlaylists = representations => representations.map(generateSegments);
  32898. const findChildren = (element, name) => from(element.childNodes).filter(({
  32899. tagName
  32900. }) => tagName === name);
  32901. const getContent = element => element.textContent.trim();
  32902. /**
  32903. * Converts the provided string that may contain a division operation to a number.
  32904. *
  32905. * @param {string} value - the provided string value
  32906. *
  32907. * @return {number} the parsed string value
  32908. */
  32909. const parseDivisionValue = value => {
  32910. return parseFloat(value.split('/').reduce((prev, current) => prev / current));
  32911. };
  32912. const parseDuration = str => {
  32913. const SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
  32914. const SECONDS_IN_MONTH = 30 * 24 * 60 * 60;
  32915. const SECONDS_IN_DAY = 24 * 60 * 60;
  32916. const SECONDS_IN_HOUR = 60 * 60;
  32917. const SECONDS_IN_MIN = 60; // P10Y10M10DT10H10M10.1S
  32918. const durationRegex = /P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/;
  32919. const match = durationRegex.exec(str);
  32920. if (!match) {
  32921. return 0;
  32922. }
  32923. const [year, month, day, hour, minute, second] = match.slice(1);
  32924. return parseFloat(year || 0) * SECONDS_IN_YEAR + parseFloat(month || 0) * SECONDS_IN_MONTH + parseFloat(day || 0) * SECONDS_IN_DAY + parseFloat(hour || 0) * SECONDS_IN_HOUR + parseFloat(minute || 0) * SECONDS_IN_MIN + parseFloat(second || 0);
  32925. };
  32926. const parseDate = str => {
  32927. // Date format without timezone according to ISO 8601
  32928. // YYY-MM-DDThh:mm:ss.ssssss
  32929. const dateRegex = /^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/; // If the date string does not specifiy a timezone, we must specifiy UTC. This is
  32930. // expressed by ending with 'Z'
  32931. if (dateRegex.test(str)) {
  32932. str += 'Z';
  32933. }
  32934. return Date.parse(str);
  32935. };
  32936. const parsers = {
  32937. /**
  32938. * Specifies the duration of the entire Media Presentation. Format is a duration string
  32939. * as specified in ISO 8601
  32940. *
  32941. * @param {string} value
  32942. * value of attribute as a string
  32943. * @return {number}
  32944. * The duration in seconds
  32945. */
  32946. mediaPresentationDuration(value) {
  32947. return parseDuration(value);
  32948. },
  32949. /**
  32950. * Specifies the Segment availability start time for all Segments referred to in this
  32951. * MPD. For a dynamic manifest, it specifies the anchor for the earliest availability
  32952. * time. Format is a date string as specified in ISO 8601
  32953. *
  32954. * @param {string} value
  32955. * value of attribute as a string
  32956. * @return {number}
  32957. * The date as seconds from unix epoch
  32958. */
  32959. availabilityStartTime(value) {
  32960. return parseDate(value) / 1000;
  32961. },
  32962. /**
  32963. * Specifies the smallest period between potential changes to the MPD. Format is a
  32964. * duration string as specified in ISO 8601
  32965. *
  32966. * @param {string} value
  32967. * value of attribute as a string
  32968. * @return {number}
  32969. * The duration in seconds
  32970. */
  32971. minimumUpdatePeriod(value) {
  32972. return parseDuration(value);
  32973. },
  32974. /**
  32975. * Specifies the suggested presentation delay. Format is a
  32976. * duration string as specified in ISO 8601
  32977. *
  32978. * @param {string} value
  32979. * value of attribute as a string
  32980. * @return {number}
  32981. * The duration in seconds
  32982. */
  32983. suggestedPresentationDelay(value) {
  32984. return parseDuration(value);
  32985. },
  32986. /**
  32987. * specifices the type of mpd. Can be either "static" or "dynamic"
  32988. *
  32989. * @param {string} value
  32990. * value of attribute as a string
  32991. *
  32992. * @return {string}
  32993. * The type as a string
  32994. */
  32995. type(value) {
  32996. return value;
  32997. },
  32998. /**
  32999. * Specifies the duration of the smallest time shifting buffer for any Representation
  33000. * in the MPD. Format is a duration string as specified in ISO 8601
  33001. *
  33002. * @param {string} value
  33003. * value of attribute as a string
  33004. * @return {number}
  33005. * The duration in seconds
  33006. */
  33007. timeShiftBufferDepth(value) {
  33008. return parseDuration(value);
  33009. },
  33010. /**
  33011. * Specifies the PeriodStart time of the Period relative to the availabilityStarttime.
  33012. * Format is a duration string as specified in ISO 8601
  33013. *
  33014. * @param {string} value
  33015. * value of attribute as a string
  33016. * @return {number}
  33017. * The duration in seconds
  33018. */
  33019. start(value) {
  33020. return parseDuration(value);
  33021. },
  33022. /**
  33023. * Specifies the width of the visual presentation
  33024. *
  33025. * @param {string} value
  33026. * value of attribute as a string
  33027. * @return {number}
  33028. * The parsed width
  33029. */
  33030. width(value) {
  33031. return parseInt(value, 10);
  33032. },
  33033. /**
  33034. * Specifies the height of the visual presentation
  33035. *
  33036. * @param {string} value
  33037. * value of attribute as a string
  33038. * @return {number}
  33039. * The parsed height
  33040. */
  33041. height(value) {
  33042. return parseInt(value, 10);
  33043. },
  33044. /**
  33045. * Specifies the bitrate of the representation
  33046. *
  33047. * @param {string} value
  33048. * value of attribute as a string
  33049. * @return {number}
  33050. * The parsed bandwidth
  33051. */
  33052. bandwidth(value) {
  33053. return parseInt(value, 10);
  33054. },
  33055. /**
  33056. * Specifies the frame rate of the representation
  33057. *
  33058. * @param {string} value
  33059. * value of attribute as a string
  33060. * @return {number}
  33061. * The parsed frame rate
  33062. */
  33063. frameRate(value) {
  33064. return parseDivisionValue(value);
  33065. },
  33066. /**
  33067. * Specifies the number of the first Media Segment in this Representation in the Period
  33068. *
  33069. * @param {string} value
  33070. * value of attribute as a string
  33071. * @return {number}
  33072. * The parsed number
  33073. */
  33074. startNumber(value) {
  33075. return parseInt(value, 10);
  33076. },
  33077. /**
  33078. * Specifies the timescale in units per seconds
  33079. *
  33080. * @param {string} value
  33081. * value of attribute as a string
  33082. * @return {number}
  33083. * The parsed timescale
  33084. */
  33085. timescale(value) {
  33086. return parseInt(value, 10);
  33087. },
  33088. /**
  33089. * Specifies the presentationTimeOffset.
  33090. *
  33091. * @param {string} value
  33092. * value of the attribute as a string
  33093. *
  33094. * @return {number}
  33095. * The parsed presentationTimeOffset
  33096. */
  33097. presentationTimeOffset(value) {
  33098. return parseInt(value, 10);
  33099. },
  33100. /**
  33101. * Specifies the constant approximate Segment duration
  33102. * NOTE: The <Period> element also contains an @duration attribute. This duration
  33103. * specifies the duration of the Period. This attribute is currently not
  33104. * supported by the rest of the parser, however we still check for it to prevent
  33105. * errors.
  33106. *
  33107. * @param {string} value
  33108. * value of attribute as a string
  33109. * @return {number}
  33110. * The parsed duration
  33111. */
  33112. duration(value) {
  33113. const parsedValue = parseInt(value, 10);
  33114. if (isNaN(parsedValue)) {
  33115. return parseDuration(value);
  33116. }
  33117. return parsedValue;
  33118. },
  33119. /**
  33120. * Specifies the Segment duration, in units of the value of the @timescale.
  33121. *
  33122. * @param {string} value
  33123. * value of attribute as a string
  33124. * @return {number}
  33125. * The parsed duration
  33126. */
  33127. d(value) {
  33128. return parseInt(value, 10);
  33129. },
  33130. /**
  33131. * Specifies the MPD start time, in @timescale units, the first Segment in the series
  33132. * starts relative to the beginning of the Period
  33133. *
  33134. * @param {string} value
  33135. * value of attribute as a string
  33136. * @return {number}
  33137. * The parsed time
  33138. */
  33139. t(value) {
  33140. return parseInt(value, 10);
  33141. },
  33142. /**
  33143. * Specifies the repeat count of the number of following contiguous Segments with the
  33144. * same duration expressed by the value of @d
  33145. *
  33146. * @param {string} value
  33147. * value of attribute as a string
  33148. * @return {number}
  33149. * The parsed number
  33150. */
  33151. r(value) {
  33152. return parseInt(value, 10);
  33153. },
  33154. /**
  33155. * Default parser for all other attributes. Acts as a no-op and just returns the value
  33156. * as a string
  33157. *
  33158. * @param {string} value
  33159. * value of attribute as a string
  33160. * @return {string}
  33161. * Unparsed value
  33162. */
  33163. DEFAULT(value) {
  33164. return value;
  33165. }
  33166. };
  33167. /**
  33168. * Gets all the attributes and values of the provided node, parses attributes with known
  33169. * types, and returns an object with attribute names mapped to values.
  33170. *
  33171. * @param {Node} el
  33172. * The node to parse attributes from
  33173. * @return {Object}
  33174. * Object with all attributes of el parsed
  33175. */
  33176. const parseAttributes = el => {
  33177. if (!(el && el.attributes)) {
  33178. return {};
  33179. }
  33180. return from(el.attributes).reduce((a, e) => {
  33181. const parseFn = parsers[e.name] || parsers.DEFAULT;
  33182. a[e.name] = parseFn(e.value);
  33183. return a;
  33184. }, {});
  33185. };
  33186. const keySystemsMap = {
  33187. 'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b': 'org.w3.clearkey',
  33188. 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed': 'com.widevine.alpha',
  33189. 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95': 'com.microsoft.playready',
  33190. 'urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb': 'com.adobe.primetime'
  33191. };
  33192. /**
  33193. * Builds a list of urls that is the product of the reference urls and BaseURL values
  33194. *
  33195. * @param {string[]} referenceUrls
  33196. * List of reference urls to resolve to
  33197. * @param {Node[]} baseUrlElements
  33198. * List of BaseURL nodes from the mpd
  33199. * @return {string[]}
  33200. * List of resolved urls
  33201. */
  33202. const buildBaseUrls = (referenceUrls, baseUrlElements) => {
  33203. if (!baseUrlElements.length) {
  33204. return referenceUrls;
  33205. }
  33206. return flatten(referenceUrls.map(function (reference) {
  33207. return baseUrlElements.map(function (baseUrlElement) {
  33208. return resolveUrl$1(reference, getContent(baseUrlElement));
  33209. });
  33210. }));
  33211. };
  33212. /**
  33213. * Contains all Segment information for its containing AdaptationSet
  33214. *
  33215. * @typedef {Object} SegmentInformation
  33216. * @property {Object|undefined} template
  33217. * Contains the attributes for the SegmentTemplate node
  33218. * @property {Object[]|undefined} segmentTimeline
  33219. * Contains a list of atrributes for each S node within the SegmentTimeline node
  33220. * @property {Object|undefined} list
  33221. * Contains the attributes for the SegmentList node
  33222. * @property {Object|undefined} base
  33223. * Contains the attributes for the SegmentBase node
  33224. */
  33225. /**
  33226. * Returns all available Segment information contained within the AdaptationSet node
  33227. *
  33228. * @param {Node} adaptationSet
  33229. * The AdaptationSet node to get Segment information from
  33230. * @return {SegmentInformation}
  33231. * The Segment information contained within the provided AdaptationSet
  33232. */
  33233. const getSegmentInformation = adaptationSet => {
  33234. const segmentTemplate = findChildren(adaptationSet, 'SegmentTemplate')[0];
  33235. const segmentList = findChildren(adaptationSet, 'SegmentList')[0];
  33236. const segmentUrls = segmentList && findChildren(segmentList, 'SegmentURL').map(s => merge$1({
  33237. tag: 'SegmentURL'
  33238. }, parseAttributes(s)));
  33239. const segmentBase = findChildren(adaptationSet, 'SegmentBase')[0];
  33240. const segmentTimelineParentNode = segmentList || segmentTemplate;
  33241. const segmentTimeline = segmentTimelineParentNode && findChildren(segmentTimelineParentNode, 'SegmentTimeline')[0];
  33242. const segmentInitializationParentNode = segmentList || segmentBase || segmentTemplate;
  33243. const segmentInitialization = segmentInitializationParentNode && findChildren(segmentInitializationParentNode, 'Initialization')[0]; // SegmentTemplate is handled slightly differently, since it can have both
  33244. // @initialization and an <Initialization> node. @initialization can be templated,
  33245. // while the node can have a url and range specified. If the <SegmentTemplate> has
  33246. // both @initialization and an <Initialization> subelement we opt to override with
  33247. // the node, as this interaction is not defined in the spec.
  33248. const template = segmentTemplate && parseAttributes(segmentTemplate);
  33249. if (template && segmentInitialization) {
  33250. template.initialization = segmentInitialization && parseAttributes(segmentInitialization);
  33251. } else if (template && template.initialization) {
  33252. // If it is @initialization we convert it to an object since this is the format that
  33253. // later functions will rely on for the initialization segment. This is only valid
  33254. // for <SegmentTemplate>
  33255. template.initialization = {
  33256. sourceURL: template.initialization
  33257. };
  33258. }
  33259. const segmentInfo = {
  33260. template,
  33261. segmentTimeline: segmentTimeline && findChildren(segmentTimeline, 'S').map(s => parseAttributes(s)),
  33262. list: segmentList && merge$1(parseAttributes(segmentList), {
  33263. segmentUrls,
  33264. initialization: parseAttributes(segmentInitialization)
  33265. }),
  33266. base: segmentBase && merge$1(parseAttributes(segmentBase), {
  33267. initialization: parseAttributes(segmentInitialization)
  33268. })
  33269. };
  33270. Object.keys(segmentInfo).forEach(key => {
  33271. if (!segmentInfo[key]) {
  33272. delete segmentInfo[key];
  33273. }
  33274. });
  33275. return segmentInfo;
  33276. };
  33277. /**
  33278. * Contains Segment information and attributes needed to construct a Playlist object
  33279. * from a Representation
  33280. *
  33281. * @typedef {Object} RepresentationInformation
  33282. * @property {SegmentInformation} segmentInfo
  33283. * Segment information for this Representation
  33284. * @property {Object} attributes
  33285. * Inherited attributes for this Representation
  33286. */
  33287. /**
  33288. * Maps a Representation node to an object containing Segment information and attributes
  33289. *
  33290. * @name inheritBaseUrlsCallback
  33291. * @function
  33292. * @param {Node} representation
  33293. * Representation node from the mpd
  33294. * @return {RepresentationInformation}
  33295. * Representation information needed to construct a Playlist object
  33296. */
  33297. /**
  33298. * Returns a callback for Array.prototype.map for mapping Representation nodes to
  33299. * Segment information and attributes using inherited BaseURL nodes.
  33300. *
  33301. * @param {Object} adaptationSetAttributes
  33302. * Contains attributes inherited by the AdaptationSet
  33303. * @param {string[]} adaptationSetBaseUrls
  33304. * Contains list of resolved base urls inherited by the AdaptationSet
  33305. * @param {SegmentInformation} adaptationSetSegmentInfo
  33306. * Contains Segment information for the AdaptationSet
  33307. * @return {inheritBaseUrlsCallback}
  33308. * Callback map function
  33309. */
  33310. const inheritBaseUrls = (adaptationSetAttributes, adaptationSetBaseUrls, adaptationSetSegmentInfo) => representation => {
  33311. const repBaseUrlElements = findChildren(representation, 'BaseURL');
  33312. const repBaseUrls = buildBaseUrls(adaptationSetBaseUrls, repBaseUrlElements);
  33313. const attributes = merge$1(adaptationSetAttributes, parseAttributes(representation));
  33314. const representationSegmentInfo = getSegmentInformation(representation);
  33315. return repBaseUrls.map(baseUrl => {
  33316. return {
  33317. segmentInfo: merge$1(adaptationSetSegmentInfo, representationSegmentInfo),
  33318. attributes: merge$1(attributes, {
  33319. baseUrl
  33320. })
  33321. };
  33322. });
  33323. };
  33324. /**
  33325. * Tranforms a series of content protection nodes to
  33326. * an object containing pssh data by key system
  33327. *
  33328. * @param {Node[]} contentProtectionNodes
  33329. * Content protection nodes
  33330. * @return {Object}
  33331. * Object containing pssh data by key system
  33332. */
  33333. const generateKeySystemInformation = contentProtectionNodes => {
  33334. return contentProtectionNodes.reduce((acc, node) => {
  33335. const attributes = parseAttributes(node); // Although it could be argued that according to the UUID RFC spec the UUID string (a-f chars) should be generated
  33336. // as a lowercase string it also mentions it should be treated as case-insensitive on input. Since the key system
  33337. // UUIDs in the keySystemsMap are hardcoded as lowercase in the codebase there isn't any reason not to do
  33338. // .toLowerCase() on the input UUID string from the manifest (at least I could not think of one).
  33339. if (attributes.schemeIdUri) {
  33340. attributes.schemeIdUri = attributes.schemeIdUri.toLowerCase();
  33341. }
  33342. const keySystem = keySystemsMap[attributes.schemeIdUri];
  33343. if (keySystem) {
  33344. acc[keySystem] = {
  33345. attributes
  33346. };
  33347. const psshNode = findChildren(node, 'cenc:pssh')[0];
  33348. if (psshNode) {
  33349. const pssh = getContent(psshNode);
  33350. acc[keySystem].pssh = pssh && decodeB64ToUint8Array(pssh);
  33351. }
  33352. }
  33353. return acc;
  33354. }, {});
  33355. }; // defined in ANSI_SCTE 214-1 2016
  33356. const parseCaptionServiceMetadata = service => {
  33357. // 608 captions
  33358. if (service.schemeIdUri === 'urn:scte:dash:cc:cea-608:2015') {
  33359. const values = typeof service.value !== 'string' ? [] : service.value.split(';');
  33360. return values.map(value => {
  33361. let channel;
  33362. let language; // default language to value
  33363. language = value;
  33364. if (/^CC\d=/.test(value)) {
  33365. [channel, language] = value.split('=');
  33366. } else if (/^CC\d$/.test(value)) {
  33367. channel = value;
  33368. }
  33369. return {
  33370. channel,
  33371. language
  33372. };
  33373. });
  33374. } else if (service.schemeIdUri === 'urn:scte:dash:cc:cea-708:2015') {
  33375. const values = typeof service.value !== 'string' ? [] : service.value.split(';');
  33376. return values.map(value => {
  33377. const flags = {
  33378. // service or channel number 1-63
  33379. 'channel': undefined,
  33380. // language is a 3ALPHA per ISO 639.2/B
  33381. // field is required
  33382. 'language': undefined,
  33383. // BIT 1/0 or ?
  33384. // default value is 1, meaning 16:9 aspect ratio, 0 is 4:3, ? is unknown
  33385. 'aspectRatio': 1,
  33386. // BIT 1/0
  33387. // easy reader flag indicated the text is tailed to the needs of beginning readers
  33388. // default 0, or off
  33389. 'easyReader': 0,
  33390. // BIT 1/0
  33391. // If 3d metadata is present (CEA-708.1) then 1
  33392. // default 0
  33393. '3D': 0
  33394. };
  33395. if (/=/.test(value)) {
  33396. const [channel, opts = ''] = value.split('=');
  33397. flags.channel = channel;
  33398. flags.language = value;
  33399. opts.split(',').forEach(opt => {
  33400. const [name, val] = opt.split(':');
  33401. if (name === 'lang') {
  33402. flags.language = val; // er for easyReadery
  33403. } else if (name === 'er') {
  33404. flags.easyReader = Number(val); // war for wide aspect ratio
  33405. } else if (name === 'war') {
  33406. flags.aspectRatio = Number(val);
  33407. } else if (name === '3D') {
  33408. flags['3D'] = Number(val);
  33409. }
  33410. });
  33411. } else {
  33412. flags.language = value;
  33413. }
  33414. if (flags.channel) {
  33415. flags.channel = 'SERVICE' + flags.channel;
  33416. }
  33417. return flags;
  33418. });
  33419. }
  33420. };
  33421. /**
  33422. * Maps an AdaptationSet node to a list of Representation information objects
  33423. *
  33424. * @name toRepresentationsCallback
  33425. * @function
  33426. * @param {Node} adaptationSet
  33427. * AdaptationSet node from the mpd
  33428. * @return {RepresentationInformation[]}
  33429. * List of objects containing Representaion information
  33430. */
  33431. /**
  33432. * Returns a callback for Array.prototype.map for mapping AdaptationSet nodes to a list of
  33433. * Representation information objects
  33434. *
  33435. * @param {Object} periodAttributes
  33436. * Contains attributes inherited by the Period
  33437. * @param {string[]} periodBaseUrls
  33438. * Contains list of resolved base urls inherited by the Period
  33439. * @param {string[]} periodSegmentInfo
  33440. * Contains Segment Information at the period level
  33441. * @return {toRepresentationsCallback}
  33442. * Callback map function
  33443. */
  33444. const toRepresentations = (periodAttributes, periodBaseUrls, periodSegmentInfo) => adaptationSet => {
  33445. const adaptationSetAttributes = parseAttributes(adaptationSet);
  33446. const adaptationSetBaseUrls = buildBaseUrls(periodBaseUrls, findChildren(adaptationSet, 'BaseURL'));
  33447. const role = findChildren(adaptationSet, 'Role')[0];
  33448. const roleAttributes = {
  33449. role: parseAttributes(role)
  33450. };
  33451. let attrs = merge$1(periodAttributes, adaptationSetAttributes, roleAttributes);
  33452. const accessibility = findChildren(adaptationSet, 'Accessibility')[0];
  33453. const captionServices = parseCaptionServiceMetadata(parseAttributes(accessibility));
  33454. if (captionServices) {
  33455. attrs = merge$1(attrs, {
  33456. captionServices
  33457. });
  33458. }
  33459. const label = findChildren(adaptationSet, 'Label')[0];
  33460. if (label && label.childNodes.length) {
  33461. const labelVal = label.childNodes[0].nodeValue.trim();
  33462. attrs = merge$1(attrs, {
  33463. label: labelVal
  33464. });
  33465. }
  33466. const contentProtection = generateKeySystemInformation(findChildren(adaptationSet, 'ContentProtection'));
  33467. if (Object.keys(contentProtection).length) {
  33468. attrs = merge$1(attrs, {
  33469. contentProtection
  33470. });
  33471. }
  33472. const segmentInfo = getSegmentInformation(adaptationSet);
  33473. const representations = findChildren(adaptationSet, 'Representation');
  33474. const adaptationSetSegmentInfo = merge$1(periodSegmentInfo, segmentInfo);
  33475. return flatten(representations.map(inheritBaseUrls(attrs, adaptationSetBaseUrls, adaptationSetSegmentInfo)));
  33476. };
  33477. /**
  33478. * Contains all period information for mapping nodes onto adaptation sets.
  33479. *
  33480. * @typedef {Object} PeriodInformation
  33481. * @property {Node} period.node
  33482. * Period node from the mpd
  33483. * @property {Object} period.attributes
  33484. * Parsed period attributes from node plus any added
  33485. */
  33486. /**
  33487. * Maps a PeriodInformation object to a list of Representation information objects for all
  33488. * AdaptationSet nodes contained within the Period.
  33489. *
  33490. * @name toAdaptationSetsCallback
  33491. * @function
  33492. * @param {PeriodInformation} period
  33493. * Period object containing necessary period information
  33494. * @param {number} periodStart
  33495. * Start time of the Period within the mpd
  33496. * @return {RepresentationInformation[]}
  33497. * List of objects containing Representaion information
  33498. */
  33499. /**
  33500. * Returns a callback for Array.prototype.map for mapping Period nodes to a list of
  33501. * Representation information objects
  33502. *
  33503. * @param {Object} mpdAttributes
  33504. * Contains attributes inherited by the mpd
  33505. * @param {string[]} mpdBaseUrls
  33506. * Contains list of resolved base urls inherited by the mpd
  33507. * @return {toAdaptationSetsCallback}
  33508. * Callback map function
  33509. */
  33510. const toAdaptationSets = (mpdAttributes, mpdBaseUrls) => (period, index) => {
  33511. const periodBaseUrls = buildBaseUrls(mpdBaseUrls, findChildren(period.node, 'BaseURL'));
  33512. const periodAttributes = merge$1(mpdAttributes, {
  33513. periodStart: period.attributes.start
  33514. });
  33515. if (typeof period.attributes.duration === 'number') {
  33516. periodAttributes.periodDuration = period.attributes.duration;
  33517. }
  33518. const adaptationSets = findChildren(period.node, 'AdaptationSet');
  33519. const periodSegmentInfo = getSegmentInformation(period.node);
  33520. return flatten(adaptationSets.map(toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo)));
  33521. };
  33522. /**
  33523. * Gets Period@start property for a given period.
  33524. *
  33525. * @param {Object} options
  33526. * Options object
  33527. * @param {Object} options.attributes
  33528. * Period attributes
  33529. * @param {Object} [options.priorPeriodAttributes]
  33530. * Prior period attributes (if prior period is available)
  33531. * @param {string} options.mpdType
  33532. * The MPD@type these periods came from
  33533. * @return {number|null}
  33534. * The period start, or null if it's an early available period or error
  33535. */
  33536. const getPeriodStart = ({
  33537. attributes,
  33538. priorPeriodAttributes,
  33539. mpdType
  33540. }) => {
  33541. // Summary of period start time calculation from DASH spec section 5.3.2.1
  33542. //
  33543. // A period's start is the first period's start + time elapsed after playing all
  33544. // prior periods to this one. Periods continue one after the other in time (without
  33545. // gaps) until the end of the presentation.
  33546. //
  33547. // The value of Period@start should be:
  33548. // 1. if Period@start is present: value of Period@start
  33549. // 2. if previous period exists and it has @duration: previous Period@start +
  33550. // previous Period@duration
  33551. // 3. if this is first period and MPD@type is 'static': 0
  33552. // 4. in all other cases, consider the period an "early available period" (note: not
  33553. // currently supported)
  33554. // (1)
  33555. if (typeof attributes.start === 'number') {
  33556. return attributes.start;
  33557. } // (2)
  33558. if (priorPeriodAttributes && typeof priorPeriodAttributes.start === 'number' && typeof priorPeriodAttributes.duration === 'number') {
  33559. return priorPeriodAttributes.start + priorPeriodAttributes.duration;
  33560. } // (3)
  33561. if (!priorPeriodAttributes && mpdType === 'static') {
  33562. return 0;
  33563. } // (4)
  33564. // There is currently no logic for calculating the Period@start value if there is
  33565. // no Period@start or prior Period@start and Period@duration available. This is not made
  33566. // explicit by the DASH interop guidelines or the DASH spec, however, since there's
  33567. // nothing about any other resolution strategies, it's implied. Thus, this case should
  33568. // be considered an early available period, or error, and null should suffice for both
  33569. // of those cases.
  33570. return null;
  33571. };
  33572. /**
  33573. * Traverses the mpd xml tree to generate a list of Representation information objects
  33574. * that have inherited attributes from parent nodes
  33575. *
  33576. * @param {Node} mpd
  33577. * The root node of the mpd
  33578. * @param {Object} options
  33579. * Available options for inheritAttributes
  33580. * @param {string} options.manifestUri
  33581. * The uri source of the mpd
  33582. * @param {number} options.NOW
  33583. * Current time per DASH IOP. Default is current time in ms since epoch
  33584. * @param {number} options.clientOffset
  33585. * Client time difference from NOW (in milliseconds)
  33586. * @return {RepresentationInformation[]}
  33587. * List of objects containing Representation information
  33588. */
  33589. const inheritAttributes = (mpd, options = {}) => {
  33590. const {
  33591. manifestUri = '',
  33592. NOW = Date.now(),
  33593. clientOffset = 0
  33594. } = options;
  33595. const periodNodes = findChildren(mpd, 'Period');
  33596. if (!periodNodes.length) {
  33597. throw new Error(errors.INVALID_NUMBER_OF_PERIOD);
  33598. }
  33599. const locations = findChildren(mpd, 'Location');
  33600. const mpdAttributes = parseAttributes(mpd);
  33601. const mpdBaseUrls = buildBaseUrls([manifestUri], findChildren(mpd, 'BaseURL')); // See DASH spec section 5.3.1.2, Semantics of MPD element. Default type to 'static'.
  33602. mpdAttributes.type = mpdAttributes.type || 'static';
  33603. mpdAttributes.sourceDuration = mpdAttributes.mediaPresentationDuration || 0;
  33604. mpdAttributes.NOW = NOW;
  33605. mpdAttributes.clientOffset = clientOffset;
  33606. if (locations.length) {
  33607. mpdAttributes.locations = locations.map(getContent);
  33608. }
  33609. const periods = []; // Since toAdaptationSets acts on individual periods right now, the simplest approach to
  33610. // adding properties that require looking at prior periods is to parse attributes and add
  33611. // missing ones before toAdaptationSets is called. If more such properties are added, it
  33612. // may be better to refactor toAdaptationSets.
  33613. periodNodes.forEach((node, index) => {
  33614. const attributes = parseAttributes(node); // Use the last modified prior period, as it may contain added information necessary
  33615. // for this period.
  33616. const priorPeriod = periods[index - 1];
  33617. attributes.start = getPeriodStart({
  33618. attributes,
  33619. priorPeriodAttributes: priorPeriod ? priorPeriod.attributes : null,
  33620. mpdType: mpdAttributes.type
  33621. });
  33622. periods.push({
  33623. node,
  33624. attributes
  33625. });
  33626. });
  33627. return {
  33628. locations: mpdAttributes.locations,
  33629. representationInfo: flatten(periods.map(toAdaptationSets(mpdAttributes, mpdBaseUrls)))
  33630. };
  33631. };
  33632. const stringToMpdXml = manifestString => {
  33633. if (manifestString === '') {
  33634. throw new Error(errors.DASH_EMPTY_MANIFEST);
  33635. }
  33636. const parser = new DOMParser();
  33637. let xml;
  33638. let mpd;
  33639. try {
  33640. xml = parser.parseFromString(manifestString, 'application/xml');
  33641. mpd = xml && xml.documentElement.tagName === 'MPD' ? xml.documentElement : null;
  33642. } catch (e) {// ie 11 throwsw on invalid xml
  33643. }
  33644. if (!mpd || mpd && mpd.getElementsByTagName('parsererror').length > 0) {
  33645. throw new Error(errors.DASH_INVALID_XML);
  33646. }
  33647. return mpd;
  33648. };
  33649. /**
  33650. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  33651. *
  33652. * @param {string} mpd
  33653. * XML string of the MPD manifest
  33654. * @return {Object|null}
  33655. * Attributes of UTCTiming node specified in the manifest. Null if none found
  33656. */
  33657. const parseUTCTimingScheme = mpd => {
  33658. const UTCTimingNode = findChildren(mpd, 'UTCTiming')[0];
  33659. if (!UTCTimingNode) {
  33660. return null;
  33661. }
  33662. const attributes = parseAttributes(UTCTimingNode);
  33663. switch (attributes.schemeIdUri) {
  33664. case 'urn:mpeg:dash:utc:http-head:2014':
  33665. case 'urn:mpeg:dash:utc:http-head:2012':
  33666. attributes.method = 'HEAD';
  33667. break;
  33668. case 'urn:mpeg:dash:utc:http-xsdate:2014':
  33669. case 'urn:mpeg:dash:utc:http-iso:2014':
  33670. case 'urn:mpeg:dash:utc:http-xsdate:2012':
  33671. case 'urn:mpeg:dash:utc:http-iso:2012':
  33672. attributes.method = 'GET';
  33673. break;
  33674. case 'urn:mpeg:dash:utc:direct:2014':
  33675. case 'urn:mpeg:dash:utc:direct:2012':
  33676. attributes.method = 'DIRECT';
  33677. attributes.value = Date.parse(attributes.value);
  33678. break;
  33679. case 'urn:mpeg:dash:utc:http-ntp:2014':
  33680. case 'urn:mpeg:dash:utc:ntp:2014':
  33681. case 'urn:mpeg:dash:utc:sntp:2014':
  33682. default:
  33683. throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME);
  33684. }
  33685. return attributes;
  33686. };
  33687. /*
  33688. * Given a DASH manifest string and options, parses the DASH manifest into an object in the
  33689. * form outputed by m3u8-parser and accepted by videojs/http-streaming.
  33690. *
  33691. * For live DASH manifests, if `previousManifest` is provided in options, then the newly
  33692. * parsed DASH manifest will have its media sequence and discontinuity sequence values
  33693. * updated to reflect its position relative to the prior manifest.
  33694. *
  33695. * @param {string} manifestString - the DASH manifest as a string
  33696. * @param {options} [options] - any options
  33697. *
  33698. * @return {Object} the manifest object
  33699. */
  33700. const parse = (manifestString, options = {}) => {
  33701. const parsedManifestInfo = inheritAttributes(stringToMpdXml(manifestString), options);
  33702. const playlists = toPlaylists(parsedManifestInfo.representationInfo);
  33703. return toM3u8({
  33704. dashPlaylists: playlists,
  33705. locations: parsedManifestInfo.locations,
  33706. sidxMapping: options.sidxMapping,
  33707. previousManifest: options.previousManifest
  33708. });
  33709. };
  33710. /**
  33711. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  33712. *
  33713. * @param {string} manifestString
  33714. * XML string of the MPD manifest
  33715. * @return {Object|null}
  33716. * Attributes of UTCTiming node specified in the manifest. Null if none found
  33717. */
  33718. const parseUTCTiming = manifestString => parseUTCTimingScheme(stringToMpdXml(manifestString));
  33719. var MAX_UINT32 = Math.pow(2, 32);
  33720. var getUint64$1 = function (uint8) {
  33721. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  33722. var value;
  33723. if (dv.getBigUint64) {
  33724. value = dv.getBigUint64(0);
  33725. if (value < Number.MAX_SAFE_INTEGER) {
  33726. return Number(value);
  33727. }
  33728. return value;
  33729. }
  33730. return dv.getUint32(0) * MAX_UINT32 + dv.getUint32(4);
  33731. };
  33732. var numbers = {
  33733. getUint64: getUint64$1,
  33734. MAX_UINT32: MAX_UINT32
  33735. };
  33736. var getUint64 = numbers.getUint64;
  33737. var parseSidx = function (data) {
  33738. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  33739. result = {
  33740. version: data[0],
  33741. flags: new Uint8Array(data.subarray(1, 4)),
  33742. references: [],
  33743. referenceId: view.getUint32(4),
  33744. timescale: view.getUint32(8)
  33745. },
  33746. i = 12;
  33747. if (result.version === 0) {
  33748. result.earliestPresentationTime = view.getUint32(i);
  33749. result.firstOffset = view.getUint32(i + 4);
  33750. i += 8;
  33751. } else {
  33752. // read 64 bits
  33753. result.earliestPresentationTime = getUint64(data.subarray(i));
  33754. result.firstOffset = getUint64(data.subarray(i + 8));
  33755. i += 16;
  33756. }
  33757. i += 2; // reserved
  33758. var referenceCount = view.getUint16(i);
  33759. i += 2; // start of references
  33760. for (; referenceCount > 0; i += 12, referenceCount--) {
  33761. result.references.push({
  33762. referenceType: (data[i] & 0x80) >>> 7,
  33763. referencedSize: view.getUint32(i) & 0x7FFFFFFF,
  33764. subsegmentDuration: view.getUint32(i + 4),
  33765. startsWithSap: !!(data[i + 8] & 0x80),
  33766. sapType: (data[i + 8] & 0x70) >>> 4,
  33767. sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
  33768. });
  33769. }
  33770. return result;
  33771. };
  33772. var parseSidx_1 = parseSidx;
  33773. var ID3 = toUint8([0x49, 0x44, 0x33]);
  33774. var getId3Size = function getId3Size(bytes, offset) {
  33775. if (offset === void 0) {
  33776. offset = 0;
  33777. }
  33778. bytes = toUint8(bytes);
  33779. var flags = bytes[offset + 5];
  33780. var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
  33781. var footerPresent = (flags & 16) >> 4;
  33782. if (footerPresent) {
  33783. return returnSize + 20;
  33784. }
  33785. return returnSize + 10;
  33786. };
  33787. var getId3Offset = function getId3Offset(bytes, offset) {
  33788. if (offset === void 0) {
  33789. offset = 0;
  33790. }
  33791. bytes = toUint8(bytes);
  33792. if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {
  33793. offset: offset
  33794. })) {
  33795. return offset;
  33796. }
  33797. offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files
  33798. // have multiple ID3 tag sections even though
  33799. // they should not.
  33800. return getId3Offset(bytes, offset);
  33801. };
  33802. var normalizePath$1 = function normalizePath(path) {
  33803. if (typeof path === 'string') {
  33804. return stringToBytes(path);
  33805. }
  33806. if (typeof path === 'number') {
  33807. return path;
  33808. }
  33809. return path;
  33810. };
  33811. var normalizePaths$1 = function normalizePaths(paths) {
  33812. if (!Array.isArray(paths)) {
  33813. return [normalizePath$1(paths)];
  33814. }
  33815. return paths.map(function (p) {
  33816. return normalizePath$1(p);
  33817. });
  33818. };
  33819. /**
  33820. * find any number of boxes by name given a path to it in an iso bmff
  33821. * such as mp4.
  33822. *
  33823. * @param {TypedArray} bytes
  33824. * bytes for the iso bmff to search for boxes in
  33825. *
  33826. * @param {Uint8Array[]|string[]|string|Uint8Array} name
  33827. * An array of paths or a single path representing the name
  33828. * of boxes to search through in bytes. Paths may be
  33829. * uint8 (character codes) or strings.
  33830. *
  33831. * @param {boolean} [complete=false]
  33832. * Should we search only for complete boxes on the final path.
  33833. * This is very useful when you do not want to get back partial boxes
  33834. * in the case of streaming files.
  33835. *
  33836. * @return {Uint8Array[]}
  33837. * An array of the end paths that we found.
  33838. */
  33839. var findBox = function findBox(bytes, paths, complete) {
  33840. if (complete === void 0) {
  33841. complete = false;
  33842. }
  33843. paths = normalizePaths$1(paths);
  33844. bytes = toUint8(bytes);
  33845. var results = [];
  33846. if (!paths.length) {
  33847. // short-circuit the search for empty paths
  33848. return results;
  33849. }
  33850. var i = 0;
  33851. while (i < bytes.length) {
  33852. var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
  33853. var type = bytes.subarray(i + 4, i + 8); // invalid box format.
  33854. if (size === 0) {
  33855. break;
  33856. }
  33857. var end = i + size;
  33858. if (end > bytes.length) {
  33859. // this box is bigger than the number of bytes we have
  33860. // and complete is set, we cannot find any more boxes.
  33861. if (complete) {
  33862. break;
  33863. }
  33864. end = bytes.length;
  33865. }
  33866. var data = bytes.subarray(i + 8, end);
  33867. if (bytesMatch(type, paths[0])) {
  33868. if (paths.length === 1) {
  33869. // this is the end of the path and we've found the box we were
  33870. // looking for
  33871. results.push(data);
  33872. } else {
  33873. // recursively search for the next box along the path
  33874. results.push.apply(results, findBox(data, paths.slice(1), complete));
  33875. }
  33876. }
  33877. i = end;
  33878. } // we've finished searching all of bytes
  33879. return results;
  33880. };
  33881. // https://matroska-org.github.io/libebml/specs.html
  33882. // https://www.matroska.org/technical/elements.html
  33883. // https://www.webmproject.org/docs/container/
  33884. var EBML_TAGS = {
  33885. EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),
  33886. DocType: toUint8([0x42, 0x82]),
  33887. Segment: toUint8([0x18, 0x53, 0x80, 0x67]),
  33888. SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),
  33889. Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),
  33890. Track: toUint8([0xAE]),
  33891. TrackNumber: toUint8([0xd7]),
  33892. DefaultDuration: toUint8([0x23, 0xe3, 0x83]),
  33893. TrackEntry: toUint8([0xAE]),
  33894. TrackType: toUint8([0x83]),
  33895. FlagDefault: toUint8([0x88]),
  33896. CodecID: toUint8([0x86]),
  33897. CodecPrivate: toUint8([0x63, 0xA2]),
  33898. VideoTrack: toUint8([0xe0]),
  33899. AudioTrack: toUint8([0xe1]),
  33900. // Not used yet, but will be used for live webm/mkv
  33901. // see https://www.matroska.org/technical/basics.html#block-structure
  33902. // see https://www.matroska.org/technical/basics.html#simpleblock-structure
  33903. Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),
  33904. Timestamp: toUint8([0xE7]),
  33905. TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),
  33906. BlockGroup: toUint8([0xA0]),
  33907. BlockDuration: toUint8([0x9B]),
  33908. Block: toUint8([0xA1]),
  33909. SimpleBlock: toUint8([0xA3])
  33910. };
  33911. /**
  33912. * This is a simple table to determine the length
  33913. * of things in ebml. The length is one based (starts at 1,
  33914. * rather than zero) and for every zero bit before a one bit
  33915. * we add one to length. We also need this table because in some
  33916. * case we have to xor all the length bits from another value.
  33917. */
  33918. var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
  33919. var getLength = function getLength(byte) {
  33920. var len = 1;
  33921. for (var i = 0; i < LENGTH_TABLE.length; i++) {
  33922. if (byte & LENGTH_TABLE[i]) {
  33923. break;
  33924. }
  33925. len++;
  33926. }
  33927. return len;
  33928. }; // length in ebml is stored in the first 4 to 8 bits
  33929. // of the first byte. 4 for the id length and 8 for the
  33930. // data size length. Length is measured by converting the number to binary
  33931. // then 1 + the number of zeros before a 1 is encountered starting
  33932. // from the left.
  33933. var getvint = function getvint(bytes, offset, removeLength, signed) {
  33934. if (removeLength === void 0) {
  33935. removeLength = true;
  33936. }
  33937. if (signed === void 0) {
  33938. signed = false;
  33939. }
  33940. var length = getLength(bytes[offset]);
  33941. var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes
  33942. // as they will be modified below to remove the dataSizeLen bits and we do not
  33943. // want to modify the original data. normally we could just call slice on
  33944. // uint8array but ie 11 does not support that...
  33945. if (removeLength) {
  33946. valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
  33947. valueBytes[0] ^= LENGTH_TABLE[length - 1];
  33948. }
  33949. return {
  33950. length: length,
  33951. value: bytesToNumber(valueBytes, {
  33952. signed: signed
  33953. }),
  33954. bytes: valueBytes
  33955. };
  33956. };
  33957. var normalizePath = function normalizePath(path) {
  33958. if (typeof path === 'string') {
  33959. return path.match(/.{1,2}/g).map(function (p) {
  33960. return normalizePath(p);
  33961. });
  33962. }
  33963. if (typeof path === 'number') {
  33964. return numberToBytes(path);
  33965. }
  33966. return path;
  33967. };
  33968. var normalizePaths = function normalizePaths(paths) {
  33969. if (!Array.isArray(paths)) {
  33970. return [normalizePath(paths)];
  33971. }
  33972. return paths.map(function (p) {
  33973. return normalizePath(p);
  33974. });
  33975. };
  33976. var getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {
  33977. if (offset >= bytes.length) {
  33978. return bytes.length;
  33979. }
  33980. var innerid = getvint(bytes, offset, false);
  33981. if (bytesMatch(id.bytes, innerid.bytes)) {
  33982. return offset;
  33983. }
  33984. var dataHeader = getvint(bytes, offset + innerid.length);
  33985. return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
  33986. };
  33987. /**
  33988. * Notes on the EBLM format.
  33989. *
  33990. * EBLM uses "vints" tags. Every vint tag contains
  33991. * two parts
  33992. *
  33993. * 1. The length from the first byte. You get this by
  33994. * converting the byte to binary and counting the zeros
  33995. * before a 1. Then you add 1 to that. Examples
  33996. * 00011111 = length 4 because there are 3 zeros before a 1.
  33997. * 00100000 = length 3 because there are 2 zeros before a 1.
  33998. * 00000011 = length 7 because there are 6 zeros before a 1.
  33999. *
  34000. * 2. The bits used for length are removed from the first byte
  34001. * Then all the bytes are merged into a value. NOTE: this
  34002. * is not the case for id ebml tags as there id includes
  34003. * length bits.
  34004. *
  34005. */
  34006. var findEbml = function findEbml(bytes, paths) {
  34007. paths = normalizePaths(paths);
  34008. bytes = toUint8(bytes);
  34009. var results = [];
  34010. if (!paths.length) {
  34011. return results;
  34012. }
  34013. var i = 0;
  34014. while (i < bytes.length) {
  34015. var id = getvint(bytes, i, false);
  34016. var dataHeader = getvint(bytes, i + id.length);
  34017. var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream
  34018. if (dataHeader.value === 0x7f) {
  34019. dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
  34020. if (dataHeader.value !== bytes.length) {
  34021. dataHeader.value -= dataStart;
  34022. }
  34023. }
  34024. var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
  34025. var data = bytes.subarray(dataStart, dataEnd);
  34026. if (bytesMatch(paths[0], id.bytes)) {
  34027. if (paths.length === 1) {
  34028. // this is the end of the paths and we've found the tag we were
  34029. // looking for
  34030. results.push(data);
  34031. } else {
  34032. // recursively search for the next tag inside of the data
  34033. // of this one
  34034. results = results.concat(findEbml(data, paths.slice(1)));
  34035. }
  34036. }
  34037. var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it
  34038. i += totalLength;
  34039. }
  34040. return results;
  34041. }; // see https://www.matroska.org/technical/basics.html#block-structure
  34042. var NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);
  34043. var NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);
  34044. var EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);
  34045. /**
  34046. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  34047. * Sequence Payload"
  34048. *
  34049. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  34050. * unit
  34051. * @return {Uint8Array} the RBSP without any Emulation
  34052. * Prevention Bytes
  34053. */
  34054. var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {
  34055. var positions = [];
  34056. var i = 1; // Find all `Emulation Prevention Bytes`
  34057. while (i < bytes.length - 2) {
  34058. if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
  34059. positions.push(i + 2);
  34060. i++;
  34061. }
  34062. i++;
  34063. } // If no Emulation Prevention Bytes were found just return the original
  34064. // array
  34065. if (positions.length === 0) {
  34066. return bytes;
  34067. } // Create a new array to hold the NAL unit data
  34068. var newLength = bytes.length - positions.length;
  34069. var newData = new Uint8Array(newLength);
  34070. var sourceIndex = 0;
  34071. for (i = 0; i < newLength; sourceIndex++, i++) {
  34072. if (sourceIndex === positions[0]) {
  34073. // Skip this byte
  34074. sourceIndex++; // Remove this position index
  34075. positions.shift();
  34076. }
  34077. newData[i] = bytes[sourceIndex];
  34078. }
  34079. return newData;
  34080. };
  34081. var findNal = function findNal(bytes, dataType, types, nalLimit) {
  34082. if (nalLimit === void 0) {
  34083. nalLimit = Infinity;
  34084. }
  34085. bytes = toUint8(bytes);
  34086. types = [].concat(types);
  34087. var i = 0;
  34088. var nalStart;
  34089. var nalsFound = 0; // keep searching until:
  34090. // we reach the end of bytes
  34091. // we reach the maximum number of nals they want to seach
  34092. // NOTE: that we disregard nalLimit when we have found the start
  34093. // of the nal we want so that we can find the end of the nal we want.
  34094. while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
  34095. var nalOffset = void 0;
  34096. if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
  34097. nalOffset = 4;
  34098. } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
  34099. nalOffset = 3;
  34100. } // we are unsynced,
  34101. // find the next nal unit
  34102. if (!nalOffset) {
  34103. i++;
  34104. continue;
  34105. }
  34106. nalsFound++;
  34107. if (nalStart) {
  34108. return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
  34109. }
  34110. var nalType = void 0;
  34111. if (dataType === 'h264') {
  34112. nalType = bytes[i + nalOffset] & 0x1f;
  34113. } else if (dataType === 'h265') {
  34114. nalType = bytes[i + nalOffset] >> 1 & 0x3f;
  34115. }
  34116. if (types.indexOf(nalType) !== -1) {
  34117. nalStart = i + nalOffset;
  34118. } // nal header is 1 length for h264, and 2 for h265
  34119. i += nalOffset + (dataType === 'h264' ? 1 : 2);
  34120. }
  34121. return bytes.subarray(0, 0);
  34122. };
  34123. var findH264Nal = function findH264Nal(bytes, type, nalLimit) {
  34124. return findNal(bytes, 'h264', type, nalLimit);
  34125. };
  34126. var findH265Nal = function findH265Nal(bytes, type, nalLimit) {
  34127. return findNal(bytes, 'h265', type, nalLimit);
  34128. };
  34129. var CONSTANTS = {
  34130. // "webm" string literal in hex
  34131. 'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),
  34132. // "matroska" string literal in hex
  34133. 'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
  34134. // "fLaC" string literal in hex
  34135. 'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),
  34136. // "OggS" string literal in hex
  34137. 'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),
  34138. // ac-3 sync byte, also works for ec-3 as that is simply a codec
  34139. // of ac-3
  34140. 'ac3': toUint8([0x0b, 0x77]),
  34141. // "RIFF" string literal in hex used for wav and avi
  34142. 'riff': toUint8([0x52, 0x49, 0x46, 0x46]),
  34143. // "AVI" string literal in hex
  34144. 'avi': toUint8([0x41, 0x56, 0x49]),
  34145. // "WAVE" string literal in hex
  34146. 'wav': toUint8([0x57, 0x41, 0x56, 0x45]),
  34147. // "ftyp3g" string literal in hex
  34148. '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
  34149. // "ftyp" string literal in hex
  34150. 'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),
  34151. // "styp" string literal in hex
  34152. 'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),
  34153. // "ftypqt" string literal in hex
  34154. 'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74]),
  34155. // moov string literal in hex
  34156. 'moov': toUint8([0x6D, 0x6F, 0x6F, 0x76]),
  34157. // moof string literal in hex
  34158. 'moof': toUint8([0x6D, 0x6F, 0x6F, 0x66])
  34159. };
  34160. var _isLikely = {
  34161. aac: function aac(bytes) {
  34162. var offset = getId3Offset(bytes);
  34163. return bytesMatch(bytes, [0xFF, 0x10], {
  34164. offset: offset,
  34165. mask: [0xFF, 0x16]
  34166. });
  34167. },
  34168. mp3: function mp3(bytes) {
  34169. var offset = getId3Offset(bytes);
  34170. return bytesMatch(bytes, [0xFF, 0x02], {
  34171. offset: offset,
  34172. mask: [0xFF, 0x06]
  34173. });
  34174. },
  34175. webm: function webm(bytes) {
  34176. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm
  34177. return bytesMatch(docType, CONSTANTS.webm);
  34178. },
  34179. mkv: function mkv(bytes) {
  34180. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska
  34181. return bytesMatch(docType, CONSTANTS.matroska);
  34182. },
  34183. mp4: function mp4(bytes) {
  34184. // if this file is another base media file format, it is not mp4
  34185. if (_isLikely['3gp'](bytes) || _isLikely.mov(bytes)) {
  34186. return false;
  34187. } // if this file starts with a ftyp or styp box its mp4
  34188. if (bytesMatch(bytes, CONSTANTS.mp4, {
  34189. offset: 4
  34190. }) || bytesMatch(bytes, CONSTANTS.fmp4, {
  34191. offset: 4
  34192. })) {
  34193. return true;
  34194. } // if this file starts with a moof/moov box its mp4
  34195. if (bytesMatch(bytes, CONSTANTS.moof, {
  34196. offset: 4
  34197. }) || bytesMatch(bytes, CONSTANTS.moov, {
  34198. offset: 4
  34199. })) {
  34200. return true;
  34201. }
  34202. },
  34203. mov: function mov(bytes) {
  34204. return bytesMatch(bytes, CONSTANTS.mov, {
  34205. offset: 4
  34206. });
  34207. },
  34208. '3gp': function gp(bytes) {
  34209. return bytesMatch(bytes, CONSTANTS['3gp'], {
  34210. offset: 4
  34211. });
  34212. },
  34213. ac3: function ac3(bytes) {
  34214. var offset = getId3Offset(bytes);
  34215. return bytesMatch(bytes, CONSTANTS.ac3, {
  34216. offset: offset
  34217. });
  34218. },
  34219. ts: function ts(bytes) {
  34220. if (bytes.length < 189 && bytes.length >= 1) {
  34221. return bytes[0] === 0x47;
  34222. }
  34223. var i = 0; // check the first 376 bytes for two matching sync bytes
  34224. while (i + 188 < bytes.length && i < 188) {
  34225. if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
  34226. return true;
  34227. }
  34228. i += 1;
  34229. }
  34230. return false;
  34231. },
  34232. flac: function flac(bytes) {
  34233. var offset = getId3Offset(bytes);
  34234. return bytesMatch(bytes, CONSTANTS.flac, {
  34235. offset: offset
  34236. });
  34237. },
  34238. ogg: function ogg(bytes) {
  34239. return bytesMatch(bytes, CONSTANTS.ogg);
  34240. },
  34241. avi: function avi(bytes) {
  34242. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {
  34243. offset: 8
  34244. });
  34245. },
  34246. wav: function wav(bytes) {
  34247. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {
  34248. offset: 8
  34249. });
  34250. },
  34251. 'h264': function h264(bytes) {
  34252. // find seq_parameter_set_rbsp
  34253. return findH264Nal(bytes, 7, 3).length;
  34254. },
  34255. 'h265': function h265(bytes) {
  34256. // find video_parameter_set_rbsp or seq_parameter_set_rbsp
  34257. return findH265Nal(bytes, [32, 33], 3).length;
  34258. }
  34259. }; // get all the isLikely functions
  34260. // but make sure 'ts' is above h264 and h265
  34261. // but below everything else as it is the least specific
  34262. var isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265
  34263. .filter(function (t) {
  34264. return t !== 'ts' && t !== 'h264' && t !== 'h265';
  34265. }) // add it back to the bottom
  34266. .concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.
  34267. isLikelyTypes.forEach(function (type) {
  34268. var isLikelyFn = _isLikely[type];
  34269. _isLikely[type] = function (bytes) {
  34270. return isLikelyFn(toUint8(bytes));
  34271. };
  34272. }); // export after wrapping
  34273. var isLikely = _isLikely; // A useful list of file signatures can be found here
  34274. // https://en.wikipedia.org/wiki/List_of_file_signatures
  34275. var detectContainerForBytes = function detectContainerForBytes(bytes) {
  34276. bytes = toUint8(bytes);
  34277. for (var i = 0; i < isLikelyTypes.length; i++) {
  34278. var type = isLikelyTypes[i];
  34279. if (isLikely[type](bytes)) {
  34280. return type;
  34281. }
  34282. }
  34283. return '';
  34284. }; // fmp4 is not a container
  34285. var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {
  34286. return findBox(bytes, ['moof']).length > 0;
  34287. };
  34288. /**
  34289. * mux.js
  34290. *
  34291. * Copyright (c) Brightcove
  34292. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  34293. */
  34294. var ONE_SECOND_IN_TS = 90000,
  34295. // 90kHz clock
  34296. secondsToVideoTs,
  34297. secondsToAudioTs,
  34298. videoTsToSeconds,
  34299. audioTsToSeconds,
  34300. audioTsToVideoTs,
  34301. videoTsToAudioTs,
  34302. metadataTsToSeconds;
  34303. secondsToVideoTs = function (seconds) {
  34304. return seconds * ONE_SECOND_IN_TS;
  34305. };
  34306. secondsToAudioTs = function (seconds, sampleRate) {
  34307. return seconds * sampleRate;
  34308. };
  34309. videoTsToSeconds = function (timestamp) {
  34310. return timestamp / ONE_SECOND_IN_TS;
  34311. };
  34312. audioTsToSeconds = function (timestamp, sampleRate) {
  34313. return timestamp / sampleRate;
  34314. };
  34315. audioTsToVideoTs = function (timestamp, sampleRate) {
  34316. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  34317. };
  34318. videoTsToAudioTs = function (timestamp, sampleRate) {
  34319. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  34320. };
  34321. /**
  34322. * Adjust ID3 tag or caption timing information by the timeline pts values
  34323. * (if keepOriginalTimestamps is false) and convert to seconds
  34324. */
  34325. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  34326. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  34327. };
  34328. var clock = {
  34329. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
  34330. secondsToVideoTs: secondsToVideoTs,
  34331. secondsToAudioTs: secondsToAudioTs,
  34332. videoTsToSeconds: videoTsToSeconds,
  34333. audioTsToSeconds: audioTsToSeconds,
  34334. audioTsToVideoTs: audioTsToVideoTs,
  34335. videoTsToAudioTs: videoTsToAudioTs,
  34336. metadataTsToSeconds: metadataTsToSeconds
  34337. };
  34338. var clock_1 = clock.ONE_SECOND_IN_TS;
  34339. /*! @name @videojs/http-streaming @version 3.0.2 @license Apache-2.0 */
  34340. /**
  34341. * @file resolve-url.js - Handling how URLs are resolved and manipulated
  34342. */
  34343. const resolveUrl = resolveUrl$2;
  34344. /**
  34345. * If the xhr request was redirected, return the responseURL, otherwise,
  34346. * return the original url.
  34347. *
  34348. * @api private
  34349. *
  34350. * @param {string} url - an url being requested
  34351. * @param {XMLHttpRequest} req - xhr request result
  34352. *
  34353. * @return {string}
  34354. */
  34355. const resolveManifestRedirect = (url, req) => {
  34356. // To understand how the responseURL below is set and generated:
  34357. // - https://fetch.spec.whatwg.org/#concept-response-url
  34358. // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
  34359. if (req && req.responseURL && url !== req.responseURL) {
  34360. return req.responseURL;
  34361. }
  34362. return url;
  34363. };
  34364. const logger = source => {
  34365. if (videojs.log.debug) {
  34366. return videojs.log.debug.bind(videojs, 'VHS:', `${source} >`);
  34367. }
  34368. return function () {};
  34369. };
  34370. /**
  34371. * Provides a compatibility layer between Video.js 7 and 8 API changes for VHS.
  34372. */
  34373. /**
  34374. * Delegates to videojs.obj.merge (Video.js 8) or
  34375. * videojs.mergeOptions (Video.js 7).
  34376. */
  34377. function merge(...args) {
  34378. const context = videojs.obj || videojs;
  34379. const fn = context.merge || context.mergeOptions;
  34380. return fn.apply(context, args);
  34381. }
  34382. /**
  34383. * Delegates to videojs.time.createTimeRanges (Video.js 8) or
  34384. * videojs.createTimeRanges (Video.js 7).
  34385. */
  34386. function createTimeRanges(...args) {
  34387. const context = videojs.time || videojs;
  34388. const fn = context.createTimeRanges || context.createTimeRanges;
  34389. return fn.apply(context, args);
  34390. }
  34391. /**
  34392. * ranges
  34393. *
  34394. * Utilities for working with TimeRanges.
  34395. *
  34396. */
  34397. const TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
  34398. // can be misleading because of precision differences or when the current media has poorly
  34399. // aligned audio and video, which can cause values to be slightly off from what you would
  34400. // expect. This value is what we consider to be safe to use in such comparisons to account
  34401. // for these scenarios.
  34402. const SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
  34403. const filterRanges = function (timeRanges, predicate) {
  34404. const results = [];
  34405. let i;
  34406. if (timeRanges && timeRanges.length) {
  34407. // Search for ranges that match the predicate
  34408. for (i = 0; i < timeRanges.length; i++) {
  34409. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  34410. results.push([timeRanges.start(i), timeRanges.end(i)]);
  34411. }
  34412. }
  34413. }
  34414. return createTimeRanges(results);
  34415. };
  34416. /**
  34417. * Attempts to find the buffered TimeRange that contains the specified
  34418. * time.
  34419. *
  34420. * @param {TimeRanges} buffered - the TimeRanges object to query
  34421. * @param {number} time - the time to filter on.
  34422. * @return {TimeRanges} a new TimeRanges object
  34423. */
  34424. const findRange = function (buffered, time) {
  34425. return filterRanges(buffered, function (start, end) {
  34426. return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  34427. });
  34428. };
  34429. /**
  34430. * Returns the TimeRanges that begin later than the specified time.
  34431. *
  34432. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  34433. * @param {number} time - the time to filter on.
  34434. * @return {TimeRanges} a new TimeRanges object.
  34435. */
  34436. const findNextRange = function (timeRanges, time) {
  34437. return filterRanges(timeRanges, function (start) {
  34438. return start - TIME_FUDGE_FACTOR >= time;
  34439. });
  34440. };
  34441. /**
  34442. * Returns gaps within a list of TimeRanges
  34443. *
  34444. * @param {TimeRanges} buffered - the TimeRanges object
  34445. * @return {TimeRanges} a TimeRanges object of gaps
  34446. */
  34447. const findGaps = function (buffered) {
  34448. if (buffered.length < 2) {
  34449. return createTimeRanges();
  34450. }
  34451. const ranges = [];
  34452. for (let i = 1; i < buffered.length; i++) {
  34453. const start = buffered.end(i - 1);
  34454. const end = buffered.start(i);
  34455. ranges.push([start, end]);
  34456. }
  34457. return createTimeRanges(ranges);
  34458. };
  34459. /**
  34460. * Calculate the intersection of two TimeRanges
  34461. *
  34462. * @param {TimeRanges} bufferA
  34463. * @param {TimeRanges} bufferB
  34464. * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
  34465. */
  34466. const bufferIntersection = function (bufferA, bufferB) {
  34467. let start = null;
  34468. let end = null;
  34469. let arity = 0;
  34470. const extents = [];
  34471. const ranges = [];
  34472. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  34473. return createTimeRanges();
  34474. } // Handle the case where we have both buffers and create an
  34475. // intersection of the two
  34476. let count = bufferA.length; // A) Gather up all start and end times
  34477. while (count--) {
  34478. extents.push({
  34479. time: bufferA.start(count),
  34480. type: 'start'
  34481. });
  34482. extents.push({
  34483. time: bufferA.end(count),
  34484. type: 'end'
  34485. });
  34486. }
  34487. count = bufferB.length;
  34488. while (count--) {
  34489. extents.push({
  34490. time: bufferB.start(count),
  34491. type: 'start'
  34492. });
  34493. extents.push({
  34494. time: bufferB.end(count),
  34495. type: 'end'
  34496. });
  34497. } // B) Sort them by time
  34498. extents.sort(function (a, b) {
  34499. return a.time - b.time;
  34500. }); // C) Go along one by one incrementing arity for start and decrementing
  34501. // arity for ends
  34502. for (count = 0; count < extents.length; count++) {
  34503. if (extents[count].type === 'start') {
  34504. arity++; // D) If arity is ever incremented to 2 we are entering an
  34505. // overlapping range
  34506. if (arity === 2) {
  34507. start = extents[count].time;
  34508. }
  34509. } else if (extents[count].type === 'end') {
  34510. arity--; // E) If arity is ever decremented to 1 we leaving an
  34511. // overlapping range
  34512. if (arity === 1) {
  34513. end = extents[count].time;
  34514. }
  34515. } // F) Record overlapping ranges
  34516. if (start !== null && end !== null) {
  34517. ranges.push([start, end]);
  34518. start = null;
  34519. end = null;
  34520. }
  34521. }
  34522. return createTimeRanges(ranges);
  34523. };
  34524. /**
  34525. * Gets a human readable string for a TimeRange
  34526. *
  34527. * @param {TimeRange} range
  34528. * @return {string} a human readable string
  34529. */
  34530. const printableRange = range => {
  34531. const strArr = [];
  34532. if (!range || !range.length) {
  34533. return '';
  34534. }
  34535. for (let i = 0; i < range.length; i++) {
  34536. strArr.push(range.start(i) + ' => ' + range.end(i));
  34537. }
  34538. return strArr.join(', ');
  34539. };
  34540. /**
  34541. * Calculates the amount of time left in seconds until the player hits the end of the
  34542. * buffer and causes a rebuffer
  34543. *
  34544. * @param {TimeRange} buffered
  34545. * The state of the buffer
  34546. * @param {Numnber} currentTime
  34547. * The current time of the player
  34548. * @param {number} playbackRate
  34549. * The current playback rate of the player. Defaults to 1.
  34550. * @return {number}
  34551. * Time until the player has to start rebuffering in seconds.
  34552. * @function timeUntilRebuffer
  34553. */
  34554. const timeUntilRebuffer = function (buffered, currentTime, playbackRate = 1) {
  34555. const bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  34556. return (bufferedEnd - currentTime) / playbackRate;
  34557. };
  34558. /**
  34559. * Converts a TimeRanges object into an array representation
  34560. *
  34561. * @param {TimeRanges} timeRanges
  34562. * @return {Array}
  34563. */
  34564. const timeRangesToArray = timeRanges => {
  34565. const timeRangesList = [];
  34566. for (let i = 0; i < timeRanges.length; i++) {
  34567. timeRangesList.push({
  34568. start: timeRanges.start(i),
  34569. end: timeRanges.end(i)
  34570. });
  34571. }
  34572. return timeRangesList;
  34573. };
  34574. /**
  34575. * Determines if two time range objects are different.
  34576. *
  34577. * @param {TimeRange} a
  34578. * the first time range object to check
  34579. *
  34580. * @param {TimeRange} b
  34581. * the second time range object to check
  34582. *
  34583. * @return {Boolean}
  34584. * Whether the time range objects differ
  34585. */
  34586. const isRangeDifferent = function (a, b) {
  34587. // same object
  34588. if (a === b) {
  34589. return false;
  34590. } // one or the other is undefined
  34591. if (!a && b || !b && a) {
  34592. return true;
  34593. } // length is different
  34594. if (a.length !== b.length) {
  34595. return true;
  34596. } // see if any start/end pair is different
  34597. for (let i = 0; i < a.length; i++) {
  34598. if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
  34599. return true;
  34600. }
  34601. } // if the length and every pair is the same
  34602. // this is the same time range
  34603. return false;
  34604. };
  34605. const lastBufferedEnd = function (a) {
  34606. if (!a || !a.length || !a.end) {
  34607. return;
  34608. }
  34609. return a.end(a.length - 1);
  34610. };
  34611. /**
  34612. * A utility function to add up the amount of time in a timeRange
  34613. * after a specified startTime.
  34614. * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0
  34615. * would return 40 as there are 40s seconds after 0 in the timeRange
  34616. *
  34617. * @param {TimeRange} range
  34618. * The range to check against
  34619. * @param {number} startTime
  34620. * The time in the time range that you should start counting from
  34621. *
  34622. * @return {number}
  34623. * The number of seconds in the buffer passed the specified time.
  34624. */
  34625. const timeAheadOf = function (range, startTime) {
  34626. let time = 0;
  34627. if (!range || !range.length) {
  34628. return time;
  34629. }
  34630. for (let i = 0; i < range.length; i++) {
  34631. const start = range.start(i);
  34632. const end = range.end(i); // startTime is after this range entirely
  34633. if (startTime > end) {
  34634. continue;
  34635. } // startTime is within this range
  34636. if (startTime > start && startTime <= end) {
  34637. time += end - startTime;
  34638. continue;
  34639. } // startTime is before this range.
  34640. time += end - start;
  34641. }
  34642. return time;
  34643. };
  34644. /**
  34645. * @file playlist.js
  34646. *
  34647. * Playlist related utilities.
  34648. */
  34649. /**
  34650. * Get the duration of a segment, with special cases for
  34651. * llhls segments that do not have a duration yet.
  34652. *
  34653. * @param {Object} playlist
  34654. * the playlist that the segment belongs to.
  34655. * @param {Object} segment
  34656. * the segment to get a duration for.
  34657. *
  34658. * @return {number}
  34659. * the segment duration
  34660. */
  34661. const segmentDurationWithParts = (playlist, segment) => {
  34662. // if this isn't a preload segment
  34663. // then we will have a segment duration that is accurate.
  34664. if (!segment.preload) {
  34665. return segment.duration;
  34666. } // otherwise we have to add up parts and preload hints
  34667. // to get an up to date duration.
  34668. let result = 0;
  34669. (segment.parts || []).forEach(function (p) {
  34670. result += p.duration;
  34671. }); // for preload hints we have to use partTargetDuration
  34672. // as they won't even have a duration yet.
  34673. (segment.preloadHints || []).forEach(function (p) {
  34674. if (p.type === 'PART') {
  34675. result += playlist.partTargetDuration;
  34676. }
  34677. });
  34678. return result;
  34679. };
  34680. /**
  34681. * A function to get a combined list of parts and segments with durations
  34682. * and indexes.
  34683. *
  34684. * @param {Playlist} playlist the playlist to get the list for.
  34685. *
  34686. * @return {Array} The part/segment list.
  34687. */
  34688. const getPartsAndSegments = playlist => (playlist.segments || []).reduce((acc, segment, si) => {
  34689. if (segment.parts) {
  34690. segment.parts.forEach(function (part, pi) {
  34691. acc.push({
  34692. duration: part.duration,
  34693. segmentIndex: si,
  34694. partIndex: pi,
  34695. part,
  34696. segment
  34697. });
  34698. });
  34699. } else {
  34700. acc.push({
  34701. duration: segment.duration,
  34702. segmentIndex: si,
  34703. partIndex: null,
  34704. segment,
  34705. part: null
  34706. });
  34707. }
  34708. return acc;
  34709. }, []);
  34710. const getLastParts = media => {
  34711. const lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  34712. return lastSegment && lastSegment.parts || [];
  34713. };
  34714. const getKnownPartCount = ({
  34715. preloadSegment
  34716. }) => {
  34717. if (!preloadSegment) {
  34718. return;
  34719. }
  34720. const {
  34721. parts,
  34722. preloadHints
  34723. } = preloadSegment;
  34724. let partCount = (preloadHints || []).reduce((count, hint) => count + (hint.type === 'PART' ? 1 : 0), 0);
  34725. partCount += parts && parts.length ? parts.length : 0;
  34726. return partCount;
  34727. };
  34728. /**
  34729. * Get the number of seconds to delay from the end of a
  34730. * live playlist.
  34731. *
  34732. * @param {Playlist} main the main playlist
  34733. * @param {Playlist} media the media playlist
  34734. * @return {number} the hold back in seconds.
  34735. */
  34736. const liveEdgeDelay = (main, media) => {
  34737. if (media.endList) {
  34738. return 0;
  34739. } // dash suggestedPresentationDelay trumps everything
  34740. if (main && main.suggestedPresentationDelay) {
  34741. return main.suggestedPresentationDelay;
  34742. }
  34743. const hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
  34744. if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
  34745. return media.serverControl.partHoldBack;
  34746. } else if (hasParts && media.partTargetDuration) {
  34747. return media.partTargetDuration * 3; // finally look for full segment delays
  34748. } else if (media.serverControl && media.serverControl.holdBack) {
  34749. return media.serverControl.holdBack;
  34750. } else if (media.targetDuration) {
  34751. return media.targetDuration * 3;
  34752. }
  34753. return 0;
  34754. };
  34755. /**
  34756. * walk backward until we find a duration we can use
  34757. * or return a failure
  34758. *
  34759. * @param {Playlist} playlist the playlist to walk through
  34760. * @param {Number} endSequence the mediaSequence to stop walking on
  34761. */
  34762. const backwardDuration = function (playlist, endSequence) {
  34763. let result = 0;
  34764. let i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
  34765. // the interval, use it
  34766. let segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
  34767. // information that is earlier than endSequence
  34768. if (segment) {
  34769. if (typeof segment.start !== 'undefined') {
  34770. return {
  34771. result: segment.start,
  34772. precise: true
  34773. };
  34774. }
  34775. if (typeof segment.end !== 'undefined') {
  34776. return {
  34777. result: segment.end - segment.duration,
  34778. precise: true
  34779. };
  34780. }
  34781. }
  34782. while (i--) {
  34783. segment = playlist.segments[i];
  34784. if (typeof segment.end !== 'undefined') {
  34785. return {
  34786. result: result + segment.end,
  34787. precise: true
  34788. };
  34789. }
  34790. result += segmentDurationWithParts(playlist, segment);
  34791. if (typeof segment.start !== 'undefined') {
  34792. return {
  34793. result: result + segment.start,
  34794. precise: true
  34795. };
  34796. }
  34797. }
  34798. return {
  34799. result,
  34800. precise: false
  34801. };
  34802. };
  34803. /**
  34804. * walk forward until we find a duration we can use
  34805. * or return a failure
  34806. *
  34807. * @param {Playlist} playlist the playlist to walk through
  34808. * @param {number} endSequence the mediaSequence to stop walking on
  34809. */
  34810. const forwardDuration = function (playlist, endSequence) {
  34811. let result = 0;
  34812. let segment;
  34813. let i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
  34814. // information
  34815. for (; i < playlist.segments.length; i++) {
  34816. segment = playlist.segments[i];
  34817. if (typeof segment.start !== 'undefined') {
  34818. return {
  34819. result: segment.start - result,
  34820. precise: true
  34821. };
  34822. }
  34823. result += segmentDurationWithParts(playlist, segment);
  34824. if (typeof segment.end !== 'undefined') {
  34825. return {
  34826. result: segment.end - result,
  34827. precise: true
  34828. };
  34829. }
  34830. } // indicate we didn't find a useful duration estimate
  34831. return {
  34832. result: -1,
  34833. precise: false
  34834. };
  34835. };
  34836. /**
  34837. * Calculate the media duration from the segments associated with a
  34838. * playlist. The duration of a subinterval of the available segments
  34839. * may be calculated by specifying an end index.
  34840. *
  34841. * @param {Object} playlist a media playlist object
  34842. * @param {number=} endSequence an exclusive upper boundary
  34843. * for the playlist. Defaults to playlist length.
  34844. * @param {number} expired the amount of time that has dropped
  34845. * off the front of the playlist in a live scenario
  34846. * @return {number} the duration between the first available segment
  34847. * and end index.
  34848. */
  34849. const intervalDuration = function (playlist, endSequence, expired) {
  34850. if (typeof endSequence === 'undefined') {
  34851. endSequence = playlist.mediaSequence + playlist.segments.length;
  34852. }
  34853. if (endSequence < playlist.mediaSequence) {
  34854. return 0;
  34855. } // do a backward walk to estimate the duration
  34856. const backward = backwardDuration(playlist, endSequence);
  34857. if (backward.precise) {
  34858. // if we were able to base our duration estimate on timing
  34859. // information provided directly from the Media Source, return
  34860. // it
  34861. return backward.result;
  34862. } // walk forward to see if a precise duration estimate can be made
  34863. // that way
  34864. const forward = forwardDuration(playlist, endSequence);
  34865. if (forward.precise) {
  34866. // we found a segment that has been buffered and so it's
  34867. // position is known precisely
  34868. return forward.result;
  34869. } // return the less-precise, playlist-based duration estimate
  34870. return backward.result + expired;
  34871. };
  34872. /**
  34873. * Calculates the duration of a playlist. If a start and end index
  34874. * are specified, the duration will be for the subset of the media
  34875. * timeline between those two indices. The total duration for live
  34876. * playlists is always Infinity.
  34877. *
  34878. * @param {Object} playlist a media playlist object
  34879. * @param {number=} endSequence an exclusive upper
  34880. * boundary for the playlist. Defaults to the playlist media
  34881. * sequence number plus its length.
  34882. * @param {number=} expired the amount of time that has
  34883. * dropped off the front of the playlist in a live scenario
  34884. * @return {number} the duration between the start index and end
  34885. * index.
  34886. */
  34887. const duration = function (playlist, endSequence, expired) {
  34888. if (!playlist) {
  34889. return 0;
  34890. }
  34891. if (typeof expired !== 'number') {
  34892. expired = 0;
  34893. } // if a slice of the total duration is not requested, use
  34894. // playlist-level duration indicators when they're present
  34895. if (typeof endSequence === 'undefined') {
  34896. // if present, use the duration specified in the playlist
  34897. if (playlist.totalDuration) {
  34898. return playlist.totalDuration;
  34899. } // duration should be Infinity for live playlists
  34900. if (!playlist.endList) {
  34901. return window.Infinity;
  34902. }
  34903. } // calculate the total duration based on the segment durations
  34904. return intervalDuration(playlist, endSequence, expired);
  34905. };
  34906. /**
  34907. * Calculate the time between two indexes in the current playlist
  34908. * neight the start- nor the end-index need to be within the current
  34909. * playlist in which case, the targetDuration of the playlist is used
  34910. * to approximate the durations of the segments
  34911. *
  34912. * @param {Array} options.durationList list to iterate over for durations.
  34913. * @param {number} options.defaultDuration duration to use for elements before or after the durationList
  34914. * @param {number} options.startIndex partsAndSegments index to start
  34915. * @param {number} options.endIndex partsAndSegments index to end.
  34916. * @return {number} the number of seconds between startIndex and endIndex
  34917. */
  34918. const sumDurations = function ({
  34919. defaultDuration,
  34920. durationList,
  34921. startIndex,
  34922. endIndex
  34923. }) {
  34924. let durations = 0;
  34925. if (startIndex > endIndex) {
  34926. [startIndex, endIndex] = [endIndex, startIndex];
  34927. }
  34928. if (startIndex < 0) {
  34929. for (let i = startIndex; i < Math.min(0, endIndex); i++) {
  34930. durations += defaultDuration;
  34931. }
  34932. startIndex = 0;
  34933. }
  34934. for (let i = startIndex; i < endIndex; i++) {
  34935. durations += durationList[i].duration;
  34936. }
  34937. return durations;
  34938. };
  34939. /**
  34940. * Calculates the playlist end time
  34941. *
  34942. * @param {Object} playlist a media playlist object
  34943. * @param {number=} expired the amount of time that has
  34944. * dropped off the front of the playlist in a live scenario
  34945. * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
  34946. * playlist end calculation should consider the safe live end
  34947. * (truncate the playlist end by three segments). This is normally
  34948. * used for calculating the end of the playlist's seekable range.
  34949. * This takes into account the value of liveEdgePadding.
  34950. * Setting liveEdgePadding to 0 is equivalent to setting this to false.
  34951. * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
  34952. * If this is provided, it is used in the safe live end calculation.
  34953. * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
  34954. * Corresponds to suggestedPresentationDelay in DASH manifests.
  34955. * @return {number} the end time of playlist
  34956. * @function playlistEnd
  34957. */
  34958. const playlistEnd = function (playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  34959. if (!playlist || !playlist.segments) {
  34960. return null;
  34961. }
  34962. if (playlist.endList) {
  34963. return duration(playlist);
  34964. }
  34965. if (expired === null) {
  34966. return null;
  34967. }
  34968. expired = expired || 0;
  34969. let lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  34970. if (useSafeLiveEnd) {
  34971. liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
  34972. lastSegmentEndTime -= liveEdgePadding;
  34973. } // don't return a time less than zero
  34974. return Math.max(0, lastSegmentEndTime);
  34975. };
  34976. /**
  34977. * Calculates the interval of time that is currently seekable in a
  34978. * playlist. The returned time ranges are relative to the earliest
  34979. * moment in the specified playlist that is still available. A full
  34980. * seekable implementation for live streams would need to offset
  34981. * these values by the duration of content that has expired from the
  34982. * stream.
  34983. *
  34984. * @param {Object} playlist a media playlist object
  34985. * dropped off the front of the playlist in a live scenario
  34986. * @param {number=} expired the amount of time that has
  34987. * dropped off the front of the playlist in a live scenario
  34988. * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
  34989. * Corresponds to suggestedPresentationDelay in DASH manifests.
  34990. * @return {TimeRanges} the periods of time that are valid targets
  34991. * for seeking
  34992. */
  34993. const seekable = function (playlist, expired, liveEdgePadding) {
  34994. const useSafeLiveEnd = true;
  34995. const seekableStart = expired || 0;
  34996. const seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  34997. if (seekableEnd === null) {
  34998. return createTimeRanges();
  34999. }
  35000. return createTimeRanges(seekableStart, seekableEnd);
  35001. };
  35002. /**
  35003. * Determine the index and estimated starting time of the segment that
  35004. * contains a specified playback position in a media playlist.
  35005. *
  35006. * @param {Object} options.playlist the media playlist to query
  35007. * @param {number} options.currentTime The number of seconds since the earliest
  35008. * possible position to determine the containing segment for
  35009. * @param {number} options.startTime the time when the segment/part starts
  35010. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  35011. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  35012. *
  35013. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  35014. */
  35015. const getMediaInfoForTime = function ({
  35016. playlist,
  35017. currentTime,
  35018. startingSegmentIndex,
  35019. startingPartIndex,
  35020. startTime,
  35021. exactManifestTimings
  35022. }) {
  35023. let time = currentTime - startTime;
  35024. const partsAndSegments = getPartsAndSegments(playlist);
  35025. let startIndex = 0;
  35026. for (let i = 0; i < partsAndSegments.length; i++) {
  35027. const partAndSegment = partsAndSegments[i];
  35028. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  35029. continue;
  35030. } // skip this if part index does not match.
  35031. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  35032. continue;
  35033. }
  35034. startIndex = i;
  35035. break;
  35036. }
  35037. if (time < 0) {
  35038. // Walk backward from startIndex in the playlist, adding durations
  35039. // until we find a segment that contains `time` and return it
  35040. if (startIndex > 0) {
  35041. for (let i = startIndex - 1; i >= 0; i--) {
  35042. const partAndSegment = partsAndSegments[i];
  35043. time += partAndSegment.duration;
  35044. if (exactManifestTimings) {
  35045. if (time < 0) {
  35046. continue;
  35047. }
  35048. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  35049. continue;
  35050. }
  35051. return {
  35052. partIndex: partAndSegment.partIndex,
  35053. segmentIndex: partAndSegment.segmentIndex,
  35054. startTime: startTime - sumDurations({
  35055. defaultDuration: playlist.targetDuration,
  35056. durationList: partsAndSegments,
  35057. startIndex,
  35058. endIndex: i
  35059. })
  35060. };
  35061. }
  35062. } // We were unable to find a good segment within the playlist
  35063. // so select the first segment
  35064. return {
  35065. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  35066. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  35067. startTime: currentTime
  35068. };
  35069. } // When startIndex is negative, we first walk forward to first segment
  35070. // adding target durations. If we "run out of time" before getting to
  35071. // the first segment, return the first segment
  35072. if (startIndex < 0) {
  35073. for (let i = startIndex; i < 0; i++) {
  35074. time -= playlist.targetDuration;
  35075. if (time < 0) {
  35076. return {
  35077. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  35078. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  35079. startTime: currentTime
  35080. };
  35081. }
  35082. }
  35083. startIndex = 0;
  35084. } // Walk forward from startIndex in the playlist, subtracting durations
  35085. // until we find a segment that contains `time` and return it
  35086. for (let i = startIndex; i < partsAndSegments.length; i++) {
  35087. const partAndSegment = partsAndSegments[i];
  35088. time -= partAndSegment.duration;
  35089. if (exactManifestTimings) {
  35090. if (time > 0) {
  35091. continue;
  35092. }
  35093. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  35094. continue;
  35095. }
  35096. return {
  35097. partIndex: partAndSegment.partIndex,
  35098. segmentIndex: partAndSegment.segmentIndex,
  35099. startTime: startTime + sumDurations({
  35100. defaultDuration: playlist.targetDuration,
  35101. durationList: partsAndSegments,
  35102. startIndex,
  35103. endIndex: i
  35104. })
  35105. };
  35106. } // We are out of possible candidates so load the last one...
  35107. return {
  35108. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  35109. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  35110. startTime: currentTime
  35111. };
  35112. };
  35113. /**
  35114. * Check whether the playlist is excluded or not.
  35115. *
  35116. * @param {Object} playlist the media playlist object
  35117. * @return {boolean} whether the playlist is excluded or not
  35118. * @function isExcluded
  35119. */
  35120. const isExcluded = function (playlist) {
  35121. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  35122. };
  35123. /**
  35124. * Check whether the playlist is compatible with current playback configuration or has
  35125. * been excluded permanently for being incompatible.
  35126. *
  35127. * @param {Object} playlist the media playlist object
  35128. * @return {boolean} whether the playlist is incompatible or not
  35129. * @function isIncompatible
  35130. */
  35131. const isIncompatible = function (playlist) {
  35132. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  35133. };
  35134. /**
  35135. * Check whether the playlist is enabled or not.
  35136. *
  35137. * @param {Object} playlist the media playlist object
  35138. * @return {boolean} whether the playlist is enabled or not
  35139. * @function isEnabled
  35140. */
  35141. const isEnabled = function (playlist) {
  35142. const excluded = isExcluded(playlist);
  35143. return !playlist.disabled && !excluded;
  35144. };
  35145. /**
  35146. * Check whether the playlist has been manually disabled through the representations api.
  35147. *
  35148. * @param {Object} playlist the media playlist object
  35149. * @return {boolean} whether the playlist is disabled manually or not
  35150. * @function isDisabled
  35151. */
  35152. const isDisabled = function (playlist) {
  35153. return playlist.disabled;
  35154. };
  35155. /**
  35156. * Returns whether the current playlist is an AES encrypted HLS stream
  35157. *
  35158. * @return {boolean} true if it's an AES encrypted HLS stream
  35159. */
  35160. const isAes = function (media) {
  35161. for (let i = 0; i < media.segments.length; i++) {
  35162. if (media.segments[i].key) {
  35163. return true;
  35164. }
  35165. }
  35166. return false;
  35167. };
  35168. /**
  35169. * Checks if the playlist has a value for the specified attribute
  35170. *
  35171. * @param {string} attr
  35172. * Attribute to check for
  35173. * @param {Object} playlist
  35174. * The media playlist object
  35175. * @return {boolean}
  35176. * Whether the playlist contains a value for the attribute or not
  35177. * @function hasAttribute
  35178. */
  35179. const hasAttribute = function (attr, playlist) {
  35180. return playlist.attributes && playlist.attributes[attr];
  35181. };
  35182. /**
  35183. * Estimates the time required to complete a segment download from the specified playlist
  35184. *
  35185. * @param {number} segmentDuration
  35186. * Duration of requested segment
  35187. * @param {number} bandwidth
  35188. * Current measured bandwidth of the player
  35189. * @param {Object} playlist
  35190. * The media playlist object
  35191. * @param {number=} bytesReceived
  35192. * Number of bytes already received for the request. Defaults to 0
  35193. * @return {number|NaN}
  35194. * The estimated time to request the segment. NaN if bandwidth information for
  35195. * the given playlist is unavailable
  35196. * @function estimateSegmentRequestTime
  35197. */
  35198. const estimateSegmentRequestTime = function (segmentDuration, bandwidth, playlist, bytesReceived = 0) {
  35199. if (!hasAttribute('BANDWIDTH', playlist)) {
  35200. return NaN;
  35201. }
  35202. const size = segmentDuration * playlist.attributes.BANDWIDTH;
  35203. return (size - bytesReceived * 8) / bandwidth;
  35204. };
  35205. /*
  35206. * Returns whether the current playlist is the lowest rendition
  35207. *
  35208. * @return {Boolean} true if on lowest rendition
  35209. */
  35210. const isLowestEnabledRendition = (main, media) => {
  35211. if (main.playlists.length === 1) {
  35212. return true;
  35213. }
  35214. const currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  35215. return main.playlists.filter(playlist => {
  35216. if (!isEnabled(playlist)) {
  35217. return false;
  35218. }
  35219. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  35220. }).length === 0;
  35221. };
  35222. const playlistMatch = (a, b) => {
  35223. // both playlits are null
  35224. // or only one playlist is non-null
  35225. // no match
  35226. if (!a && !b || !a && b || a && !b) {
  35227. return false;
  35228. } // playlist objects are the same, match
  35229. if (a === b) {
  35230. return true;
  35231. } // first try to use id as it should be the most
  35232. // accurate
  35233. if (a.id && b.id && a.id === b.id) {
  35234. return true;
  35235. } // next try to use reslovedUri as it should be the
  35236. // second most accurate.
  35237. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  35238. return true;
  35239. } // finally try to use uri as it should be accurate
  35240. // but might miss a few cases for relative uris
  35241. if (a.uri && b.uri && a.uri === b.uri) {
  35242. return true;
  35243. }
  35244. return false;
  35245. };
  35246. const someAudioVariant = function (main, callback) {
  35247. const AUDIO = main && main.mediaGroups && main.mediaGroups.AUDIO || {};
  35248. let found = false;
  35249. for (const groupName in AUDIO) {
  35250. for (const label in AUDIO[groupName]) {
  35251. found = callback(AUDIO[groupName][label]);
  35252. if (found) {
  35253. break;
  35254. }
  35255. }
  35256. if (found) {
  35257. break;
  35258. }
  35259. }
  35260. return !!found;
  35261. };
  35262. const isAudioOnly = main => {
  35263. // we are audio only if we have no main playlists but do
  35264. // have media group playlists.
  35265. if (!main || !main.playlists || !main.playlists.length) {
  35266. // without audio variants or playlists this
  35267. // is not an audio only main.
  35268. const found = someAudioVariant(main, variant => variant.playlists && variant.playlists.length || variant.uri);
  35269. return found;
  35270. } // if every playlist has only an audio codec it is audio only
  35271. for (let i = 0; i < main.playlists.length; i++) {
  35272. const playlist = main.playlists[i];
  35273. const CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  35274. if (CODECS && CODECS.split(',').every(c => isAudioCodec(c))) {
  35275. continue;
  35276. } // playlist is in an audio group it is audio only
  35277. const found = someAudioVariant(main, variant => playlistMatch(playlist, variant));
  35278. if (found) {
  35279. continue;
  35280. } // if we make it here this playlist isn't audio and we
  35281. // are not audio only
  35282. return false;
  35283. } // if we make it past every playlist without returning, then
  35284. // this is an audio only playlist.
  35285. return true;
  35286. }; // exports
  35287. var Playlist = {
  35288. liveEdgeDelay,
  35289. duration,
  35290. seekable,
  35291. getMediaInfoForTime,
  35292. isEnabled,
  35293. isDisabled,
  35294. isExcluded,
  35295. isIncompatible,
  35296. playlistEnd,
  35297. isAes,
  35298. hasAttribute,
  35299. estimateSegmentRequestTime,
  35300. isLowestEnabledRendition,
  35301. isAudioOnly,
  35302. playlistMatch,
  35303. segmentDurationWithParts
  35304. };
  35305. const {
  35306. log
  35307. } = videojs;
  35308. const createPlaylistID = (index, uri) => {
  35309. return `${index}-${uri}`;
  35310. }; // default function for creating a group id
  35311. const groupID = (type, group, label) => {
  35312. return `placeholder-uri-${type}-${group}-${label}`;
  35313. };
  35314. /**
  35315. * Parses a given m3u8 playlist
  35316. *
  35317. * @param {Function} [onwarn]
  35318. * a function to call when the parser triggers a warning event.
  35319. * @param {Function} [oninfo]
  35320. * a function to call when the parser triggers an info event.
  35321. * @param {string} manifestString
  35322. * The downloaded manifest string
  35323. * @param {Object[]} [customTagParsers]
  35324. * An array of custom tag parsers for the m3u8-parser instance
  35325. * @param {Object[]} [customTagMappers]
  35326. * An array of custom tag mappers for the m3u8-parser instance
  35327. * @param {boolean} [llhls]
  35328. * Whether to keep ll-hls features in the manifest after parsing.
  35329. * @return {Object}
  35330. * The manifest object
  35331. */
  35332. const parseManifest = ({
  35333. onwarn,
  35334. oninfo,
  35335. manifestString,
  35336. customTagParsers = [],
  35337. customTagMappers = [],
  35338. llhls
  35339. }) => {
  35340. const parser = new Parser();
  35341. if (onwarn) {
  35342. parser.on('warn', onwarn);
  35343. }
  35344. if (oninfo) {
  35345. parser.on('info', oninfo);
  35346. }
  35347. customTagParsers.forEach(customParser => parser.addParser(customParser));
  35348. customTagMappers.forEach(mapper => parser.addTagMapper(mapper));
  35349. parser.push(manifestString);
  35350. parser.end();
  35351. const manifest = parser.manifest; // remove llhls features from the parsed manifest
  35352. // if we don't want llhls support.
  35353. if (!llhls) {
  35354. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  35355. if (manifest.hasOwnProperty(k)) {
  35356. delete manifest[k];
  35357. }
  35358. });
  35359. if (manifest.segments) {
  35360. manifest.segments.forEach(function (segment) {
  35361. ['parts', 'preloadHints'].forEach(function (k) {
  35362. if (segment.hasOwnProperty(k)) {
  35363. delete segment[k];
  35364. }
  35365. });
  35366. });
  35367. }
  35368. }
  35369. if (!manifest.targetDuration) {
  35370. let targetDuration = 10;
  35371. if (manifest.segments && manifest.segments.length) {
  35372. targetDuration = manifest.segments.reduce((acc, s) => Math.max(acc, s.duration), 0);
  35373. }
  35374. if (onwarn) {
  35375. onwarn(`manifest has no targetDuration defaulting to ${targetDuration}`);
  35376. }
  35377. manifest.targetDuration = targetDuration;
  35378. }
  35379. const parts = getLastParts(manifest);
  35380. if (parts.length && !manifest.partTargetDuration) {
  35381. const partTargetDuration = parts.reduce((acc, p) => Math.max(acc, p.duration), 0);
  35382. if (onwarn) {
  35383. onwarn(`manifest has no partTargetDuration defaulting to ${partTargetDuration}`);
  35384. 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.');
  35385. }
  35386. manifest.partTargetDuration = partTargetDuration;
  35387. }
  35388. return manifest;
  35389. };
  35390. /**
  35391. * Loops through all supported media groups in main and calls the provided
  35392. * callback for each group
  35393. *
  35394. * @param {Object} main
  35395. * The parsed main manifest object
  35396. * @param {Function} callback
  35397. * Callback to call for each media group
  35398. */
  35399. const forEachMediaGroup = (main, callback) => {
  35400. if (!main.mediaGroups) {
  35401. return;
  35402. }
  35403. ['AUDIO', 'SUBTITLES'].forEach(mediaType => {
  35404. if (!main.mediaGroups[mediaType]) {
  35405. return;
  35406. }
  35407. for (const groupKey in main.mediaGroups[mediaType]) {
  35408. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  35409. const mediaProperties = main.mediaGroups[mediaType][groupKey][labelKey];
  35410. callback(mediaProperties, mediaType, groupKey, labelKey);
  35411. }
  35412. }
  35413. });
  35414. };
  35415. /**
  35416. * Adds properties and attributes to the playlist to keep consistent functionality for
  35417. * playlists throughout VHS.
  35418. *
  35419. * @param {Object} config
  35420. * Arguments object
  35421. * @param {Object} config.playlist
  35422. * The media playlist
  35423. * @param {string} [config.uri]
  35424. * The uri to the media playlist (if media playlist is not from within a main
  35425. * playlist)
  35426. * @param {string} id
  35427. * ID to use for the playlist
  35428. */
  35429. const setupMediaPlaylist = ({
  35430. playlist,
  35431. uri,
  35432. id
  35433. }) => {
  35434. playlist.id = id;
  35435. playlist.playlistErrors_ = 0;
  35436. if (uri) {
  35437. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  35438. // playlists do not contain their own source URI, but one is needed for consistency in
  35439. // VHS.
  35440. playlist.uri = uri;
  35441. } // For HLS main playlists, even though certain attributes MUST be defined, the
  35442. // stream may still be played without them.
  35443. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  35444. // manifest.
  35445. //
  35446. // To avoid undefined reference errors through the project, and make the code easier
  35447. // to write/read, add an empty attributes object for these cases.
  35448. playlist.attributes = playlist.attributes || {};
  35449. };
  35450. /**
  35451. * Adds ID, resolvedUri, and attributes properties to each playlist of the main, where
  35452. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  35453. * playlist references to the playlists array.
  35454. *
  35455. * @param {Object} main
  35456. * The main playlist
  35457. */
  35458. const setupMediaPlaylists = main => {
  35459. let i = main.playlists.length;
  35460. while (i--) {
  35461. const playlist = main.playlists[i];
  35462. setupMediaPlaylist({
  35463. playlist,
  35464. id: createPlaylistID(i, playlist.uri)
  35465. });
  35466. playlist.resolvedUri = resolveUrl(main.uri, playlist.uri);
  35467. main.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  35468. main.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  35469. // the stream can be played without it. Although an attributes property may have been
  35470. // added to the playlist to prevent undefined references, issue a warning to fix the
  35471. // manifest.
  35472. if (!playlist.attributes.BANDWIDTH) {
  35473. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  35474. }
  35475. }
  35476. };
  35477. /**
  35478. * Adds resolvedUri properties to each media group.
  35479. *
  35480. * @param {Object} main
  35481. * The main playlist
  35482. */
  35483. const resolveMediaGroupUris = main => {
  35484. forEachMediaGroup(main, properties => {
  35485. if (properties.uri) {
  35486. properties.resolvedUri = resolveUrl(main.uri, properties.uri);
  35487. }
  35488. });
  35489. };
  35490. /**
  35491. * Creates a main playlist wrapper to insert a sole media playlist into.
  35492. *
  35493. * @param {Object} media
  35494. * Media playlist
  35495. * @param {string} uri
  35496. * The media URI
  35497. *
  35498. * @return {Object}
  35499. * main playlist
  35500. */
  35501. const mainForMedia = (media, uri) => {
  35502. const id = createPlaylistID(0, uri);
  35503. const main = {
  35504. mediaGroups: {
  35505. 'AUDIO': {},
  35506. 'VIDEO': {},
  35507. 'CLOSED-CAPTIONS': {},
  35508. 'SUBTITLES': {}
  35509. },
  35510. uri: window.location.href,
  35511. resolvedUri: window.location.href,
  35512. playlists: [{
  35513. uri,
  35514. id,
  35515. resolvedUri: uri,
  35516. // m3u8-parser does not attach an attributes property to media playlists so make
  35517. // sure that the property is attached to avoid undefined reference errors
  35518. attributes: {}
  35519. }]
  35520. }; // set up ID reference
  35521. main.playlists[id] = main.playlists[0]; // URI reference added for backwards compatibility
  35522. main.playlists[uri] = main.playlists[0];
  35523. return main;
  35524. };
  35525. /**
  35526. * Does an in-place update of the main manifest to add updated playlist URI references
  35527. * as well as other properties needed by VHS that aren't included by the parser.
  35528. *
  35529. * @param {Object} main
  35530. * main manifest object
  35531. * @param {string} uri
  35532. * The source URI
  35533. * @param {function} createGroupID
  35534. * A function to determine how to create the groupID for mediaGroups
  35535. */
  35536. const addPropertiesToMain = (main, uri, createGroupID = groupID) => {
  35537. main.uri = uri;
  35538. for (let i = 0; i < main.playlists.length; i++) {
  35539. if (!main.playlists[i].uri) {
  35540. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  35541. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  35542. // TODO: consider adding dummy URIs in mpd-parser
  35543. const phonyUri = `placeholder-uri-${i}`;
  35544. main.playlists[i].uri = phonyUri;
  35545. }
  35546. }
  35547. const audioOnlyMain = isAudioOnly(main);
  35548. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  35549. // add a playlist array under properties
  35550. if (!properties.playlists || !properties.playlists.length) {
  35551. // If the manifest is audio only and this media group does not have a uri, check
  35552. // if the media group is located in the main list of playlists. If it is, don't add
  35553. // placeholder properties as it shouldn't be considered an alternate audio track.
  35554. if (audioOnlyMain && mediaType === 'AUDIO' && !properties.uri) {
  35555. for (let i = 0; i < main.playlists.length; i++) {
  35556. const p = main.playlists[i];
  35557. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  35558. return;
  35559. }
  35560. }
  35561. }
  35562. properties.playlists = [_extends$1({}, properties)];
  35563. }
  35564. properties.playlists.forEach(function (p, i) {
  35565. const groupId = createGroupID(mediaType, groupKey, labelKey, p);
  35566. const id = createPlaylistID(i, groupId);
  35567. if (p.uri) {
  35568. p.resolvedUri = p.resolvedUri || resolveUrl(main.uri, p.uri);
  35569. } else {
  35570. // DEPRECATED, this has been added to prevent a breaking change.
  35571. // previously we only ever had a single media group playlist, so
  35572. // we mark the first playlist uri without prepending the index as we used to
  35573. // ideally we would do all of the playlists the same way.
  35574. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  35575. // the placeholder again
  35576. p.resolvedUri = p.uri;
  35577. }
  35578. p.id = p.id || id; // add an empty attributes object, all playlists are
  35579. // expected to have this.
  35580. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  35581. main.playlists[p.id] = p;
  35582. main.playlists[p.uri] = p;
  35583. });
  35584. });
  35585. setupMediaPlaylists(main);
  35586. resolveMediaGroupUris(main);
  35587. };
  35588. /**
  35589. * @file playlist-loader.js
  35590. *
  35591. * A state machine that manages the loading, caching, and updating of
  35592. * M3U8 playlists.
  35593. *
  35594. */
  35595. const {
  35596. EventTarget: EventTarget$1
  35597. } = videojs;
  35598. const addLLHLSQueryDirectives = (uri, media) => {
  35599. if (media.endList || !media.serverControl) {
  35600. return uri;
  35601. }
  35602. const parameters = {};
  35603. if (media.serverControl.canBlockReload) {
  35604. const {
  35605. preloadSegment
  35606. } = media; // next msn is a zero based value, length is not.
  35607. let nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  35608. // that we are going to request a part of that preload segment.
  35609. // the logic below is used to determine that.
  35610. if (preloadSegment) {
  35611. const parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  35612. const nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  35613. // length of parts, then we know we had part preload hints
  35614. // and we need to add the _HLS_part= query
  35615. if (nextPart > -1 && nextPart !== parts.length - 1) {
  35616. // add existing parts to our preload hints
  35617. // eslint-disable-next-line
  35618. parameters._HLS_part = nextPart;
  35619. } // this if statement makes sure that we request the msn
  35620. // of the preload segment if:
  35621. // 1. the preload segment had parts (and was not yet a full segment)
  35622. // but was added to our segments array
  35623. // 2. the preload segment had preload hints for parts that are not in
  35624. // the manifest yet.
  35625. // in all other cases we want the segment after the preload segment
  35626. // which will be given by using media.segments.length because it is 1 based
  35627. // rather than 0 based.
  35628. if (nextPart > -1 || parts.length) {
  35629. nextMSN--;
  35630. }
  35631. } // add _HLS_msn= in front of any _HLS_part query
  35632. // eslint-disable-next-line
  35633. parameters._HLS_msn = nextMSN;
  35634. }
  35635. if (media.serverControl && media.serverControl.canSkipUntil) {
  35636. // add _HLS_skip= infront of all other queries.
  35637. // eslint-disable-next-line
  35638. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  35639. }
  35640. if (Object.keys(parameters).length) {
  35641. const parsedUri = new window.URL(uri);
  35642. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  35643. if (!parameters.hasOwnProperty(name)) {
  35644. return;
  35645. }
  35646. parsedUri.searchParams.set(name, parameters[name]);
  35647. });
  35648. uri = parsedUri.toString();
  35649. }
  35650. return uri;
  35651. };
  35652. /**
  35653. * Returns a new segment object with properties and
  35654. * the parts array merged.
  35655. *
  35656. * @param {Object} a the old segment
  35657. * @param {Object} b the new segment
  35658. *
  35659. * @return {Object} the merged segment
  35660. */
  35661. const updateSegment = (a, b) => {
  35662. if (!a) {
  35663. return b;
  35664. }
  35665. const result = merge(a, b); // if only the old segment has preload hints
  35666. // and the new one does not, remove preload hints.
  35667. if (a.preloadHints && !b.preloadHints) {
  35668. delete result.preloadHints;
  35669. } // if only the old segment has parts
  35670. // then the parts are no longer valid
  35671. if (a.parts && !b.parts) {
  35672. delete result.parts; // if both segments have parts
  35673. // copy part propeties from the old segment
  35674. // to the new one.
  35675. } else if (a.parts && b.parts) {
  35676. for (let i = 0; i < b.parts.length; i++) {
  35677. if (a.parts && a.parts[i]) {
  35678. result.parts[i] = merge(a.parts[i], b.parts[i]);
  35679. }
  35680. }
  35681. } // set skipped to false for segments that have
  35682. // have had information merged from the old segment.
  35683. if (!a.skipped && b.skipped) {
  35684. result.skipped = false;
  35685. } // set preload to false for segments that have
  35686. // had information added in the new segment.
  35687. if (a.preload && !b.preload) {
  35688. result.preload = false;
  35689. }
  35690. return result;
  35691. };
  35692. /**
  35693. * Returns a new array of segments that is the result of merging
  35694. * properties from an older list of segments onto an updated
  35695. * list. No properties on the updated playlist will be ovewritten.
  35696. *
  35697. * @param {Array} original the outdated list of segments
  35698. * @param {Array} update the updated list of segments
  35699. * @param {number=} offset the index of the first update
  35700. * segment in the original segment list. For non-live playlists,
  35701. * this should always be zero and does not need to be
  35702. * specified. For live playlists, it should be the difference
  35703. * between the media sequence numbers in the original and updated
  35704. * playlists.
  35705. * @return {Array} a list of merged segment objects
  35706. */
  35707. const updateSegments = (original, update, offset) => {
  35708. const oldSegments = original.slice();
  35709. const newSegments = update.slice();
  35710. offset = offset || 0;
  35711. const result = [];
  35712. let currentMap;
  35713. for (let newIndex = 0; newIndex < newSegments.length; newIndex++) {
  35714. const oldSegment = oldSegments[newIndex + offset];
  35715. const newSegment = newSegments[newIndex];
  35716. if (oldSegment) {
  35717. currentMap = oldSegment.map || currentMap;
  35718. result.push(updateSegment(oldSegment, newSegment));
  35719. } else {
  35720. // carry over map to new segment if it is missing
  35721. if (currentMap && !newSegment.map) {
  35722. newSegment.map = currentMap;
  35723. }
  35724. result.push(newSegment);
  35725. }
  35726. }
  35727. return result;
  35728. };
  35729. const resolveSegmentUris = (segment, baseUri) => {
  35730. // preloadSegment will not have a uri at all
  35731. // as the segment isn't actually in the manifest yet, only parts
  35732. if (!segment.resolvedUri && segment.uri) {
  35733. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  35734. }
  35735. if (segment.key && !segment.key.resolvedUri) {
  35736. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  35737. }
  35738. if (segment.map && !segment.map.resolvedUri) {
  35739. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  35740. }
  35741. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  35742. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  35743. }
  35744. if (segment.parts && segment.parts.length) {
  35745. segment.parts.forEach(p => {
  35746. if (p.resolvedUri) {
  35747. return;
  35748. }
  35749. p.resolvedUri = resolveUrl(baseUri, p.uri);
  35750. });
  35751. }
  35752. if (segment.preloadHints && segment.preloadHints.length) {
  35753. segment.preloadHints.forEach(p => {
  35754. if (p.resolvedUri) {
  35755. return;
  35756. }
  35757. p.resolvedUri = resolveUrl(baseUri, p.uri);
  35758. });
  35759. }
  35760. };
  35761. const getAllSegments = function (media) {
  35762. const segments = media.segments || [];
  35763. const preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  35764. // a usable segment, only include a preloadSegment that has
  35765. // parts.
  35766. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  35767. // if preloadHints has a MAP that means that the
  35768. // init segment is going to change. We cannot use any of the parts
  35769. // from this preload segment.
  35770. if (preloadSegment.preloadHints) {
  35771. for (let i = 0; i < preloadSegment.preloadHints.length; i++) {
  35772. if (preloadSegment.preloadHints[i].type === 'MAP') {
  35773. return segments;
  35774. }
  35775. }
  35776. } // set the duration for our preload segment to target duration.
  35777. preloadSegment.duration = media.targetDuration;
  35778. preloadSegment.preload = true;
  35779. segments.push(preloadSegment);
  35780. }
  35781. return segments;
  35782. }; // consider the playlist unchanged if the playlist object is the same or
  35783. // the number of segments is equal, the media sequence number is unchanged,
  35784. // and this playlist hasn't become the end of the playlist
  35785. 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;
  35786. /**
  35787. * Returns a new main playlist that is the result of merging an
  35788. * updated media playlist into the original version. If the
  35789. * updated media playlist does not match any of the playlist
  35790. * entries in the original main playlist, null is returned.
  35791. *
  35792. * @param {Object} main a parsed main M3U8 object
  35793. * @param {Object} media a parsed media M3U8 object
  35794. * @return {Object} a new object that represents the original
  35795. * main playlist with the updated media playlist merged in, or
  35796. * null if the merge produced no change.
  35797. */
  35798. const updateMain$1 = (main, newMedia, unchangedCheck = isPlaylistUnchanged) => {
  35799. const result = merge(main, {});
  35800. const oldMedia = result.playlists[newMedia.id];
  35801. if (!oldMedia) {
  35802. return null;
  35803. }
  35804. if (unchangedCheck(oldMedia, newMedia)) {
  35805. return null;
  35806. }
  35807. newMedia.segments = getAllSegments(newMedia);
  35808. const mergedPlaylist = merge(oldMedia, newMedia); // always use the new media's preload segment
  35809. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  35810. delete mergedPlaylist.preloadSegment;
  35811. } // if the update could overlap existing segment information, merge the two segment lists
  35812. if (oldMedia.segments) {
  35813. if (newMedia.skip) {
  35814. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  35815. // old properties into the new segments
  35816. for (let i = 0; i < newMedia.skip.skippedSegments; i++) {
  35817. newMedia.segments.unshift({
  35818. skipped: true
  35819. });
  35820. }
  35821. }
  35822. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  35823. } // resolve any segment URIs to prevent us from having to do it later
  35824. mergedPlaylist.segments.forEach(segment => {
  35825. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  35826. }); // TODO Right now in the playlists array there are two references to each playlist, one
  35827. // that is referenced by index, and one by URI. The index reference may no longer be
  35828. // necessary.
  35829. for (let i = 0; i < result.playlists.length; i++) {
  35830. if (result.playlists[i].id === newMedia.id) {
  35831. result.playlists[i] = mergedPlaylist;
  35832. }
  35833. }
  35834. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  35835. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  35836. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  35837. if (!properties.playlists) {
  35838. return;
  35839. }
  35840. for (let i = 0; i < properties.playlists.length; i++) {
  35841. if (newMedia.id === properties.playlists[i].id) {
  35842. properties.playlists[i] = mergedPlaylist;
  35843. }
  35844. }
  35845. });
  35846. return result;
  35847. };
  35848. /**
  35849. * Calculates the time to wait before refreshing a live playlist
  35850. *
  35851. * @param {Object} media
  35852. * The current media
  35853. * @param {boolean} update
  35854. * True if there were any updates from the last refresh, false otherwise
  35855. * @return {number}
  35856. * The time in ms to wait before refreshing the live playlist
  35857. */
  35858. const refreshDelay = (media, update) => {
  35859. const segments = media.segments || [];
  35860. const lastSegment = segments[segments.length - 1];
  35861. const lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  35862. const lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  35863. if (update && lastDuration) {
  35864. return lastDuration * 1000;
  35865. } // if the playlist is unchanged since the last reload or last segment duration
  35866. // cannot be determined, try again after half the target duration
  35867. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  35868. };
  35869. /**
  35870. * Load a playlist from a remote location
  35871. *
  35872. * @class PlaylistLoader
  35873. * @extends Stream
  35874. * @param {string|Object} src url or object of manifest
  35875. * @param {boolean} withCredentials the withCredentials xhr option
  35876. * @class
  35877. */
  35878. class PlaylistLoader extends EventTarget$1 {
  35879. constructor(src, vhs, options = {}) {
  35880. super();
  35881. if (!src) {
  35882. throw new Error('A non-empty playlist URL or object is required');
  35883. }
  35884. this.logger_ = logger('PlaylistLoader');
  35885. const {
  35886. withCredentials = false
  35887. } = options;
  35888. this.src = src;
  35889. this.vhs_ = vhs;
  35890. this.withCredentials = withCredentials;
  35891. const vhsOptions = vhs.options_;
  35892. this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  35893. this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  35894. this.llhls = vhsOptions && vhsOptions.llhls; // initialize the loader state
  35895. this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  35896. this.handleMediaupdatetimeout_ = this.handleMediaupdatetimeout_.bind(this);
  35897. this.on('mediaupdatetimeout', this.handleMediaupdatetimeout_);
  35898. }
  35899. handleMediaupdatetimeout_() {
  35900. if (this.state !== 'HAVE_METADATA') {
  35901. // only refresh the media playlist if no other activity is going on
  35902. return;
  35903. }
  35904. const media = this.media();
  35905. let uri = resolveUrl(this.main.uri, media.uri);
  35906. if (this.llhls) {
  35907. uri = addLLHLSQueryDirectives(uri, media);
  35908. }
  35909. this.state = 'HAVE_CURRENT_METADATA';
  35910. this.request = this.vhs_.xhr({
  35911. uri,
  35912. withCredentials: this.withCredentials
  35913. }, (error, req) => {
  35914. // disposed
  35915. if (!this.request) {
  35916. return;
  35917. }
  35918. if (error) {
  35919. return this.playlistRequestError(this.request, this.media(), 'HAVE_METADATA');
  35920. }
  35921. this.haveMetadata({
  35922. playlistString: this.request.responseText,
  35923. url: this.media().uri,
  35924. id: this.media().id
  35925. });
  35926. });
  35927. }
  35928. playlistRequestError(xhr, playlist, startingState) {
  35929. const {
  35930. uri,
  35931. id
  35932. } = playlist; // any in-flight request is now finished
  35933. this.request = null;
  35934. if (startingState) {
  35935. this.state = startingState;
  35936. }
  35937. this.error = {
  35938. playlist: this.main.playlists[id],
  35939. status: xhr.status,
  35940. message: `HLS playlist request error at URL: ${uri}.`,
  35941. responseText: xhr.responseText,
  35942. code: xhr.status >= 500 ? 4 : 2
  35943. };
  35944. this.trigger('error');
  35945. }
  35946. parseManifest_({
  35947. url,
  35948. manifestString
  35949. }) {
  35950. return parseManifest({
  35951. onwarn: ({
  35952. message
  35953. }) => this.logger_(`m3u8-parser warn for ${url}: ${message}`),
  35954. oninfo: ({
  35955. message
  35956. }) => this.logger_(`m3u8-parser info for ${url}: ${message}`),
  35957. manifestString,
  35958. customTagParsers: this.customTagParsers,
  35959. customTagMappers: this.customTagMappers,
  35960. llhls: this.llhls
  35961. });
  35962. }
  35963. /**
  35964. * Update the playlist loader's state in response to a new or updated playlist.
  35965. *
  35966. * @param {string} [playlistString]
  35967. * Playlist string (if playlistObject is not provided)
  35968. * @param {Object} [playlistObject]
  35969. * Playlist object (if playlistString is not provided)
  35970. * @param {string} url
  35971. * URL of playlist
  35972. * @param {string} id
  35973. * ID to use for playlist
  35974. */
  35975. haveMetadata({
  35976. playlistString,
  35977. playlistObject,
  35978. url,
  35979. id
  35980. }) {
  35981. // any in-flight request is now finished
  35982. this.request = null;
  35983. this.state = 'HAVE_METADATA';
  35984. const playlist = playlistObject || this.parseManifest_({
  35985. url,
  35986. manifestString: playlistString
  35987. });
  35988. playlist.lastRequest = Date.now();
  35989. setupMediaPlaylist({
  35990. playlist,
  35991. uri: url,
  35992. id
  35993. }); // merge this playlist into the main manifest
  35994. const update = updateMain$1(this.main, playlist);
  35995. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  35996. this.pendingMedia_ = null;
  35997. if (update) {
  35998. this.main = update;
  35999. this.media_ = this.main.playlists[id];
  36000. } else {
  36001. this.trigger('playlistunchanged');
  36002. }
  36003. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  36004. this.trigger('loadedplaylist');
  36005. }
  36006. /**
  36007. * Abort any outstanding work and clean up.
  36008. */
  36009. dispose() {
  36010. this.trigger('dispose');
  36011. this.stopRequest();
  36012. window.clearTimeout(this.mediaUpdateTimeout);
  36013. window.clearTimeout(this.finalRenditionTimeout);
  36014. this.off();
  36015. }
  36016. stopRequest() {
  36017. if (this.request) {
  36018. const oldRequest = this.request;
  36019. this.request = null;
  36020. oldRequest.onreadystatechange = null;
  36021. oldRequest.abort();
  36022. }
  36023. }
  36024. /**
  36025. * When called without any arguments, returns the currently
  36026. * active media playlist. When called with a single argument,
  36027. * triggers the playlist loader to asynchronously switch to the
  36028. * specified media playlist. Calling this method while the
  36029. * loader is in the HAVE_NOTHING causes an error to be emitted
  36030. * but otherwise has no effect.
  36031. *
  36032. * @param {Object=} playlist the parsed media playlist
  36033. * object to switch to
  36034. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  36035. *
  36036. * @return {Playlist} the current loaded media
  36037. */
  36038. media(playlist, shouldDelay) {
  36039. // getter
  36040. if (!playlist) {
  36041. return this.media_;
  36042. } // setter
  36043. if (this.state === 'HAVE_NOTHING') {
  36044. throw new Error('Cannot switch media playlist from ' + this.state);
  36045. } // find the playlist object if the target playlist has been
  36046. // specified by URI
  36047. if (typeof playlist === 'string') {
  36048. if (!this.main.playlists[playlist]) {
  36049. throw new Error('Unknown playlist URI: ' + playlist);
  36050. }
  36051. playlist = this.main.playlists[playlist];
  36052. }
  36053. window.clearTimeout(this.finalRenditionTimeout);
  36054. if (shouldDelay) {
  36055. const delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  36056. this.finalRenditionTimeout = window.setTimeout(this.media.bind(this, playlist, false), delay);
  36057. return;
  36058. }
  36059. const startingState = this.state;
  36060. const mediaChange = !this.media_ || playlist.id !== this.media_.id;
  36061. const mainPlaylistRef = this.main.playlists[playlist.id]; // switch to fully loaded playlists immediately
  36062. if (mainPlaylistRef && mainPlaylistRef.endList ||
  36063. // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  36064. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  36065. playlist.endList && playlist.segments.length) {
  36066. // abort outstanding playlist requests
  36067. if (this.request) {
  36068. this.request.onreadystatechange = null;
  36069. this.request.abort();
  36070. this.request = null;
  36071. }
  36072. this.state = 'HAVE_METADATA';
  36073. this.media_ = playlist; // trigger media change if the active media has been updated
  36074. if (mediaChange) {
  36075. this.trigger('mediachanging');
  36076. if (startingState === 'HAVE_MAIN_MANIFEST') {
  36077. // The initial playlist was a main manifest, and the first media selected was
  36078. // also provided (in the form of a resolved playlist object) as part of the
  36079. // source object (rather than just a URL). Therefore, since the media playlist
  36080. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  36081. // normal flow, and needs an explicit trigger here.
  36082. this.trigger('loadedmetadata');
  36083. } else {
  36084. this.trigger('mediachange');
  36085. }
  36086. }
  36087. return;
  36088. } // We update/set the timeout here so that live playlists
  36089. // that are not a media change will "start" the loader as expected.
  36090. // We expect that this function will start the media update timeout
  36091. // cycle again. This also prevents a playlist switch failure from
  36092. // causing us to stall during live.
  36093. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  36094. if (!mediaChange) {
  36095. return;
  36096. }
  36097. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  36098. if (this.request) {
  36099. if (playlist.resolvedUri === this.request.url) {
  36100. // requesting to switch to the same playlist multiple times
  36101. // has no effect after the first
  36102. return;
  36103. }
  36104. this.request.onreadystatechange = null;
  36105. this.request.abort();
  36106. this.request = null;
  36107. } // request the new playlist
  36108. if (this.media_) {
  36109. this.trigger('mediachanging');
  36110. }
  36111. this.pendingMedia_ = playlist;
  36112. this.request = this.vhs_.xhr({
  36113. uri: playlist.resolvedUri,
  36114. withCredentials: this.withCredentials
  36115. }, (error, req) => {
  36116. // disposed
  36117. if (!this.request) {
  36118. return;
  36119. }
  36120. playlist.lastRequest = Date.now();
  36121. playlist.resolvedUri = resolveManifestRedirect(playlist.resolvedUri, req);
  36122. if (error) {
  36123. return this.playlistRequestError(this.request, playlist, startingState);
  36124. }
  36125. this.haveMetadata({
  36126. playlistString: req.responseText,
  36127. url: playlist.uri,
  36128. id: playlist.id
  36129. }); // fire loadedmetadata the first time a media playlist is loaded
  36130. if (startingState === 'HAVE_MAIN_MANIFEST') {
  36131. this.trigger('loadedmetadata');
  36132. } else {
  36133. this.trigger('mediachange');
  36134. }
  36135. });
  36136. }
  36137. /**
  36138. * pause loading of the playlist
  36139. */
  36140. pause() {
  36141. if (this.mediaUpdateTimeout) {
  36142. window.clearTimeout(this.mediaUpdateTimeout);
  36143. this.mediaUpdateTimeout = null;
  36144. }
  36145. this.stopRequest();
  36146. if (this.state === 'HAVE_NOTHING') {
  36147. // If we pause the loader before any data has been retrieved, its as if we never
  36148. // started, so reset to an unstarted state.
  36149. this.started = false;
  36150. } // Need to restore state now that no activity is happening
  36151. if (this.state === 'SWITCHING_MEDIA') {
  36152. // if the loader was in the process of switching media, it should either return to
  36153. // HAVE_MAIN_MANIFEST or HAVE_METADATA depending on if the loader has loaded a media
  36154. // playlist yet. This is determined by the existence of loader.media_
  36155. if (this.media_) {
  36156. this.state = 'HAVE_METADATA';
  36157. } else {
  36158. this.state = 'HAVE_MAIN_MANIFEST';
  36159. }
  36160. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  36161. this.state = 'HAVE_METADATA';
  36162. }
  36163. }
  36164. /**
  36165. * start loading of the playlist
  36166. */
  36167. load(shouldDelay) {
  36168. if (this.mediaUpdateTimeout) {
  36169. window.clearTimeout(this.mediaUpdateTimeout);
  36170. this.mediaUpdateTimeout = null;
  36171. }
  36172. const media = this.media();
  36173. if (shouldDelay) {
  36174. const delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  36175. this.mediaUpdateTimeout = window.setTimeout(() => {
  36176. this.mediaUpdateTimeout = null;
  36177. this.load();
  36178. }, delay);
  36179. return;
  36180. }
  36181. if (!this.started) {
  36182. this.start();
  36183. return;
  36184. }
  36185. if (media && !media.endList) {
  36186. this.trigger('mediaupdatetimeout');
  36187. } else {
  36188. this.trigger('loadedplaylist');
  36189. }
  36190. }
  36191. updateMediaUpdateTimeout_(delay) {
  36192. if (this.mediaUpdateTimeout) {
  36193. window.clearTimeout(this.mediaUpdateTimeout);
  36194. this.mediaUpdateTimeout = null;
  36195. } // we only have use mediaupdatetimeout for live playlists.
  36196. if (!this.media() || this.media().endList) {
  36197. return;
  36198. }
  36199. this.mediaUpdateTimeout = window.setTimeout(() => {
  36200. this.mediaUpdateTimeout = null;
  36201. this.trigger('mediaupdatetimeout');
  36202. this.updateMediaUpdateTimeout_(delay);
  36203. }, delay);
  36204. }
  36205. /**
  36206. * start loading of the playlist
  36207. */
  36208. start() {
  36209. this.started = true;
  36210. if (typeof this.src === 'object') {
  36211. // in the case of an entirely constructed manifest object (meaning there's no actual
  36212. // manifest on a server), default the uri to the page's href
  36213. if (!this.src.uri) {
  36214. this.src.uri = window.location.href;
  36215. } // resolvedUri is added on internally after the initial request. Since there's no
  36216. // request for pre-resolved manifests, add on resolvedUri here.
  36217. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  36218. // request can be skipped (since the top level of the manifest, at a minimum, is
  36219. // already available as a parsed manifest object). However, if the manifest object
  36220. // represents a main playlist, some media playlists may need to be resolved before
  36221. // the starting segment list is available. Therefore, go directly to setup of the
  36222. // initial playlist, and let the normal flow continue from there.
  36223. //
  36224. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  36225. // that the first request is asynchronous.
  36226. setTimeout(() => {
  36227. this.setupInitialPlaylist(this.src);
  36228. }, 0);
  36229. return;
  36230. } // request the specified URL
  36231. this.request = this.vhs_.xhr({
  36232. uri: this.src,
  36233. withCredentials: this.withCredentials
  36234. }, (error, req) => {
  36235. // disposed
  36236. if (!this.request) {
  36237. return;
  36238. } // clear the loader's request reference
  36239. this.request = null;
  36240. if (error) {
  36241. this.error = {
  36242. status: req.status,
  36243. message: `HLS playlist request error at URL: ${this.src}.`,
  36244. responseText: req.responseText,
  36245. // MEDIA_ERR_NETWORK
  36246. code: 2
  36247. };
  36248. if (this.state === 'HAVE_NOTHING') {
  36249. this.started = false;
  36250. }
  36251. return this.trigger('error');
  36252. }
  36253. this.src = resolveManifestRedirect(this.src, req);
  36254. const manifest = this.parseManifest_({
  36255. manifestString: req.responseText,
  36256. url: this.src
  36257. });
  36258. this.setupInitialPlaylist(manifest);
  36259. });
  36260. }
  36261. srcUri() {
  36262. return typeof this.src === 'string' ? this.src : this.src.uri;
  36263. }
  36264. /**
  36265. * Given a manifest object that's either a main or media playlist, trigger the proper
  36266. * events and set the state of the playlist loader.
  36267. *
  36268. * If the manifest object represents a main playlist, `loadedplaylist` will be
  36269. * triggered to allow listeners to select a playlist. If none is selected, the loader
  36270. * will default to the first one in the playlists array.
  36271. *
  36272. * If the manifest object represents a media playlist, `loadedplaylist` will be
  36273. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  36274. *
  36275. * In the case of a media playlist, a main playlist object wrapper with one playlist
  36276. * will be created so that all logic can handle playlists in the same fashion (as an
  36277. * assumed manifest object schema).
  36278. *
  36279. * @param {Object} manifest
  36280. * The parsed manifest object
  36281. */
  36282. setupInitialPlaylist(manifest) {
  36283. this.state = 'HAVE_MAIN_MANIFEST';
  36284. if (manifest.playlists) {
  36285. this.main = manifest;
  36286. addPropertiesToMain(this.main, this.srcUri()); // If the initial main playlist has playlists wtih segments already resolved,
  36287. // then resolve URIs in advance, as they are usually done after a playlist request,
  36288. // which may not happen if the playlist is resolved.
  36289. manifest.playlists.forEach(playlist => {
  36290. playlist.segments = getAllSegments(playlist);
  36291. playlist.segments.forEach(segment => {
  36292. resolveSegmentUris(segment, playlist.resolvedUri);
  36293. });
  36294. });
  36295. this.trigger('loadedplaylist');
  36296. if (!this.request) {
  36297. // no media playlist was specifically selected so start
  36298. // from the first listed one
  36299. this.media(this.main.playlists[0]);
  36300. }
  36301. return;
  36302. } // In order to support media playlists passed in as vhs-json, the case where the uri
  36303. // is not provided as part of the manifest should be considered, and an appropriate
  36304. // default used.
  36305. const uri = this.srcUri() || window.location.href;
  36306. this.main = mainForMedia(manifest, uri);
  36307. this.haveMetadata({
  36308. playlistObject: manifest,
  36309. url: uri,
  36310. id: this.main.playlists[0].id
  36311. });
  36312. this.trigger('loadedmetadata');
  36313. }
  36314. }
  36315. /**
  36316. * @file xhr.js
  36317. */
  36318. const {
  36319. xhr: videojsXHR
  36320. } = videojs;
  36321. const callbackWrapper = function (request, error, response, callback) {
  36322. const reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  36323. if (!error && reqResponse) {
  36324. request.responseTime = Date.now();
  36325. request.roundTripTime = request.responseTime - request.requestTime;
  36326. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  36327. if (!request.bandwidth) {
  36328. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  36329. }
  36330. }
  36331. if (response.headers) {
  36332. request.responseHeaders = response.headers;
  36333. } // videojs.xhr now uses a specific code on the error
  36334. // object to signal that a request has timed out instead
  36335. // of setting a boolean on the request object
  36336. if (error && error.code === 'ETIMEDOUT') {
  36337. request.timedout = true;
  36338. } // videojs.xhr no longer considers status codes outside of 200 and 0
  36339. // (for file uris) to be errors, but the old XHR did, so emulate that
  36340. // behavior. Status 206 may be used in response to byterange requests.
  36341. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  36342. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  36343. }
  36344. callback(error, request);
  36345. };
  36346. const xhrFactory = function () {
  36347. const xhr = function XhrFunction(options, callback) {
  36348. // Add a default timeout
  36349. options = merge({
  36350. timeout: 45e3
  36351. }, options); // Allow an optional user-specified function to modify the option
  36352. // object before we construct the xhr request
  36353. const beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest;
  36354. if (beforeRequest && typeof beforeRequest === 'function') {
  36355. const newOptions = beforeRequest(options);
  36356. if (newOptions) {
  36357. options = newOptions;
  36358. }
  36359. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  36360. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  36361. const xhrMethod = videojs.Vhs.xhr.original === true ? videojsXHR : videojs.Vhs.xhr;
  36362. const request = xhrMethod(options, function (error, response) {
  36363. return callbackWrapper(request, error, response, callback);
  36364. });
  36365. const originalAbort = request.abort;
  36366. request.abort = function () {
  36367. request.aborted = true;
  36368. return originalAbort.apply(request, arguments);
  36369. };
  36370. request.uri = options.uri;
  36371. request.requestTime = Date.now();
  36372. return request;
  36373. };
  36374. xhr.original = true;
  36375. return xhr;
  36376. };
  36377. /**
  36378. * Turns segment byterange into a string suitable for use in
  36379. * HTTP Range requests
  36380. *
  36381. * @param {Object} byterange - an object with two values defining the start and end
  36382. * of a byte-range
  36383. */
  36384. const byterangeStr = function (byterange) {
  36385. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  36386. // header uses inclusive ranges
  36387. let byterangeEnd;
  36388. const byterangeStart = byterange.offset;
  36389. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  36390. byterangeEnd = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  36391. } else {
  36392. byterangeEnd = byterange.offset + byterange.length - 1;
  36393. }
  36394. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  36395. };
  36396. /**
  36397. * Defines headers for use in the xhr request for a particular segment.
  36398. *
  36399. * @param {Object} segment - a simplified copy of the segmentInfo object
  36400. * from SegmentLoader
  36401. */
  36402. const segmentXhrHeaders = function (segment) {
  36403. const headers = {};
  36404. if (segment.byterange) {
  36405. headers.Range = byterangeStr(segment.byterange);
  36406. }
  36407. return headers;
  36408. };
  36409. /**
  36410. * @file bin-utils.js
  36411. */
  36412. /**
  36413. * convert a TimeRange to text
  36414. *
  36415. * @param {TimeRange} range the timerange to use for conversion
  36416. * @param {number} i the iterator on the range to convert
  36417. * @return {string} the range in string format
  36418. */
  36419. const textRange = function (range, i) {
  36420. return range.start(i) + '-' + range.end(i);
  36421. };
  36422. /**
  36423. * format a number as hex string
  36424. *
  36425. * @param {number} e The number
  36426. * @param {number} i the iterator
  36427. * @return {string} the hex formatted number as a string
  36428. */
  36429. const formatHexString = function (e, i) {
  36430. const value = e.toString(16);
  36431. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  36432. };
  36433. const formatAsciiString = function (e) {
  36434. if (e >= 0x20 && e < 0x7e) {
  36435. return String.fromCharCode(e);
  36436. }
  36437. return '.';
  36438. };
  36439. /**
  36440. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  36441. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  36442. *
  36443. * @param {Object} message
  36444. * Object of properties and values to send to the web worker
  36445. * @return {Object}
  36446. * Modified message with TypedArray values expanded
  36447. * @function createTransferableMessage
  36448. */
  36449. const createTransferableMessage = function (message) {
  36450. const transferable = {};
  36451. Object.keys(message).forEach(key => {
  36452. const value = message[key];
  36453. if (isArrayBufferView(value)) {
  36454. transferable[key] = {
  36455. bytes: value.buffer,
  36456. byteOffset: value.byteOffset,
  36457. byteLength: value.byteLength
  36458. };
  36459. } else {
  36460. transferable[key] = value;
  36461. }
  36462. });
  36463. return transferable;
  36464. };
  36465. /**
  36466. * Returns a unique string identifier for a media initialization
  36467. * segment.
  36468. *
  36469. * @param {Object} initSegment
  36470. * the init segment object.
  36471. *
  36472. * @return {string} the generated init segment id
  36473. */
  36474. const initSegmentId = function (initSegment) {
  36475. const byterange = initSegment.byterange || {
  36476. length: Infinity,
  36477. offset: 0
  36478. };
  36479. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  36480. };
  36481. /**
  36482. * Returns a unique string identifier for a media segment key.
  36483. *
  36484. * @param {Object} key the encryption key
  36485. * @return {string} the unique id for the media segment key.
  36486. */
  36487. const segmentKeyId = function (key) {
  36488. return key.resolvedUri;
  36489. };
  36490. /**
  36491. * utils to help dump binary data to the console
  36492. *
  36493. * @param {Array|TypedArray} data
  36494. * data to dump to a string
  36495. *
  36496. * @return {string} the data as a hex string.
  36497. */
  36498. const hexDump = data => {
  36499. const bytes = Array.prototype.slice.call(data);
  36500. const step = 16;
  36501. let result = '';
  36502. let hex;
  36503. let ascii;
  36504. for (let j = 0; j < bytes.length / step; j++) {
  36505. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  36506. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  36507. result += hex + ' ' + ascii + '\n';
  36508. }
  36509. return result;
  36510. };
  36511. const tagDump = ({
  36512. bytes
  36513. }) => hexDump(bytes);
  36514. const textRanges = ranges => {
  36515. let result = '';
  36516. let i;
  36517. for (i = 0; i < ranges.length; i++) {
  36518. result += textRange(ranges, i) + ' ';
  36519. }
  36520. return result;
  36521. };
  36522. var utils = /*#__PURE__*/Object.freeze({
  36523. __proto__: null,
  36524. createTransferableMessage: createTransferableMessage,
  36525. initSegmentId: initSegmentId,
  36526. segmentKeyId: segmentKeyId,
  36527. hexDump: hexDump,
  36528. tagDump: tagDump,
  36529. textRanges: textRanges
  36530. });
  36531. // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  36532. // 25% was arbitrarily chosen, and may need to be refined over time.
  36533. const SEGMENT_END_FUDGE_PERCENT = 0.25;
  36534. /**
  36535. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  36536. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  36537. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  36538. *
  36539. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  36540. * point" (a point where we have a mapping from program time to player time, with player
  36541. * time being the post transmux start of the segment).
  36542. *
  36543. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  36544. *
  36545. * @param {number} playerTime the player time
  36546. * @param {Object} segment the segment which contains the player time
  36547. * @return {Date} program time
  36548. */
  36549. const playerTimeToProgramTime = (playerTime, segment) => {
  36550. if (!segment.dateTimeObject) {
  36551. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  36552. // be used to map the start of a segment with a real world time).
  36553. return null;
  36554. }
  36555. const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  36556. const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  36557. const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  36558. const offsetFromSegmentStart = playerTime - startOfSegment;
  36559. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  36560. };
  36561. const originalSegmentVideoDuration = videoTimingInfo => {
  36562. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  36563. };
  36564. /**
  36565. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  36566. * returned segment might be an estimate or an accurate match.
  36567. *
  36568. * @param {string} programTime The ISO-8601 programTime to find a match for
  36569. * @param {Object} playlist A playlist object to search within
  36570. */
  36571. const findSegmentForProgramTime = (programTime, playlist) => {
  36572. // Assumptions:
  36573. // - verifyProgramDateTimeTags has already been run
  36574. // - live streams have been started
  36575. let dateTimeObject;
  36576. try {
  36577. dateTimeObject = new Date(programTime);
  36578. } catch (e) {
  36579. return null;
  36580. }
  36581. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  36582. return null;
  36583. }
  36584. let segment = playlist.segments[0];
  36585. if (dateTimeObject < segment.dateTimeObject) {
  36586. // Requested time is before stream start.
  36587. return null;
  36588. }
  36589. for (let i = 0; i < playlist.segments.length - 1; i++) {
  36590. segment = playlist.segments[i];
  36591. const nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
  36592. if (dateTimeObject < nextSegmentStart) {
  36593. break;
  36594. }
  36595. }
  36596. const lastSegment = playlist.segments[playlist.segments.length - 1];
  36597. const lastSegmentStart = lastSegment.dateTimeObject;
  36598. const lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  36599. const lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  36600. if (dateTimeObject > lastSegmentEnd) {
  36601. // Beyond the end of the stream, or our best guess of the end of the stream.
  36602. return null;
  36603. }
  36604. if (dateTimeObject > lastSegmentStart) {
  36605. segment = lastSegment;
  36606. }
  36607. return {
  36608. segment,
  36609. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  36610. // Although, given that all segments have accurate date time objects, the segment
  36611. // selected should be accurate, unless the video has been transmuxed at some point
  36612. // (determined by the presence of the videoTimingInfo object), the segment's "player
  36613. // time" (the start time in the player) can't be considered accurate.
  36614. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  36615. };
  36616. };
  36617. /**
  36618. * Finds a segment that contains the given player time(in seconds).
  36619. *
  36620. * @param {number} time The player time to find a match for
  36621. * @param {Object} playlist A playlist object to search within
  36622. */
  36623. const findSegmentForPlayerTime = (time, playlist) => {
  36624. // Assumptions:
  36625. // - there will always be a segment.duration
  36626. // - we can start from zero
  36627. // - segments are in time order
  36628. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  36629. return null;
  36630. }
  36631. let segmentEnd = 0;
  36632. let segment;
  36633. for (let i = 0; i < playlist.segments.length; i++) {
  36634. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  36635. // should contain the most accurate values we have for the segment's player times.
  36636. //
  36637. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  36638. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  36639. // calculate an end value.
  36640. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  36641. if (time <= segmentEnd) {
  36642. break;
  36643. }
  36644. }
  36645. const lastSegment = playlist.segments[playlist.segments.length - 1];
  36646. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  36647. // The time requested is beyond the stream end.
  36648. return null;
  36649. }
  36650. if (time > segmentEnd) {
  36651. // The time is within or beyond the last segment.
  36652. //
  36653. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  36654. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  36655. // Technically, because the duration value is only an estimate, the time may still
  36656. // exist in the last segment, however, there isn't enough information to make even
  36657. // a reasonable estimate.
  36658. return null;
  36659. }
  36660. segment = lastSegment;
  36661. }
  36662. return {
  36663. segment,
  36664. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  36665. // Because videoTimingInfo is only set after transmux, it is the only way to get
  36666. // accurate timing values.
  36667. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  36668. };
  36669. };
  36670. /**
  36671. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  36672. * If the offset returned is positive, the programTime occurs after the
  36673. * comparisonTimestamp.
  36674. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  36675. *
  36676. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  36677. * @param {string} programTime The programTime as an ISO-8601 string
  36678. * @return {number} offset
  36679. */
  36680. const getOffsetFromTimestamp = (comparisonTimeStamp, programTime) => {
  36681. let segmentDateTime;
  36682. let programDateTime;
  36683. try {
  36684. segmentDateTime = new Date(comparisonTimeStamp);
  36685. programDateTime = new Date(programTime);
  36686. } catch (e) {// TODO handle error
  36687. }
  36688. const segmentTimeEpoch = segmentDateTime.getTime();
  36689. const programTimeEpoch = programDateTime.getTime();
  36690. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  36691. };
  36692. /**
  36693. * Checks that all segments in this playlist have programDateTime tags.
  36694. *
  36695. * @param {Object} playlist A playlist object
  36696. */
  36697. const verifyProgramDateTimeTags = playlist => {
  36698. if (!playlist.segments || playlist.segments.length === 0) {
  36699. return false;
  36700. }
  36701. for (let i = 0; i < playlist.segments.length; i++) {
  36702. const segment = playlist.segments[i];
  36703. if (!segment.dateTimeObject) {
  36704. return false;
  36705. }
  36706. }
  36707. return true;
  36708. };
  36709. /**
  36710. * Returns the programTime of the media given a playlist and a playerTime.
  36711. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  36712. * If the segments containing the time requested have not been buffered yet, an estimate
  36713. * may be returned to the callback.
  36714. *
  36715. * @param {Object} args
  36716. * @param {Object} args.playlist A playlist object to search within
  36717. * @param {number} time A playerTime in seconds
  36718. * @param {Function} callback(err, programTime)
  36719. * @return {string} err.message A detailed error message
  36720. * @return {Object} programTime
  36721. * @return {number} programTime.mediaSeconds The streamTime in seconds
  36722. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  36723. */
  36724. const getProgramTime = ({
  36725. playlist,
  36726. time = undefined,
  36727. callback
  36728. }) => {
  36729. if (!callback) {
  36730. throw new Error('getProgramTime: callback must be provided');
  36731. }
  36732. if (!playlist || time === undefined) {
  36733. return callback({
  36734. message: 'getProgramTime: playlist and time must be provided'
  36735. });
  36736. }
  36737. const matchedSegment = findSegmentForPlayerTime(time, playlist);
  36738. if (!matchedSegment) {
  36739. return callback({
  36740. message: 'valid programTime was not found'
  36741. });
  36742. }
  36743. if (matchedSegment.type === 'estimate') {
  36744. return callback({
  36745. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  36746. seekTime: matchedSegment.estimatedStart
  36747. });
  36748. }
  36749. const programTimeObject = {
  36750. mediaSeconds: time
  36751. };
  36752. const programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  36753. if (programTime) {
  36754. programTimeObject.programDateTime = programTime.toISOString();
  36755. }
  36756. return callback(null, programTimeObject);
  36757. };
  36758. /**
  36759. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  36760. *
  36761. * @param {Object} args
  36762. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  36763. * @param {Object} args.playlist A playlist to look within
  36764. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  36765. * @param {Function} args.seekTo A method to perform a seek
  36766. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  36767. * @param {Object} args.tech The tech to seek on
  36768. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  36769. * @return {string} err.message A detailed error message
  36770. * @return {number} newTime The exact time that was seeked to in seconds
  36771. */
  36772. const seekToProgramTime = ({
  36773. programTime,
  36774. playlist,
  36775. retryCount = 2,
  36776. seekTo,
  36777. pauseAfterSeek = true,
  36778. tech,
  36779. callback
  36780. }) => {
  36781. if (!callback) {
  36782. throw new Error('seekToProgramTime: callback must be provided');
  36783. }
  36784. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  36785. return callback({
  36786. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  36787. });
  36788. }
  36789. if (!playlist.endList && !tech.hasStarted_) {
  36790. return callback({
  36791. message: 'player must be playing a live stream to start buffering'
  36792. });
  36793. }
  36794. if (!verifyProgramDateTimeTags(playlist)) {
  36795. return callback({
  36796. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  36797. });
  36798. }
  36799. const matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  36800. if (!matchedSegment) {
  36801. return callback({
  36802. message: `${programTime} was not found in the stream`
  36803. });
  36804. }
  36805. const segment = matchedSegment.segment;
  36806. const mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  36807. if (matchedSegment.type === 'estimate') {
  36808. // we've run out of retries
  36809. if (retryCount === 0) {
  36810. return callback({
  36811. message: `${programTime} is not buffered yet. Try again`
  36812. });
  36813. }
  36814. seekTo(matchedSegment.estimatedStart + mediaOffset);
  36815. tech.one('seeked', () => {
  36816. seekToProgramTime({
  36817. programTime,
  36818. playlist,
  36819. retryCount: retryCount - 1,
  36820. seekTo,
  36821. pauseAfterSeek,
  36822. tech,
  36823. callback
  36824. });
  36825. });
  36826. return;
  36827. } // Since the segment.start value is determined from the buffered end or ending time
  36828. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  36829. // modifications.
  36830. const seekToTime = segment.start + mediaOffset;
  36831. const seekedCallback = () => {
  36832. return callback(null, tech.currentTime());
  36833. }; // listen for seeked event
  36834. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  36835. if (pauseAfterSeek) {
  36836. tech.pause();
  36837. }
  36838. seekTo(seekToTime);
  36839. };
  36840. // which will only happen if the request is complete.
  36841. const callbackOnCompleted = (request, cb) => {
  36842. if (request.readyState === 4) {
  36843. return cb();
  36844. }
  36845. return;
  36846. };
  36847. const containerRequest = (uri, xhr, cb) => {
  36848. let bytes = [];
  36849. let id3Offset;
  36850. let finished = false;
  36851. const endRequestAndCallback = function (err, req, type, _bytes) {
  36852. req.abort();
  36853. finished = true;
  36854. return cb(err, req, type, _bytes);
  36855. };
  36856. const progressListener = function (error, request) {
  36857. if (finished) {
  36858. return;
  36859. }
  36860. if (error) {
  36861. return endRequestAndCallback(error, request, '', bytes);
  36862. } // grap the new part of content that was just downloaded
  36863. const newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  36864. bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
  36865. id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
  36866. // or we need at least two bytes after an id3Offset
  36867. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  36868. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  36869. }
  36870. const type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  36871. // to see the second sync byte, wait until we have enough data
  36872. // before declaring it ts
  36873. if (type === 'ts' && bytes.length < 188) {
  36874. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  36875. } // this may be an unsynced ts segment
  36876. // wait for 376 bytes before detecting no container
  36877. if (!type && bytes.length < 376) {
  36878. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  36879. }
  36880. return endRequestAndCallback(null, request, type, bytes);
  36881. };
  36882. const options = {
  36883. uri,
  36884. beforeSend(request) {
  36885. // this forces the browser to pass the bytes to us unprocessed
  36886. request.overrideMimeType('text/plain; charset=x-user-defined');
  36887. request.addEventListener('progress', function ({
  36888. total,
  36889. loaded
  36890. }) {
  36891. return callbackWrapper(request, null, {
  36892. statusCode: request.status
  36893. }, progressListener);
  36894. });
  36895. }
  36896. };
  36897. const request = xhr(options, function (error, response) {
  36898. return callbackWrapper(request, error, response, progressListener);
  36899. });
  36900. return request;
  36901. };
  36902. const {
  36903. EventTarget
  36904. } = videojs;
  36905. const dashPlaylistUnchanged = function (a, b) {
  36906. if (!isPlaylistUnchanged(a, b)) {
  36907. return false;
  36908. } // for dash the above check will often return true in scenarios where
  36909. // the playlist actually has changed because mediaSequence isn't a
  36910. // dash thing, and we often set it to 1. So if the playlists have the same amount
  36911. // of segments we return true.
  36912. // So for dash we need to make sure that the underlying segments are different.
  36913. // if sidx changed then the playlists are different.
  36914. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  36915. return false;
  36916. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  36917. return false;
  36918. } // one or the other does not have segments
  36919. // there was a change.
  36920. if (a.segments && !b.segments || !a.segments && b.segments) {
  36921. return false;
  36922. } // neither has segments nothing changed
  36923. if (!a.segments && !b.segments) {
  36924. return true;
  36925. } // check segments themselves
  36926. for (let i = 0; i < a.segments.length; i++) {
  36927. const aSegment = a.segments[i];
  36928. const bSegment = b.segments[i]; // if uris are different between segments there was a change
  36929. if (aSegment.uri !== bSegment.uri) {
  36930. return false;
  36931. } // neither segment has a byterange, there will be no byterange change.
  36932. if (!aSegment.byterange && !bSegment.byterange) {
  36933. continue;
  36934. }
  36935. const aByterange = aSegment.byterange;
  36936. const bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  36937. if (aByterange && !bByterange || !aByterange && bByterange) {
  36938. return false;
  36939. } // if both segments have byterange with different offsets, there was a change.
  36940. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  36941. return false;
  36942. }
  36943. } // if everything was the same with segments, this is the same playlist.
  36944. return true;
  36945. };
  36946. /**
  36947. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  36948. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  36949. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  36950. * periods without continuous playback this function may need modification as well as the parser.
  36951. */
  36952. const dashGroupId = (type, group, label, playlist) => {
  36953. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  36954. const playlistId = playlist.attributes.NAME || label;
  36955. return `placeholder-uri-${type}-${group}-${playlistId}`;
  36956. };
  36957. /**
  36958. * Parses the main XML string and updates playlist URI references.
  36959. *
  36960. * @param {Object} config
  36961. * Object of arguments
  36962. * @param {string} config.mainXml
  36963. * The mpd XML
  36964. * @param {string} config.srcUrl
  36965. * The mpd URL
  36966. * @param {Date} config.clientOffset
  36967. * A time difference between server and client
  36968. * @param {Object} config.sidxMapping
  36969. * SIDX mappings for moof/mdat URIs and byte ranges
  36970. * @return {Object}
  36971. * The parsed mpd manifest object
  36972. */
  36973. const parseMainXml = ({
  36974. mainXml,
  36975. srcUrl,
  36976. clientOffset,
  36977. sidxMapping,
  36978. previousManifest
  36979. }) => {
  36980. const manifest = parse(mainXml, {
  36981. manifestUri: srcUrl,
  36982. clientOffset,
  36983. sidxMapping,
  36984. previousManifest
  36985. });
  36986. addPropertiesToMain(manifest, srcUrl, dashGroupId);
  36987. return manifest;
  36988. };
  36989. /**
  36990. * Removes any mediaGroup labels that no longer exist in the newMain
  36991. *
  36992. * @param {Object} update
  36993. * The previous mpd object being updated
  36994. * @param {Object} newMain
  36995. * The new mpd object
  36996. */
  36997. const removeOldMediaGroupLabels = (update, newMain) => {
  36998. forEachMediaGroup(update, (properties, type, group, label) => {
  36999. if (!(label in newMain.mediaGroups[type][group])) {
  37000. delete update.mediaGroups[type][group][label];
  37001. }
  37002. });
  37003. };
  37004. /**
  37005. * Returns a new main manifest that is the result of merging an updated main manifest
  37006. * into the original version.
  37007. *
  37008. * @param {Object} oldMain
  37009. * The old parsed mpd object
  37010. * @param {Object} newMain
  37011. * The updated parsed mpd object
  37012. * @return {Object}
  37013. * A new object representing the original main manifest with the updated media
  37014. * playlists merged in
  37015. */
  37016. const updateMain = (oldMain, newMain, sidxMapping) => {
  37017. let noChanges = true;
  37018. let update = merge(oldMain, {
  37019. // These are top level properties that can be updated
  37020. duration: newMain.duration,
  37021. minimumUpdatePeriod: newMain.minimumUpdatePeriod,
  37022. timelineStarts: newMain.timelineStarts
  37023. }); // First update the playlists in playlist list
  37024. for (let i = 0; i < newMain.playlists.length; i++) {
  37025. const playlist = newMain.playlists[i];
  37026. if (playlist.sidx) {
  37027. const sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  37028. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  37029. addSidxSegmentsToPlaylist$1(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  37030. }
  37031. }
  37032. const playlistUpdate = updateMain$1(update, playlist, dashPlaylistUnchanged);
  37033. if (playlistUpdate) {
  37034. update = playlistUpdate;
  37035. noChanges = false;
  37036. }
  37037. } // Then update media group playlists
  37038. forEachMediaGroup(newMain, (properties, type, group, label) => {
  37039. if (properties.playlists && properties.playlists.length) {
  37040. const id = properties.playlists[0].id;
  37041. const playlistUpdate = updateMain$1(update, properties.playlists[0], dashPlaylistUnchanged);
  37042. if (playlistUpdate) {
  37043. update = playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  37044. if (!(label in update.mediaGroups[type][group])) {
  37045. update.mediaGroups[type][group][label] = properties;
  37046. } // update the playlist reference within media groups
  37047. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  37048. noChanges = false;
  37049. }
  37050. }
  37051. }); // remove mediaGroup labels and references that no longer exist in the newMain
  37052. removeOldMediaGroupLabels(update, newMain);
  37053. if (newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  37054. noChanges = false;
  37055. }
  37056. if (noChanges) {
  37057. return null;
  37058. }
  37059. return update;
  37060. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  37061. // If the SIDXs have maps, the two maps should match,
  37062. // both `a` and `b` missing SIDXs is considered matching.
  37063. // If `a` or `b` but not both have a map, they aren't matching.
  37064. const equivalentSidx = (a, b) => {
  37065. const neitherMap = Boolean(!a.map && !b.map);
  37066. const equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  37067. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  37068. }; // exported for testing
  37069. const compareSidxEntry = (playlists, oldSidxMapping) => {
  37070. const newSidxMapping = {};
  37071. for (const id in playlists) {
  37072. const playlist = playlists[id];
  37073. const currentSidxInfo = playlist.sidx;
  37074. if (currentSidxInfo) {
  37075. const key = generateSidxKey(currentSidxInfo);
  37076. if (!oldSidxMapping[key]) {
  37077. break;
  37078. }
  37079. const savedSidxInfo = oldSidxMapping[key].sidxInfo;
  37080. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  37081. newSidxMapping[key] = oldSidxMapping[key];
  37082. }
  37083. }
  37084. }
  37085. return newSidxMapping;
  37086. };
  37087. /**
  37088. * A function that filters out changed items as they need to be requested separately.
  37089. *
  37090. * The method is exported for testing
  37091. *
  37092. * @param {Object} main the parsed mpd XML returned via mpd-parser
  37093. * @param {Object} oldSidxMapping the SIDX to compare against
  37094. */
  37095. const filterChangedSidxMappings = (main, oldSidxMapping) => {
  37096. const videoSidx = compareSidxEntry(main.playlists, oldSidxMapping);
  37097. let mediaGroupSidx = videoSidx;
  37098. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  37099. if (properties.playlists && properties.playlists.length) {
  37100. const playlists = properties.playlists;
  37101. mediaGroupSidx = merge(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  37102. }
  37103. });
  37104. return mediaGroupSidx;
  37105. };
  37106. class DashPlaylistLoader extends EventTarget {
  37107. // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  37108. // playlist loader setups from media groups will expect to be able to pass a playlist
  37109. // (since there aren't external URLs to media playlists with DASH)
  37110. constructor(srcUrlOrPlaylist, vhs, options = {}, mainPlaylistLoader) {
  37111. super();
  37112. this.mainPlaylistLoader_ = mainPlaylistLoader || this;
  37113. if (!mainPlaylistLoader) {
  37114. this.isMain_ = true;
  37115. }
  37116. const {
  37117. withCredentials = false
  37118. } = options;
  37119. this.vhs_ = vhs;
  37120. this.withCredentials = withCredentials;
  37121. if (!srcUrlOrPlaylist) {
  37122. throw new Error('A non-empty playlist URL or object is required');
  37123. } // event naming?
  37124. this.on('minimumUpdatePeriod', () => {
  37125. this.refreshXml_();
  37126. }); // live playlist staleness timeout
  37127. this.on('mediaupdatetimeout', () => {
  37128. this.refreshMedia_(this.media().id);
  37129. });
  37130. this.state = 'HAVE_NOTHING';
  37131. this.loadedPlaylists_ = {};
  37132. this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  37133. // The mainPlaylistLoader will be created with a string
  37134. if (this.isMain_) {
  37135. this.mainPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  37136. // once multi-period is refactored
  37137. this.mainPlaylistLoader_.sidxMapping_ = {};
  37138. } else {
  37139. this.childPlaylist_ = srcUrlOrPlaylist;
  37140. }
  37141. }
  37142. requestErrored_(err, request, startingState) {
  37143. // disposed
  37144. if (!this.request) {
  37145. return true;
  37146. } // pending request is cleared
  37147. this.request = null;
  37148. if (err) {
  37149. // use the provided error object or create one
  37150. // based on the request/response
  37151. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  37152. status: request.status,
  37153. message: 'DASH request error at URL: ' + request.uri,
  37154. response: request.response,
  37155. // MEDIA_ERR_NETWORK
  37156. code: 2
  37157. };
  37158. if (startingState) {
  37159. this.state = startingState;
  37160. }
  37161. this.trigger('error');
  37162. return true;
  37163. }
  37164. }
  37165. /**
  37166. * Verify that the container of the sidx segment can be parsed
  37167. * and if it can, get and parse that segment.
  37168. */
  37169. addSidxSegments_(playlist, startingState, cb) {
  37170. const sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  37171. if (!playlist.sidx || !sidxKey || this.mainPlaylistLoader_.sidxMapping_[sidxKey]) {
  37172. // keep this function async
  37173. this.mediaRequest_ = window.setTimeout(() => cb(false), 0);
  37174. return;
  37175. } // resolve the segment URL relative to the playlist
  37176. const uri = resolveManifestRedirect(playlist.sidx.resolvedUri);
  37177. const fin = (err, request) => {
  37178. if (this.requestErrored_(err, request, startingState)) {
  37179. return;
  37180. }
  37181. const sidxMapping = this.mainPlaylistLoader_.sidxMapping_;
  37182. let sidx;
  37183. try {
  37184. sidx = parseSidx_1(toUint8(request.response).subarray(8));
  37185. } catch (e) {
  37186. // sidx parsing failed.
  37187. this.requestErrored_(e, request, startingState);
  37188. return;
  37189. }
  37190. sidxMapping[sidxKey] = {
  37191. sidxInfo: playlist.sidx,
  37192. sidx
  37193. };
  37194. addSidxSegmentsToPlaylist$1(playlist, sidx, playlist.sidx.resolvedUri);
  37195. return cb(true);
  37196. };
  37197. this.request = containerRequest(uri, this.vhs_.xhr, (err, request, container, bytes) => {
  37198. if (err) {
  37199. return fin(err, request);
  37200. }
  37201. if (!container || container !== 'mp4') {
  37202. return fin({
  37203. status: request.status,
  37204. message: `Unsupported ${container || 'unknown'} container type for sidx segment at URL: ${uri}`,
  37205. // response is just bytes in this case
  37206. // but we really don't want to return that.
  37207. response: '',
  37208. playlist,
  37209. internal: true,
  37210. playlistExclusionDuration: Infinity,
  37211. // MEDIA_ERR_NETWORK
  37212. code: 2
  37213. }, request);
  37214. } // if we already downloaded the sidx bytes in the container request, use them
  37215. const {
  37216. offset,
  37217. length
  37218. } = playlist.sidx.byterange;
  37219. if (bytes.length >= length + offset) {
  37220. return fin(err, {
  37221. response: bytes.subarray(offset, offset + length),
  37222. status: request.status,
  37223. uri: request.uri
  37224. });
  37225. } // otherwise request sidx bytes
  37226. this.request = this.vhs_.xhr({
  37227. uri,
  37228. responseType: 'arraybuffer',
  37229. headers: segmentXhrHeaders({
  37230. byterange: playlist.sidx.byterange
  37231. })
  37232. }, fin);
  37233. });
  37234. }
  37235. dispose() {
  37236. this.trigger('dispose');
  37237. this.stopRequest();
  37238. this.loadedPlaylists_ = {};
  37239. window.clearTimeout(this.minimumUpdatePeriodTimeout_);
  37240. window.clearTimeout(this.mediaRequest_);
  37241. window.clearTimeout(this.mediaUpdateTimeout);
  37242. this.mediaUpdateTimeout = null;
  37243. this.mediaRequest_ = null;
  37244. this.minimumUpdatePeriodTimeout_ = null;
  37245. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  37246. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  37247. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  37248. }
  37249. this.off();
  37250. }
  37251. hasPendingRequest() {
  37252. return this.request || this.mediaRequest_;
  37253. }
  37254. stopRequest() {
  37255. if (this.request) {
  37256. const oldRequest = this.request;
  37257. this.request = null;
  37258. oldRequest.onreadystatechange = null;
  37259. oldRequest.abort();
  37260. }
  37261. }
  37262. media(playlist) {
  37263. // getter
  37264. if (!playlist) {
  37265. return this.media_;
  37266. } // setter
  37267. if (this.state === 'HAVE_NOTHING') {
  37268. throw new Error('Cannot switch media playlist from ' + this.state);
  37269. }
  37270. const startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  37271. if (typeof playlist === 'string') {
  37272. if (!this.mainPlaylistLoader_.main.playlists[playlist]) {
  37273. throw new Error('Unknown playlist URI: ' + playlist);
  37274. }
  37275. playlist = this.mainPlaylistLoader_.main.playlists[playlist];
  37276. }
  37277. const mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  37278. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  37279. this.state = 'HAVE_METADATA';
  37280. this.media_ = playlist; // trigger media change if the active media has been updated
  37281. if (mediaChange) {
  37282. this.trigger('mediachanging');
  37283. this.trigger('mediachange');
  37284. }
  37285. return;
  37286. } // switching to the active playlist is a no-op
  37287. if (!mediaChange) {
  37288. return;
  37289. } // switching from an already loaded playlist
  37290. if (this.media_) {
  37291. this.trigger('mediachanging');
  37292. }
  37293. this.addSidxSegments_(playlist, startingState, sidxChanged => {
  37294. // everything is ready just continue to haveMetadata
  37295. this.haveMetadata({
  37296. startingState,
  37297. playlist
  37298. });
  37299. });
  37300. }
  37301. haveMetadata({
  37302. startingState,
  37303. playlist
  37304. }) {
  37305. this.state = 'HAVE_METADATA';
  37306. this.loadedPlaylists_[playlist.id] = playlist;
  37307. this.mediaRequest_ = null; // This will trigger loadedplaylist
  37308. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  37309. // to resolve setup of media groups
  37310. if (startingState === 'HAVE_MAIN_MANIFEST') {
  37311. this.trigger('loadedmetadata');
  37312. } else {
  37313. // trigger media change if the active media has been updated
  37314. this.trigger('mediachange');
  37315. }
  37316. }
  37317. pause() {
  37318. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  37319. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  37320. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  37321. }
  37322. this.stopRequest();
  37323. window.clearTimeout(this.mediaUpdateTimeout);
  37324. this.mediaUpdateTimeout = null;
  37325. if (this.isMain_) {
  37326. window.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_);
  37327. this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  37328. }
  37329. if (this.state === 'HAVE_NOTHING') {
  37330. // If we pause the loader before any data has been retrieved, its as if we never
  37331. // started, so reset to an unstarted state.
  37332. this.started = false;
  37333. }
  37334. }
  37335. load(isFinalRendition) {
  37336. window.clearTimeout(this.mediaUpdateTimeout);
  37337. this.mediaUpdateTimeout = null;
  37338. const media = this.media();
  37339. if (isFinalRendition) {
  37340. const delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  37341. this.mediaUpdateTimeout = window.setTimeout(() => this.load(), delay);
  37342. return;
  37343. } // because the playlists are internal to the manifest, load should either load the
  37344. // main manifest, or do nothing but trigger an event
  37345. if (!this.started) {
  37346. this.start();
  37347. return;
  37348. }
  37349. if (media && !media.endList) {
  37350. // Check to see if this is the main loader and the MUP was cleared (this happens
  37351. // when the loader was paused). `media` should be set at this point since one is always
  37352. // set during `start()`.
  37353. if (this.isMain_ && !this.minimumUpdatePeriodTimeout_) {
  37354. // Trigger minimumUpdatePeriod to refresh the main manifest
  37355. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  37356. this.updateMinimumUpdatePeriodTimeout_();
  37357. }
  37358. this.trigger('mediaupdatetimeout');
  37359. } else {
  37360. this.trigger('loadedplaylist');
  37361. }
  37362. }
  37363. start() {
  37364. this.started = true; // We don't need to request the main manifest again
  37365. // Call this asynchronously to match the xhr request behavior below
  37366. if (!this.isMain_) {
  37367. this.mediaRequest_ = window.setTimeout(() => this.haveMain_(), 0);
  37368. return;
  37369. }
  37370. this.requestMain_((req, mainChanged) => {
  37371. this.haveMain_();
  37372. if (!this.hasPendingRequest() && !this.media_) {
  37373. this.media(this.mainPlaylistLoader_.main.playlists[0]);
  37374. }
  37375. });
  37376. }
  37377. requestMain_(cb) {
  37378. this.request = this.vhs_.xhr({
  37379. uri: this.mainPlaylistLoader_.srcUrl,
  37380. withCredentials: this.withCredentials
  37381. }, (error, req) => {
  37382. if (this.requestErrored_(error, req)) {
  37383. if (this.state === 'HAVE_NOTHING') {
  37384. this.started = false;
  37385. }
  37386. return;
  37387. }
  37388. const mainChanged = req.responseText !== this.mainPlaylistLoader_.mainXml_;
  37389. this.mainPlaylistLoader_.mainXml_ = req.responseText;
  37390. if (req.responseHeaders && req.responseHeaders.date) {
  37391. this.mainLoaded_ = Date.parse(req.responseHeaders.date);
  37392. } else {
  37393. this.mainLoaded_ = Date.now();
  37394. }
  37395. this.mainPlaylistLoader_.srcUrl = resolveManifestRedirect(this.mainPlaylistLoader_.srcUrl, req);
  37396. if (mainChanged) {
  37397. this.handleMain_();
  37398. this.syncClientServerClock_(() => {
  37399. return cb(req, mainChanged);
  37400. });
  37401. return;
  37402. }
  37403. return cb(req, mainChanged);
  37404. });
  37405. }
  37406. /**
  37407. * Parses the main xml for UTCTiming node to sync the client clock to the server
  37408. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  37409. *
  37410. * @param {Function} done
  37411. * Function to call when clock sync has completed
  37412. */
  37413. syncClientServerClock_(done) {
  37414. const utcTiming = parseUTCTiming(this.mainPlaylistLoader_.mainXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  37415. // server clock
  37416. if (utcTiming === null) {
  37417. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  37418. return done();
  37419. }
  37420. if (utcTiming.method === 'DIRECT') {
  37421. this.mainPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  37422. return done();
  37423. }
  37424. this.request = this.vhs_.xhr({
  37425. uri: resolveUrl(this.mainPlaylistLoader_.srcUrl, utcTiming.value),
  37426. method: utcTiming.method,
  37427. withCredentials: this.withCredentials
  37428. }, (error, req) => {
  37429. // disposed
  37430. if (!this.request) {
  37431. return;
  37432. }
  37433. if (error) {
  37434. // sync request failed, fall back to using date header from mpd
  37435. // TODO: log warning
  37436. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  37437. return done();
  37438. }
  37439. let serverTime;
  37440. if (utcTiming.method === 'HEAD') {
  37441. if (!req.responseHeaders || !req.responseHeaders.date) {
  37442. // expected date header not preset, fall back to using date header from mpd
  37443. // TODO: log warning
  37444. serverTime = this.mainLoaded_;
  37445. } else {
  37446. serverTime = Date.parse(req.responseHeaders.date);
  37447. }
  37448. } else {
  37449. serverTime = Date.parse(req.responseText);
  37450. }
  37451. this.mainPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  37452. done();
  37453. });
  37454. }
  37455. haveMain_() {
  37456. this.state = 'HAVE_MAIN_MANIFEST';
  37457. if (this.isMain_) {
  37458. // We have the main playlist at this point, so
  37459. // trigger this to allow PlaylistController
  37460. // to make an initial playlist selection
  37461. this.trigger('loadedplaylist');
  37462. } else if (!this.media_) {
  37463. // no media playlist was specifically selected so select
  37464. // the one the child playlist loader was created with
  37465. this.media(this.childPlaylist_);
  37466. }
  37467. }
  37468. handleMain_() {
  37469. // clear media request
  37470. this.mediaRequest_ = null;
  37471. const oldMain = this.mainPlaylistLoader_.main;
  37472. let newMain = parseMainXml({
  37473. mainXml: this.mainPlaylistLoader_.mainXml_,
  37474. srcUrl: this.mainPlaylistLoader_.srcUrl,
  37475. clientOffset: this.mainPlaylistLoader_.clientOffset_,
  37476. sidxMapping: this.mainPlaylistLoader_.sidxMapping_,
  37477. previousManifest: oldMain
  37478. }); // if we have an old main to compare the new main against
  37479. if (oldMain) {
  37480. newMain = updateMain(oldMain, newMain, this.mainPlaylistLoader_.sidxMapping_);
  37481. } // only update main if we have a new main
  37482. this.mainPlaylistLoader_.main = newMain ? newMain : oldMain;
  37483. const location = this.mainPlaylistLoader_.main.locations && this.mainPlaylistLoader_.main.locations[0];
  37484. if (location && location !== this.mainPlaylistLoader_.srcUrl) {
  37485. this.mainPlaylistLoader_.srcUrl = location;
  37486. }
  37487. if (!oldMain || newMain && newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  37488. this.updateMinimumUpdatePeriodTimeout_();
  37489. }
  37490. return Boolean(newMain);
  37491. }
  37492. updateMinimumUpdatePeriodTimeout_() {
  37493. const mpl = this.mainPlaylistLoader_; // cancel any pending creation of mup on media
  37494. // a new one will be added if needed.
  37495. if (mpl.createMupOnMedia_) {
  37496. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  37497. mpl.createMupOnMedia_ = null;
  37498. } // clear any pending timeouts
  37499. if (mpl.minimumUpdatePeriodTimeout_) {
  37500. window.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  37501. mpl.minimumUpdatePeriodTimeout_ = null;
  37502. }
  37503. let mup = mpl.main && mpl.main.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  37504. // MPD has no future validity, so a new one will need to be acquired when new
  37505. // media segments are to be made available. Thus, we use the target duration
  37506. // in this case
  37507. if (mup === 0) {
  37508. if (mpl.media()) {
  37509. mup = mpl.media().targetDuration * 1000;
  37510. } else {
  37511. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  37512. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  37513. }
  37514. } // if minimumUpdatePeriod is invalid or <= zero, which
  37515. // can happen when a live video becomes VOD. skip timeout
  37516. // creation.
  37517. if (typeof mup !== 'number' || mup <= 0) {
  37518. if (mup < 0) {
  37519. this.logger_(`found invalid minimumUpdatePeriod of ${mup}, not setting a timeout`);
  37520. }
  37521. return;
  37522. }
  37523. this.createMUPTimeout_(mup);
  37524. }
  37525. createMUPTimeout_(mup) {
  37526. const mpl = this.mainPlaylistLoader_;
  37527. mpl.minimumUpdatePeriodTimeout_ = window.setTimeout(() => {
  37528. mpl.minimumUpdatePeriodTimeout_ = null;
  37529. mpl.trigger('minimumUpdatePeriod');
  37530. mpl.createMUPTimeout_(mup);
  37531. }, mup);
  37532. }
  37533. /**
  37534. * Sends request to refresh the main xml and updates the parsed main manifest
  37535. */
  37536. refreshXml_() {
  37537. this.requestMain_((req, mainChanged) => {
  37538. if (!mainChanged) {
  37539. return;
  37540. }
  37541. if (this.media_) {
  37542. this.media_ = this.mainPlaylistLoader_.main.playlists[this.media_.id];
  37543. } // This will filter out updated sidx info from the mapping
  37544. this.mainPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.sidxMapping_);
  37545. this.addSidxSegments_(this.media(), this.state, sidxChanged => {
  37546. // TODO: do we need to reload the current playlist?
  37547. this.refreshMedia_(this.media().id);
  37548. });
  37549. });
  37550. }
  37551. /**
  37552. * Refreshes the media playlist by re-parsing the main xml and updating playlist
  37553. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  37554. * from the main loader.
  37555. */
  37556. refreshMedia_(mediaID) {
  37557. if (!mediaID) {
  37558. throw new Error('refreshMedia_ must take a media id');
  37559. } // for main we have to reparse the main xml
  37560. // to re-create segments based on current timing values
  37561. // which may change media. We only skip updating the main manifest
  37562. // if this is the first time this.media_ is being set.
  37563. // as main was just parsed in that case.
  37564. if (this.media_ && this.isMain_) {
  37565. this.handleMain_();
  37566. }
  37567. const playlists = this.mainPlaylistLoader_.main.playlists;
  37568. const mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  37569. if (mediaChanged) {
  37570. this.media_ = playlists[mediaID];
  37571. } else {
  37572. this.trigger('playlistunchanged');
  37573. }
  37574. if (!this.mediaUpdateTimeout) {
  37575. const createMediaUpdateTimeout = () => {
  37576. if (this.media().endList) {
  37577. return;
  37578. }
  37579. this.mediaUpdateTimeout = window.setTimeout(() => {
  37580. this.trigger('mediaupdatetimeout');
  37581. createMediaUpdateTimeout();
  37582. }, refreshDelay(this.media(), Boolean(mediaChanged)));
  37583. };
  37584. createMediaUpdateTimeout();
  37585. }
  37586. this.trigger('loadedplaylist');
  37587. }
  37588. }
  37589. var Config = {
  37590. GOAL_BUFFER_LENGTH: 30,
  37591. MAX_GOAL_BUFFER_LENGTH: 60,
  37592. BACK_BUFFER_LENGTH: 30,
  37593. GOAL_BUFFER_LENGTH_RATE: 1,
  37594. // 0.5 MB/s
  37595. INITIAL_BANDWIDTH: 4194304,
  37596. // A fudge factor to apply to advertised playlist bitrates to account for
  37597. // temporary flucations in client bandwidth
  37598. BANDWIDTH_VARIANCE: 1.2,
  37599. // How much of the buffer must be filled before we consider upswitching
  37600. BUFFER_LOW_WATER_LINE: 0,
  37601. MAX_BUFFER_LOW_WATER_LINE: 30,
  37602. // TODO: Remove this when experimentalBufferBasedABR is removed
  37603. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  37604. BUFFER_LOW_WATER_LINE_RATE: 1,
  37605. // If the buffer is greater than the high water line, we won't switch down
  37606. BUFFER_HIGH_WATER_LINE: 30
  37607. };
  37608. const stringToArrayBuffer = string => {
  37609. const view = new Uint8Array(new ArrayBuffer(string.length));
  37610. for (let i = 0; i < string.length; i++) {
  37611. view[i] = string.charCodeAt(i);
  37612. }
  37613. return view.buffer;
  37614. };
  37615. /* global Blob, BlobBuilder, Worker */
  37616. // unify worker interface
  37617. const browserWorkerPolyFill = function (workerObj) {
  37618. // node only supports on/off
  37619. workerObj.on = workerObj.addEventListener;
  37620. workerObj.off = workerObj.removeEventListener;
  37621. return workerObj;
  37622. };
  37623. const createObjectURL = function (str) {
  37624. try {
  37625. return URL.createObjectURL(new Blob([str], {
  37626. type: 'application/javascript'
  37627. }));
  37628. } catch (e) {
  37629. const blob = new BlobBuilder();
  37630. blob.append(str);
  37631. return URL.createObjectURL(blob.getBlob());
  37632. }
  37633. };
  37634. const factory = function (code) {
  37635. return function () {
  37636. const objectUrl = createObjectURL(code);
  37637. const worker = browserWorkerPolyFill(new Worker(objectUrl));
  37638. worker.objURL = objectUrl;
  37639. const terminate = worker.terminate;
  37640. worker.on = worker.addEventListener;
  37641. worker.off = worker.removeEventListener;
  37642. worker.terminate = function () {
  37643. URL.revokeObjectURL(objectUrl);
  37644. return terminate.call(this);
  37645. };
  37646. return worker;
  37647. };
  37648. };
  37649. const transform = function (code) {
  37650. return `var browserWorkerPolyFill = ${browserWorkerPolyFill.toString()};\n` + 'browserWorkerPolyFill(self);\n' + code;
  37651. };
  37652. const getWorkerString = function (fn) {
  37653. return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
  37654. };
  37655. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  37656. const workerCode$1 = transform(getWorkerString(function () {
  37657. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  37658. /**
  37659. * mux.js
  37660. *
  37661. * Copyright (c) Brightcove
  37662. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37663. *
  37664. * A lightweight readable stream implemention that handles event dispatching.
  37665. * Objects that inherit from streams should call init in their constructors.
  37666. */
  37667. var Stream$8 = function () {
  37668. this.init = function () {
  37669. var listeners = {};
  37670. /**
  37671. * Add a listener for a specified event type.
  37672. * @param type {string} the event name
  37673. * @param listener {function} the callback to be invoked when an event of
  37674. * the specified type occurs
  37675. */
  37676. this.on = function (type, listener) {
  37677. if (!listeners[type]) {
  37678. listeners[type] = [];
  37679. }
  37680. listeners[type] = listeners[type].concat(listener);
  37681. };
  37682. /**
  37683. * Remove a listener for a specified event type.
  37684. * @param type {string} the event name
  37685. * @param listener {function} a function previously registered for this
  37686. * type of event through `on`
  37687. */
  37688. this.off = function (type, listener) {
  37689. var index;
  37690. if (!listeners[type]) {
  37691. return false;
  37692. }
  37693. index = listeners[type].indexOf(listener);
  37694. listeners[type] = listeners[type].slice();
  37695. listeners[type].splice(index, 1);
  37696. return index > -1;
  37697. };
  37698. /**
  37699. * Trigger an event of the specified type on this stream. Any additional
  37700. * arguments to this function are passed as parameters to event listeners.
  37701. * @param type {string} the event name
  37702. */
  37703. this.trigger = function (type) {
  37704. var callbacks, i, length, args;
  37705. callbacks = listeners[type];
  37706. if (!callbacks) {
  37707. return;
  37708. } // Slicing the arguments on every invocation of this method
  37709. // can add a significant amount of overhead. Avoid the
  37710. // intermediate object creation for the common case of a
  37711. // single callback argument
  37712. if (arguments.length === 2) {
  37713. length = callbacks.length;
  37714. for (i = 0; i < length; ++i) {
  37715. callbacks[i].call(this, arguments[1]);
  37716. }
  37717. } else {
  37718. args = [];
  37719. i = arguments.length;
  37720. for (i = 1; i < arguments.length; ++i) {
  37721. args.push(arguments[i]);
  37722. }
  37723. length = callbacks.length;
  37724. for (i = 0; i < length; ++i) {
  37725. callbacks[i].apply(this, args);
  37726. }
  37727. }
  37728. };
  37729. /**
  37730. * Destroys the stream and cleans up.
  37731. */
  37732. this.dispose = function () {
  37733. listeners = {};
  37734. };
  37735. };
  37736. };
  37737. /**
  37738. * Forwards all `data` events on this stream to the destination stream. The
  37739. * destination stream should provide a method `push` to receive the data
  37740. * events as they arrive.
  37741. * @param destination {stream} the stream that will receive all `data` events
  37742. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  37743. * when the current stream emits a 'done' event
  37744. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  37745. */
  37746. Stream$8.prototype.pipe = function (destination) {
  37747. this.on('data', function (data) {
  37748. destination.push(data);
  37749. });
  37750. this.on('done', function (flushSource) {
  37751. destination.flush(flushSource);
  37752. });
  37753. this.on('partialdone', function (flushSource) {
  37754. destination.partialFlush(flushSource);
  37755. });
  37756. this.on('endedtimeline', function (flushSource) {
  37757. destination.endTimeline(flushSource);
  37758. });
  37759. this.on('reset', function (flushSource) {
  37760. destination.reset(flushSource);
  37761. });
  37762. return destination;
  37763. }; // Default stream functions that are expected to be overridden to perform
  37764. // actual work. These are provided by the prototype as a sort of no-op
  37765. // implementation so that we don't have to check for their existence in the
  37766. // `pipe` function above.
  37767. Stream$8.prototype.push = function (data) {
  37768. this.trigger('data', data);
  37769. };
  37770. Stream$8.prototype.flush = function (flushSource) {
  37771. this.trigger('done', flushSource);
  37772. };
  37773. Stream$8.prototype.partialFlush = function (flushSource) {
  37774. this.trigger('partialdone', flushSource);
  37775. };
  37776. Stream$8.prototype.endTimeline = function (flushSource) {
  37777. this.trigger('endedtimeline', flushSource);
  37778. };
  37779. Stream$8.prototype.reset = function (flushSource) {
  37780. this.trigger('reset', flushSource);
  37781. };
  37782. var stream = Stream$8;
  37783. var MAX_UINT32$1 = Math.pow(2, 32);
  37784. var getUint64$3 = function (uint8) {
  37785. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  37786. var value;
  37787. if (dv.getBigUint64) {
  37788. value = dv.getBigUint64(0);
  37789. if (value < Number.MAX_SAFE_INTEGER) {
  37790. return Number(value);
  37791. }
  37792. return value;
  37793. }
  37794. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  37795. };
  37796. var numbers = {
  37797. getUint64: getUint64$3,
  37798. MAX_UINT32: MAX_UINT32$1
  37799. };
  37800. /**
  37801. * mux.js
  37802. *
  37803. * Copyright (c) Brightcove
  37804. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37805. *
  37806. * Functions that generate fragmented MP4s suitable for use with Media
  37807. * Source Extensions.
  37808. */
  37809. var MAX_UINT32 = numbers.MAX_UINT32;
  37810. 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
  37811. (function () {
  37812. var i;
  37813. types = {
  37814. avc1: [],
  37815. // codingname
  37816. avcC: [],
  37817. btrt: [],
  37818. dinf: [],
  37819. dref: [],
  37820. esds: [],
  37821. ftyp: [],
  37822. hdlr: [],
  37823. mdat: [],
  37824. mdhd: [],
  37825. mdia: [],
  37826. mfhd: [],
  37827. minf: [],
  37828. moof: [],
  37829. moov: [],
  37830. mp4a: [],
  37831. // codingname
  37832. mvex: [],
  37833. mvhd: [],
  37834. pasp: [],
  37835. sdtp: [],
  37836. smhd: [],
  37837. stbl: [],
  37838. stco: [],
  37839. stsc: [],
  37840. stsd: [],
  37841. stsz: [],
  37842. stts: [],
  37843. styp: [],
  37844. tfdt: [],
  37845. tfhd: [],
  37846. traf: [],
  37847. trak: [],
  37848. trun: [],
  37849. trex: [],
  37850. tkhd: [],
  37851. vmhd: []
  37852. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  37853. // don't throw an error
  37854. if (typeof Uint8Array === 'undefined') {
  37855. return;
  37856. }
  37857. for (i in types) {
  37858. if (types.hasOwnProperty(i)) {
  37859. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  37860. }
  37861. }
  37862. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  37863. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  37864. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  37865. VIDEO_HDLR = new Uint8Array([0x00,
  37866. // version 0
  37867. 0x00, 0x00, 0x00,
  37868. // flags
  37869. 0x00, 0x00, 0x00, 0x00,
  37870. // pre_defined
  37871. 0x76, 0x69, 0x64, 0x65,
  37872. // handler_type: 'vide'
  37873. 0x00, 0x00, 0x00, 0x00,
  37874. // reserved
  37875. 0x00, 0x00, 0x00, 0x00,
  37876. // reserved
  37877. 0x00, 0x00, 0x00, 0x00,
  37878. // reserved
  37879. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  37880. ]);
  37881. AUDIO_HDLR = new Uint8Array([0x00,
  37882. // version 0
  37883. 0x00, 0x00, 0x00,
  37884. // flags
  37885. 0x00, 0x00, 0x00, 0x00,
  37886. // pre_defined
  37887. 0x73, 0x6f, 0x75, 0x6e,
  37888. // handler_type: 'soun'
  37889. 0x00, 0x00, 0x00, 0x00,
  37890. // reserved
  37891. 0x00, 0x00, 0x00, 0x00,
  37892. // reserved
  37893. 0x00, 0x00, 0x00, 0x00,
  37894. // reserved
  37895. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  37896. ]);
  37897. HDLR_TYPES = {
  37898. video: VIDEO_HDLR,
  37899. audio: AUDIO_HDLR
  37900. };
  37901. DREF = new Uint8Array([0x00,
  37902. // version 0
  37903. 0x00, 0x00, 0x00,
  37904. // flags
  37905. 0x00, 0x00, 0x00, 0x01,
  37906. // entry_count
  37907. 0x00, 0x00, 0x00, 0x0c,
  37908. // entry_size
  37909. 0x75, 0x72, 0x6c, 0x20,
  37910. // 'url' type
  37911. 0x00,
  37912. // version 0
  37913. 0x00, 0x00, 0x01 // entry_flags
  37914. ]);
  37915. SMHD = new Uint8Array([0x00,
  37916. // version
  37917. 0x00, 0x00, 0x00,
  37918. // flags
  37919. 0x00, 0x00,
  37920. // balance, 0 means centered
  37921. 0x00, 0x00 // reserved
  37922. ]);
  37923. STCO = new Uint8Array([0x00,
  37924. // version
  37925. 0x00, 0x00, 0x00,
  37926. // flags
  37927. 0x00, 0x00, 0x00, 0x00 // entry_count
  37928. ]);
  37929. STSC = STCO;
  37930. STSZ = new Uint8Array([0x00,
  37931. // version
  37932. 0x00, 0x00, 0x00,
  37933. // flags
  37934. 0x00, 0x00, 0x00, 0x00,
  37935. // sample_size
  37936. 0x00, 0x00, 0x00, 0x00 // sample_count
  37937. ]);
  37938. STTS = STCO;
  37939. VMHD = new Uint8Array([0x00,
  37940. // version
  37941. 0x00, 0x00, 0x01,
  37942. // flags
  37943. 0x00, 0x00,
  37944. // graphicsmode
  37945. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  37946. ]);
  37947. })();
  37948. box = function (type) {
  37949. var payload = [],
  37950. size = 0,
  37951. i,
  37952. result,
  37953. view;
  37954. for (i = 1; i < arguments.length; i++) {
  37955. payload.push(arguments[i]);
  37956. }
  37957. i = payload.length; // calculate the total size we need to allocate
  37958. while (i--) {
  37959. size += payload[i].byteLength;
  37960. }
  37961. result = new Uint8Array(size + 8);
  37962. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  37963. view.setUint32(0, result.byteLength);
  37964. result.set(type, 4); // copy the payload into the result
  37965. for (i = 0, size = 8; i < payload.length; i++) {
  37966. result.set(payload[i], size);
  37967. size += payload[i].byteLength;
  37968. }
  37969. return result;
  37970. };
  37971. dinf = function () {
  37972. return box(types.dinf, box(types.dref, DREF));
  37973. };
  37974. esds = function (track) {
  37975. return box(types.esds, new Uint8Array([0x00,
  37976. // version
  37977. 0x00, 0x00, 0x00,
  37978. // flags
  37979. // ES_Descriptor
  37980. 0x03,
  37981. // tag, ES_DescrTag
  37982. 0x19,
  37983. // length
  37984. 0x00, 0x00,
  37985. // ES_ID
  37986. 0x00,
  37987. // streamDependenceFlag, URL_flag, reserved, streamPriority
  37988. // DecoderConfigDescriptor
  37989. 0x04,
  37990. // tag, DecoderConfigDescrTag
  37991. 0x11,
  37992. // length
  37993. 0x40,
  37994. // object type
  37995. 0x15,
  37996. // streamType
  37997. 0x00, 0x06, 0x00,
  37998. // bufferSizeDB
  37999. 0x00, 0x00, 0xda, 0xc0,
  38000. // maxBitrate
  38001. 0x00, 0x00, 0xda, 0xc0,
  38002. // avgBitrate
  38003. // DecoderSpecificInfo
  38004. 0x05,
  38005. // tag, DecoderSpecificInfoTag
  38006. 0x02,
  38007. // length
  38008. // ISO/IEC 14496-3, AudioSpecificConfig
  38009. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  38010. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  38011. ]));
  38012. };
  38013. ftyp = function () {
  38014. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  38015. };
  38016. hdlr = function (type) {
  38017. return box(types.hdlr, HDLR_TYPES[type]);
  38018. };
  38019. mdat = function (data) {
  38020. return box(types.mdat, data);
  38021. };
  38022. mdhd = function (track) {
  38023. var result = new Uint8Array([0x00,
  38024. // version 0
  38025. 0x00, 0x00, 0x00,
  38026. // flags
  38027. 0x00, 0x00, 0x00, 0x02,
  38028. // creation_time
  38029. 0x00, 0x00, 0x00, 0x03,
  38030. // modification_time
  38031. 0x00, 0x01, 0x5f, 0x90,
  38032. // timescale, 90,000 "ticks" per second
  38033. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF,
  38034. // duration
  38035. 0x55, 0xc4,
  38036. // 'und' language (undetermined)
  38037. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  38038. // defined. The sample rate can be parsed out of an ADTS header, for
  38039. // instance.
  38040. if (track.samplerate) {
  38041. result[12] = track.samplerate >>> 24 & 0xFF;
  38042. result[13] = track.samplerate >>> 16 & 0xFF;
  38043. result[14] = track.samplerate >>> 8 & 0xFF;
  38044. result[15] = track.samplerate & 0xFF;
  38045. }
  38046. return box(types.mdhd, result);
  38047. };
  38048. mdia = function (track) {
  38049. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  38050. };
  38051. mfhd = function (sequenceNumber) {
  38052. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  38053. // flags
  38054. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  38055. ]));
  38056. };
  38057. minf = function (track) {
  38058. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  38059. };
  38060. moof = function (sequenceNumber, tracks) {
  38061. var trackFragments = [],
  38062. i = tracks.length; // build traf boxes for each track fragment
  38063. while (i--) {
  38064. trackFragments[i] = traf(tracks[i]);
  38065. }
  38066. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  38067. };
  38068. /**
  38069. * Returns a movie box.
  38070. * @param tracks {array} the tracks associated with this movie
  38071. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  38072. */
  38073. moov = function (tracks) {
  38074. var i = tracks.length,
  38075. boxes = [];
  38076. while (i--) {
  38077. boxes[i] = trak(tracks[i]);
  38078. }
  38079. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  38080. };
  38081. mvex = function (tracks) {
  38082. var i = tracks.length,
  38083. boxes = [];
  38084. while (i--) {
  38085. boxes[i] = trex(tracks[i]);
  38086. }
  38087. return box.apply(null, [types.mvex].concat(boxes));
  38088. };
  38089. mvhd = function (duration) {
  38090. var bytes = new Uint8Array([0x00,
  38091. // version 0
  38092. 0x00, 0x00, 0x00,
  38093. // flags
  38094. 0x00, 0x00, 0x00, 0x01,
  38095. // creation_time
  38096. 0x00, 0x00, 0x00, 0x02,
  38097. // modification_time
  38098. 0x00, 0x01, 0x5f, 0x90,
  38099. // timescale, 90,000 "ticks" per second
  38100. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF,
  38101. // duration
  38102. 0x00, 0x01, 0x00, 0x00,
  38103. // 1.0 rate
  38104. 0x01, 0x00,
  38105. // 1.0 volume
  38106. 0x00, 0x00,
  38107. // reserved
  38108. 0x00, 0x00, 0x00, 0x00,
  38109. // reserved
  38110. 0x00, 0x00, 0x00, 0x00,
  38111. // reserved
  38112. 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,
  38113. // transformation: unity matrix
  38114. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  38115. // pre_defined
  38116. 0xff, 0xff, 0xff, 0xff // next_track_ID
  38117. ]);
  38118. return box(types.mvhd, bytes);
  38119. };
  38120. sdtp = function (track) {
  38121. var samples = track.samples || [],
  38122. bytes = new Uint8Array(4 + samples.length),
  38123. flags,
  38124. i; // leave the full box header (4 bytes) all zero
  38125. // write the sample table
  38126. for (i = 0; i < samples.length; i++) {
  38127. flags = samples[i].flags;
  38128. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  38129. }
  38130. return box(types.sdtp, bytes);
  38131. };
  38132. stbl = function (track) {
  38133. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  38134. };
  38135. (function () {
  38136. var videoSample, audioSample;
  38137. stsd = function (track) {
  38138. return box(types.stsd, new Uint8Array([0x00,
  38139. // version 0
  38140. 0x00, 0x00, 0x00,
  38141. // flags
  38142. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  38143. };
  38144. videoSample = function (track) {
  38145. var sps = track.sps || [],
  38146. pps = track.pps || [],
  38147. sequenceParameterSets = [],
  38148. pictureParameterSets = [],
  38149. i,
  38150. avc1Box; // assemble the SPSs
  38151. for (i = 0; i < sps.length; i++) {
  38152. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  38153. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  38154. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  38155. } // assemble the PPSs
  38156. for (i = 0; i < pps.length; i++) {
  38157. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  38158. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  38159. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  38160. }
  38161. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  38162. // reserved
  38163. 0x00, 0x01,
  38164. // data_reference_index
  38165. 0x00, 0x00,
  38166. // pre_defined
  38167. 0x00, 0x00,
  38168. // reserved
  38169. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  38170. // pre_defined
  38171. (track.width & 0xff00) >> 8, track.width & 0xff,
  38172. // width
  38173. (track.height & 0xff00) >> 8, track.height & 0xff,
  38174. // height
  38175. 0x00, 0x48, 0x00, 0x00,
  38176. // horizresolution
  38177. 0x00, 0x48, 0x00, 0x00,
  38178. // vertresolution
  38179. 0x00, 0x00, 0x00, 0x00,
  38180. // reserved
  38181. 0x00, 0x01,
  38182. // frame_count
  38183. 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,
  38184. // compressorname
  38185. 0x00, 0x18,
  38186. // depth = 24
  38187. 0x11, 0x11 // pre_defined = -1
  38188. ]), box(types.avcC, new Uint8Array([0x01,
  38189. // configurationVersion
  38190. track.profileIdc,
  38191. // AVCProfileIndication
  38192. track.profileCompatibility,
  38193. // profile_compatibility
  38194. track.levelIdc,
  38195. // AVCLevelIndication
  38196. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  38197. ].concat([sps.length],
  38198. // numOfSequenceParameterSets
  38199. sequenceParameterSets,
  38200. // "SPS"
  38201. [pps.length],
  38202. // numOfPictureParameterSets
  38203. pictureParameterSets // "PPS"
  38204. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  38205. // bufferSizeDB
  38206. 0x00, 0x2d, 0xc6, 0xc0,
  38207. // maxBitrate
  38208. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  38209. ]))];
  38210. if (track.sarRatio) {
  38211. var hSpacing = track.sarRatio[0],
  38212. vSpacing = track.sarRatio[1];
  38213. 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])));
  38214. }
  38215. return box.apply(null, avc1Box);
  38216. };
  38217. audioSample = function (track) {
  38218. return box(types.mp4a, new Uint8Array([
  38219. // SampleEntry, ISO/IEC 14496-12
  38220. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  38221. // reserved
  38222. 0x00, 0x01,
  38223. // data_reference_index
  38224. // AudioSampleEntry, ISO/IEC 14496-12
  38225. 0x00, 0x00, 0x00, 0x00,
  38226. // reserved
  38227. 0x00, 0x00, 0x00, 0x00,
  38228. // reserved
  38229. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff,
  38230. // channelcount
  38231. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff,
  38232. // samplesize
  38233. 0x00, 0x00,
  38234. // pre_defined
  38235. 0x00, 0x00,
  38236. // reserved
  38237. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  38238. // MP4AudioSampleEntry, ISO/IEC 14496-14
  38239. ]), esds(track));
  38240. };
  38241. })();
  38242. tkhd = function (track) {
  38243. var result = new Uint8Array([0x00,
  38244. // version 0
  38245. 0x00, 0x00, 0x07,
  38246. // flags
  38247. 0x00, 0x00, 0x00, 0x00,
  38248. // creation_time
  38249. 0x00, 0x00, 0x00, 0x00,
  38250. // modification_time
  38251. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,
  38252. // track_ID
  38253. 0x00, 0x00, 0x00, 0x00,
  38254. // reserved
  38255. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF,
  38256. // duration
  38257. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  38258. // reserved
  38259. 0x00, 0x00,
  38260. // layer
  38261. 0x00, 0x00,
  38262. // alternate_group
  38263. 0x01, 0x00,
  38264. // non-audio track volume
  38265. 0x00, 0x00,
  38266. // reserved
  38267. 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,
  38268. // transformation: unity matrix
  38269. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00,
  38270. // width
  38271. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  38272. ]);
  38273. return box(types.tkhd, result);
  38274. };
  38275. /**
  38276. * Generate a track fragment (traf) box. A traf box collects metadata
  38277. * about tracks in a movie fragment (moof) box.
  38278. */
  38279. traf = function (track) {
  38280. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  38281. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00,
  38282. // version 0
  38283. 0x00, 0x00, 0x3a,
  38284. // flags
  38285. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,
  38286. // track_ID
  38287. 0x00, 0x00, 0x00, 0x01,
  38288. // sample_description_index
  38289. 0x00, 0x00, 0x00, 0x00,
  38290. // default_sample_duration
  38291. 0x00, 0x00, 0x00, 0x00,
  38292. // default_sample_size
  38293. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  38294. ]));
  38295. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  38296. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  38297. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01,
  38298. // version 1
  38299. 0x00, 0x00, 0x00,
  38300. // flags
  38301. // baseMediaDecodeTime
  38302. 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
  38303. // the containing moof to the first payload byte of the associated
  38304. // mdat
  38305. dataOffset = 32 +
  38306. // tfhd
  38307. 20 +
  38308. // tfdt
  38309. 8 +
  38310. // traf header
  38311. 16 +
  38312. // mfhd
  38313. 8 +
  38314. // moof header
  38315. 8; // mdat header
  38316. // audio tracks require less metadata
  38317. if (track.type === 'audio') {
  38318. trackFragmentRun = trun$1(track, dataOffset);
  38319. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  38320. } // video tracks should contain an independent and disposable samples
  38321. // box (sdtp)
  38322. // generate one and adjust offsets to match
  38323. sampleDependencyTable = sdtp(track);
  38324. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  38325. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  38326. };
  38327. /**
  38328. * Generate a track box.
  38329. * @param track {object} a track definition
  38330. * @return {Uint8Array} the track box
  38331. */
  38332. trak = function (track) {
  38333. track.duration = track.duration || 0xffffffff;
  38334. return box(types.trak, tkhd(track), mdia(track));
  38335. };
  38336. trex = function (track) {
  38337. var result = new Uint8Array([0x00,
  38338. // version 0
  38339. 0x00, 0x00, 0x00,
  38340. // flags
  38341. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,
  38342. // track_ID
  38343. 0x00, 0x00, 0x00, 0x01,
  38344. // default_sample_description_index
  38345. 0x00, 0x00, 0x00, 0x00,
  38346. // default_sample_duration
  38347. 0x00, 0x00, 0x00, 0x00,
  38348. // default_sample_size
  38349. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  38350. ]); // the last two bytes of default_sample_flags is the sample
  38351. // degradation priority, a hint about the importance of this sample
  38352. // relative to others. Lower the degradation priority for all sample
  38353. // types other than video.
  38354. if (track.type !== 'video') {
  38355. result[result.length - 1] = 0x00;
  38356. }
  38357. return box(types.trex, result);
  38358. };
  38359. (function () {
  38360. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  38361. // duration is present for the first sample, it will be present for
  38362. // all subsequent samples.
  38363. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  38364. trunHeader = function (samples, offset) {
  38365. var durationPresent = 0,
  38366. sizePresent = 0,
  38367. flagsPresent = 0,
  38368. compositionTimeOffset = 0; // trun flag constants
  38369. if (samples.length) {
  38370. if (samples[0].duration !== undefined) {
  38371. durationPresent = 0x1;
  38372. }
  38373. if (samples[0].size !== undefined) {
  38374. sizePresent = 0x2;
  38375. }
  38376. if (samples[0].flags !== undefined) {
  38377. flagsPresent = 0x4;
  38378. }
  38379. if (samples[0].compositionTimeOffset !== undefined) {
  38380. compositionTimeOffset = 0x8;
  38381. }
  38382. }
  38383. return [0x00,
  38384. // version 0
  38385. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01,
  38386. // flags
  38387. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF,
  38388. // sample_count
  38389. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  38390. ];
  38391. };
  38392. videoTrun = function (track, offset) {
  38393. var bytesOffest, bytes, header, samples, sample, i;
  38394. samples = track.samples || [];
  38395. offset += 8 + 12 + 16 * samples.length;
  38396. header = trunHeader(samples, offset);
  38397. bytes = new Uint8Array(header.length + samples.length * 16);
  38398. bytes.set(header);
  38399. bytesOffest = header.length;
  38400. for (i = 0; i < samples.length; i++) {
  38401. sample = samples[i];
  38402. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  38403. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  38404. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  38405. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  38406. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  38407. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  38408. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  38409. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  38410. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  38411. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  38412. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  38413. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  38414. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  38415. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  38416. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  38417. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  38418. }
  38419. return box(types.trun, bytes);
  38420. };
  38421. audioTrun = function (track, offset) {
  38422. var bytes, bytesOffest, header, samples, sample, i;
  38423. samples = track.samples || [];
  38424. offset += 8 + 12 + 8 * samples.length;
  38425. header = trunHeader(samples, offset);
  38426. bytes = new Uint8Array(header.length + samples.length * 8);
  38427. bytes.set(header);
  38428. bytesOffest = header.length;
  38429. for (i = 0; i < samples.length; i++) {
  38430. sample = samples[i];
  38431. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  38432. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  38433. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  38434. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  38435. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  38436. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  38437. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  38438. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  38439. }
  38440. return box(types.trun, bytes);
  38441. };
  38442. trun$1 = function (track, offset) {
  38443. if (track.type === 'audio') {
  38444. return audioTrun(track, offset);
  38445. }
  38446. return videoTrun(track, offset);
  38447. };
  38448. })();
  38449. var mp4Generator = {
  38450. ftyp: ftyp,
  38451. mdat: mdat,
  38452. moof: moof,
  38453. moov: moov,
  38454. initSegment: function (tracks) {
  38455. var fileType = ftyp(),
  38456. movie = moov(tracks),
  38457. result;
  38458. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  38459. result.set(fileType);
  38460. result.set(movie, fileType.byteLength);
  38461. return result;
  38462. }
  38463. };
  38464. /**
  38465. * mux.js
  38466. *
  38467. * Copyright (c) Brightcove
  38468. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  38469. */
  38470. // composed of the nal units that make up that frame
  38471. // Also keep track of cummulative data about the frame from the nal units such
  38472. // as the frame duration, starting pts, etc.
  38473. var groupNalsIntoFrames = function (nalUnits) {
  38474. var i,
  38475. currentNal,
  38476. currentFrame = [],
  38477. frames = []; // TODO added for LHLS, make sure this is OK
  38478. frames.byteLength = 0;
  38479. frames.nalCount = 0;
  38480. frames.duration = 0;
  38481. currentFrame.byteLength = 0;
  38482. for (i = 0; i < nalUnits.length; i++) {
  38483. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  38484. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  38485. // Since the very first nal unit is expected to be an AUD
  38486. // only push to the frames array when currentFrame is not empty
  38487. if (currentFrame.length) {
  38488. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  38489. frames.byteLength += currentFrame.byteLength;
  38490. frames.nalCount += currentFrame.length;
  38491. frames.duration += currentFrame.duration;
  38492. frames.push(currentFrame);
  38493. }
  38494. currentFrame = [currentNal];
  38495. currentFrame.byteLength = currentNal.data.byteLength;
  38496. currentFrame.pts = currentNal.pts;
  38497. currentFrame.dts = currentNal.dts;
  38498. } else {
  38499. // Specifically flag key frames for ease of use later
  38500. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  38501. currentFrame.keyFrame = true;
  38502. }
  38503. currentFrame.duration = currentNal.dts - currentFrame.dts;
  38504. currentFrame.byteLength += currentNal.data.byteLength;
  38505. currentFrame.push(currentNal);
  38506. }
  38507. } // For the last frame, use the duration of the previous frame if we
  38508. // have nothing better to go on
  38509. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  38510. currentFrame.duration = frames[frames.length - 1].duration;
  38511. } // Push the final frame
  38512. // TODO added for LHLS, make sure this is OK
  38513. frames.byteLength += currentFrame.byteLength;
  38514. frames.nalCount += currentFrame.length;
  38515. frames.duration += currentFrame.duration;
  38516. frames.push(currentFrame);
  38517. return frames;
  38518. }; // Convert an array of frames into an array of Gop with each Gop being composed
  38519. // of the frames that make up that Gop
  38520. // Also keep track of cummulative data about the Gop from the frames such as the
  38521. // Gop duration, starting pts, etc.
  38522. var groupFramesIntoGops = function (frames) {
  38523. var i,
  38524. currentFrame,
  38525. currentGop = [],
  38526. gops = []; // We must pre-set some of the values on the Gop since we
  38527. // keep running totals of these values
  38528. currentGop.byteLength = 0;
  38529. currentGop.nalCount = 0;
  38530. currentGop.duration = 0;
  38531. currentGop.pts = frames[0].pts;
  38532. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  38533. gops.byteLength = 0;
  38534. gops.nalCount = 0;
  38535. gops.duration = 0;
  38536. gops.pts = frames[0].pts;
  38537. gops.dts = frames[0].dts;
  38538. for (i = 0; i < frames.length; i++) {
  38539. currentFrame = frames[i];
  38540. if (currentFrame.keyFrame) {
  38541. // Since the very first frame is expected to be an keyframe
  38542. // only push to the gops array when currentGop is not empty
  38543. if (currentGop.length) {
  38544. gops.push(currentGop);
  38545. gops.byteLength += currentGop.byteLength;
  38546. gops.nalCount += currentGop.nalCount;
  38547. gops.duration += currentGop.duration;
  38548. }
  38549. currentGop = [currentFrame];
  38550. currentGop.nalCount = currentFrame.length;
  38551. currentGop.byteLength = currentFrame.byteLength;
  38552. currentGop.pts = currentFrame.pts;
  38553. currentGop.dts = currentFrame.dts;
  38554. currentGop.duration = currentFrame.duration;
  38555. } else {
  38556. currentGop.duration += currentFrame.duration;
  38557. currentGop.nalCount += currentFrame.length;
  38558. currentGop.byteLength += currentFrame.byteLength;
  38559. currentGop.push(currentFrame);
  38560. }
  38561. }
  38562. if (gops.length && currentGop.duration <= 0) {
  38563. currentGop.duration = gops[gops.length - 1].duration;
  38564. }
  38565. gops.byteLength += currentGop.byteLength;
  38566. gops.nalCount += currentGop.nalCount;
  38567. gops.duration += currentGop.duration; // push the final Gop
  38568. gops.push(currentGop);
  38569. return gops;
  38570. };
  38571. /*
  38572. * Search for the first keyframe in the GOPs and throw away all frames
  38573. * until that keyframe. Then extend the duration of the pulled keyframe
  38574. * and pull the PTS and DTS of the keyframe so that it covers the time
  38575. * range of the frames that were disposed.
  38576. *
  38577. * @param {Array} gops video GOPs
  38578. * @returns {Array} modified video GOPs
  38579. */
  38580. var extendFirstKeyFrame = function (gops) {
  38581. var currentGop;
  38582. if (!gops[0][0].keyFrame && gops.length > 1) {
  38583. // Remove the first GOP
  38584. currentGop = gops.shift();
  38585. gops.byteLength -= currentGop.byteLength;
  38586. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  38587. // first gop to cover the time period of the
  38588. // frames we just removed
  38589. gops[0][0].dts = currentGop.dts;
  38590. gops[0][0].pts = currentGop.pts;
  38591. gops[0][0].duration += currentGop.duration;
  38592. }
  38593. return gops;
  38594. };
  38595. /**
  38596. * Default sample object
  38597. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  38598. */
  38599. var createDefaultSample = function () {
  38600. return {
  38601. size: 0,
  38602. flags: {
  38603. isLeading: 0,
  38604. dependsOn: 1,
  38605. isDependedOn: 0,
  38606. hasRedundancy: 0,
  38607. degradationPriority: 0,
  38608. isNonSyncSample: 1
  38609. }
  38610. };
  38611. };
  38612. /*
  38613. * Collates information from a video frame into an object for eventual
  38614. * entry into an MP4 sample table.
  38615. *
  38616. * @param {Object} frame the video frame
  38617. * @param {Number} dataOffset the byte offset to position the sample
  38618. * @return {Object} object containing sample table info for a frame
  38619. */
  38620. var sampleForFrame = function (frame, dataOffset) {
  38621. var sample = createDefaultSample();
  38622. sample.dataOffset = dataOffset;
  38623. sample.compositionTimeOffset = frame.pts - frame.dts;
  38624. sample.duration = frame.duration;
  38625. sample.size = 4 * frame.length; // Space for nal unit size
  38626. sample.size += frame.byteLength;
  38627. if (frame.keyFrame) {
  38628. sample.flags.dependsOn = 2;
  38629. sample.flags.isNonSyncSample = 0;
  38630. }
  38631. return sample;
  38632. }; // generate the track's sample table from an array of gops
  38633. var generateSampleTable$1 = function (gops, baseDataOffset) {
  38634. var h,
  38635. i,
  38636. sample,
  38637. currentGop,
  38638. currentFrame,
  38639. dataOffset = baseDataOffset || 0,
  38640. samples = [];
  38641. for (h = 0; h < gops.length; h++) {
  38642. currentGop = gops[h];
  38643. for (i = 0; i < currentGop.length; i++) {
  38644. currentFrame = currentGop[i];
  38645. sample = sampleForFrame(currentFrame, dataOffset);
  38646. dataOffset += sample.size;
  38647. samples.push(sample);
  38648. }
  38649. }
  38650. return samples;
  38651. }; // generate the track's raw mdat data from an array of gops
  38652. var concatenateNalData = function (gops) {
  38653. var h,
  38654. i,
  38655. j,
  38656. currentGop,
  38657. currentFrame,
  38658. currentNal,
  38659. dataOffset = 0,
  38660. nalsByteLength = gops.byteLength,
  38661. numberOfNals = gops.nalCount,
  38662. totalByteLength = nalsByteLength + 4 * numberOfNals,
  38663. data = new Uint8Array(totalByteLength),
  38664. view = new DataView(data.buffer); // For each Gop..
  38665. for (h = 0; h < gops.length; h++) {
  38666. currentGop = gops[h]; // For each Frame..
  38667. for (i = 0; i < currentGop.length; i++) {
  38668. currentFrame = currentGop[i]; // For each NAL..
  38669. for (j = 0; j < currentFrame.length; j++) {
  38670. currentNal = currentFrame[j];
  38671. view.setUint32(dataOffset, currentNal.data.byteLength);
  38672. dataOffset += 4;
  38673. data.set(currentNal.data, dataOffset);
  38674. dataOffset += currentNal.data.byteLength;
  38675. }
  38676. }
  38677. }
  38678. return data;
  38679. }; // generate the track's sample table from a frame
  38680. var generateSampleTableForFrame = function (frame, baseDataOffset) {
  38681. var sample,
  38682. dataOffset = baseDataOffset || 0,
  38683. samples = [];
  38684. sample = sampleForFrame(frame, dataOffset);
  38685. samples.push(sample);
  38686. return samples;
  38687. }; // generate the track's raw mdat data from a frame
  38688. var concatenateNalDataForFrame = function (frame) {
  38689. var i,
  38690. currentNal,
  38691. dataOffset = 0,
  38692. nalsByteLength = frame.byteLength,
  38693. numberOfNals = frame.length,
  38694. totalByteLength = nalsByteLength + 4 * numberOfNals,
  38695. data = new Uint8Array(totalByteLength),
  38696. view = new DataView(data.buffer); // For each NAL..
  38697. for (i = 0; i < frame.length; i++) {
  38698. currentNal = frame[i];
  38699. view.setUint32(dataOffset, currentNal.data.byteLength);
  38700. dataOffset += 4;
  38701. data.set(currentNal.data, dataOffset);
  38702. dataOffset += currentNal.data.byteLength;
  38703. }
  38704. return data;
  38705. };
  38706. var frameUtils$1 = {
  38707. groupNalsIntoFrames: groupNalsIntoFrames,
  38708. groupFramesIntoGops: groupFramesIntoGops,
  38709. extendFirstKeyFrame: extendFirstKeyFrame,
  38710. generateSampleTable: generateSampleTable$1,
  38711. concatenateNalData: concatenateNalData,
  38712. generateSampleTableForFrame: generateSampleTableForFrame,
  38713. concatenateNalDataForFrame: concatenateNalDataForFrame
  38714. };
  38715. /**
  38716. * mux.js
  38717. *
  38718. * Copyright (c) Brightcove
  38719. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  38720. */
  38721. var highPrefix = [33, 16, 5, 32, 164, 27];
  38722. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  38723. var zeroFill = function (count) {
  38724. var a = [];
  38725. while (count--) {
  38726. a.push(0);
  38727. }
  38728. return a;
  38729. };
  38730. var makeTable = function (metaTable) {
  38731. return Object.keys(metaTable).reduce(function (obj, key) {
  38732. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  38733. return arr.concat(part);
  38734. }, []));
  38735. return obj;
  38736. }, {});
  38737. };
  38738. var silence;
  38739. var silence_1 = function () {
  38740. if (!silence) {
  38741. // Frames-of-silence to use for filling in missing AAC frames
  38742. var coneOfSilence = {
  38743. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  38744. 88200: [highPrefix, [231], zeroFill(170), [56]],
  38745. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  38746. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  38747. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  38748. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  38749. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  38750. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  38751. 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]],
  38752. 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]],
  38753. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  38754. };
  38755. silence = makeTable(coneOfSilence);
  38756. }
  38757. return silence;
  38758. };
  38759. /**
  38760. * mux.js
  38761. *
  38762. * Copyright (c) Brightcove
  38763. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  38764. */
  38765. var ONE_SECOND_IN_TS$4 = 90000,
  38766. // 90kHz clock
  38767. secondsToVideoTs,
  38768. secondsToAudioTs,
  38769. videoTsToSeconds,
  38770. audioTsToSeconds,
  38771. audioTsToVideoTs,
  38772. videoTsToAudioTs,
  38773. metadataTsToSeconds;
  38774. secondsToVideoTs = function (seconds) {
  38775. return seconds * ONE_SECOND_IN_TS$4;
  38776. };
  38777. secondsToAudioTs = function (seconds, sampleRate) {
  38778. return seconds * sampleRate;
  38779. };
  38780. videoTsToSeconds = function (timestamp) {
  38781. return timestamp / ONE_SECOND_IN_TS$4;
  38782. };
  38783. audioTsToSeconds = function (timestamp, sampleRate) {
  38784. return timestamp / sampleRate;
  38785. };
  38786. audioTsToVideoTs = function (timestamp, sampleRate) {
  38787. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  38788. };
  38789. videoTsToAudioTs = function (timestamp, sampleRate) {
  38790. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  38791. };
  38792. /**
  38793. * Adjust ID3 tag or caption timing information by the timeline pts values
  38794. * (if keepOriginalTimestamps is false) and convert to seconds
  38795. */
  38796. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  38797. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  38798. };
  38799. var clock$2 = {
  38800. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  38801. secondsToVideoTs: secondsToVideoTs,
  38802. secondsToAudioTs: secondsToAudioTs,
  38803. videoTsToSeconds: videoTsToSeconds,
  38804. audioTsToSeconds: audioTsToSeconds,
  38805. audioTsToVideoTs: audioTsToVideoTs,
  38806. videoTsToAudioTs: videoTsToAudioTs,
  38807. metadataTsToSeconds: metadataTsToSeconds
  38808. };
  38809. /**
  38810. * mux.js
  38811. *
  38812. * Copyright (c) Brightcove
  38813. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  38814. */
  38815. var coneOfSilence = silence_1;
  38816. var clock$1 = clock$2;
  38817. /**
  38818. * Sum the `byteLength` properties of the data in each AAC frame
  38819. */
  38820. var sumFrameByteLengths = function (array) {
  38821. var i,
  38822. currentObj,
  38823. sum = 0; // sum the byteLength's all each nal unit in the frame
  38824. for (i = 0; i < array.length; i++) {
  38825. currentObj = array[i];
  38826. sum += currentObj.data.byteLength;
  38827. }
  38828. return sum;
  38829. }; // Possibly pad (prefix) the audio track with silence if appending this track
  38830. // would lead to the introduction of a gap in the audio buffer
  38831. var prefixWithSilence = function (track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  38832. var baseMediaDecodeTimeTs,
  38833. frameDuration = 0,
  38834. audioGapDuration = 0,
  38835. audioFillFrameCount = 0,
  38836. audioFillDuration = 0,
  38837. silentFrame,
  38838. i,
  38839. firstFrame;
  38840. if (!frames.length) {
  38841. return;
  38842. }
  38843. baseMediaDecodeTimeTs = clock$1.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  38844. frameDuration = Math.ceil(clock$1.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  38845. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  38846. // insert the shortest possible amount (audio gap or audio to video gap)
  38847. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  38848. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  38849. audioFillDuration = audioFillFrameCount * frameDuration;
  38850. } // don't attempt to fill gaps smaller than a single frame or larger
  38851. // than a half second
  38852. if (audioFillFrameCount < 1 || audioFillDuration > clock$1.ONE_SECOND_IN_TS / 2) {
  38853. return;
  38854. }
  38855. silentFrame = coneOfSilence()[track.samplerate];
  38856. if (!silentFrame) {
  38857. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  38858. // from the content instead
  38859. silentFrame = frames[0].data;
  38860. }
  38861. for (i = 0; i < audioFillFrameCount; i++) {
  38862. firstFrame = frames[0];
  38863. frames.splice(0, 0, {
  38864. data: silentFrame,
  38865. dts: firstFrame.dts - frameDuration,
  38866. pts: firstFrame.pts - frameDuration
  38867. });
  38868. }
  38869. track.baseMediaDecodeTime -= Math.floor(clock$1.videoTsToAudioTs(audioFillDuration, track.samplerate));
  38870. return audioFillDuration;
  38871. }; // If the audio segment extends before the earliest allowed dts
  38872. // value, remove AAC frames until starts at or after the earliest
  38873. // allowed DTS so that we don't end up with a negative baseMedia-
  38874. // DecodeTime for the audio track
  38875. var trimAdtsFramesByEarliestDts = function (adtsFrames, track, earliestAllowedDts) {
  38876. if (track.minSegmentDts >= earliestAllowedDts) {
  38877. return adtsFrames;
  38878. } // We will need to recalculate the earliest segment Dts
  38879. track.minSegmentDts = Infinity;
  38880. return adtsFrames.filter(function (currentFrame) {
  38881. // If this is an allowed frame, keep it and record it's Dts
  38882. if (currentFrame.dts >= earliestAllowedDts) {
  38883. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  38884. track.minSegmentPts = track.minSegmentDts;
  38885. return true;
  38886. } // Otherwise, discard it
  38887. return false;
  38888. });
  38889. }; // generate the track's raw mdat data from an array of frames
  38890. var generateSampleTable = function (frames) {
  38891. var i,
  38892. currentFrame,
  38893. samples = [];
  38894. for (i = 0; i < frames.length; i++) {
  38895. currentFrame = frames[i];
  38896. samples.push({
  38897. size: currentFrame.data.byteLength,
  38898. duration: 1024 // For AAC audio, all samples contain 1024 samples
  38899. });
  38900. }
  38901. return samples;
  38902. }; // generate the track's sample table from an array of frames
  38903. var concatenateFrameData = function (frames) {
  38904. var i,
  38905. currentFrame,
  38906. dataOffset = 0,
  38907. data = new Uint8Array(sumFrameByteLengths(frames));
  38908. for (i = 0; i < frames.length; i++) {
  38909. currentFrame = frames[i];
  38910. data.set(currentFrame.data, dataOffset);
  38911. dataOffset += currentFrame.data.byteLength;
  38912. }
  38913. return data;
  38914. };
  38915. var audioFrameUtils$1 = {
  38916. prefixWithSilence: prefixWithSilence,
  38917. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  38918. generateSampleTable: generateSampleTable,
  38919. concatenateFrameData: concatenateFrameData
  38920. };
  38921. /**
  38922. * mux.js
  38923. *
  38924. * Copyright (c) Brightcove
  38925. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  38926. */
  38927. var ONE_SECOND_IN_TS$3 = clock$2.ONE_SECOND_IN_TS;
  38928. /**
  38929. * Store information about the start and end of the track and the
  38930. * duration for each frame/sample we process in order to calculate
  38931. * the baseMediaDecodeTime
  38932. */
  38933. var collectDtsInfo = function (track, data) {
  38934. if (typeof data.pts === 'number') {
  38935. if (track.timelineStartInfo.pts === undefined) {
  38936. track.timelineStartInfo.pts = data.pts;
  38937. }
  38938. if (track.minSegmentPts === undefined) {
  38939. track.minSegmentPts = data.pts;
  38940. } else {
  38941. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  38942. }
  38943. if (track.maxSegmentPts === undefined) {
  38944. track.maxSegmentPts = data.pts;
  38945. } else {
  38946. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  38947. }
  38948. }
  38949. if (typeof data.dts === 'number') {
  38950. if (track.timelineStartInfo.dts === undefined) {
  38951. track.timelineStartInfo.dts = data.dts;
  38952. }
  38953. if (track.minSegmentDts === undefined) {
  38954. track.minSegmentDts = data.dts;
  38955. } else {
  38956. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  38957. }
  38958. if (track.maxSegmentDts === undefined) {
  38959. track.maxSegmentDts = data.dts;
  38960. } else {
  38961. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  38962. }
  38963. }
  38964. };
  38965. /**
  38966. * Clear values used to calculate the baseMediaDecodeTime between
  38967. * tracks
  38968. */
  38969. var clearDtsInfo = function (track) {
  38970. delete track.minSegmentDts;
  38971. delete track.maxSegmentDts;
  38972. delete track.minSegmentPts;
  38973. delete track.maxSegmentPts;
  38974. };
  38975. /**
  38976. * Calculate the track's baseMediaDecodeTime based on the earliest
  38977. * DTS the transmuxer has ever seen and the minimum DTS for the
  38978. * current track
  38979. * @param track {object} track metadata configuration
  38980. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  38981. * in the source; false to adjust the first segment to start at 0.
  38982. */
  38983. var calculateTrackBaseMediaDecodeTime = function (track, keepOriginalTimestamps) {
  38984. var baseMediaDecodeTime,
  38985. scale,
  38986. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  38987. if (!keepOriginalTimestamps) {
  38988. minSegmentDts -= track.timelineStartInfo.dts;
  38989. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  38990. // we want the start of the first segment to be placed
  38991. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  38992. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  38993. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  38994. if (track.type === 'audio') {
  38995. // Audio has a different clock equal to the sampling_rate so we need to
  38996. // scale the PTS values into the clock rate of the track
  38997. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  38998. baseMediaDecodeTime *= scale;
  38999. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  39000. }
  39001. return baseMediaDecodeTime;
  39002. };
  39003. var trackDecodeInfo$1 = {
  39004. clearDtsInfo: clearDtsInfo,
  39005. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  39006. collectDtsInfo: collectDtsInfo
  39007. };
  39008. /**
  39009. * mux.js
  39010. *
  39011. * Copyright (c) Brightcove
  39012. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  39013. *
  39014. * Reads in-band caption information from a video elementary
  39015. * stream. Captions must follow the CEA-708 standard for injection
  39016. * into an MPEG-2 transport streams.
  39017. * @see https://en.wikipedia.org/wiki/CEA-708
  39018. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  39019. */
  39020. // payload type field to indicate how they are to be
  39021. // interpreted. CEAS-708 caption content is always transmitted with
  39022. // payload type 0x04.
  39023. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  39024. RBSP_TRAILING_BITS = 128;
  39025. /**
  39026. * Parse a supplemental enhancement information (SEI) NAL unit.
  39027. * Stops parsing once a message of type ITU T T35 has been found.
  39028. *
  39029. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  39030. * @return {object} the parsed SEI payload
  39031. * @see Rec. ITU-T H.264, 7.3.2.3.1
  39032. */
  39033. var parseSei = function (bytes) {
  39034. var i = 0,
  39035. result = {
  39036. payloadType: -1,
  39037. payloadSize: 0
  39038. },
  39039. payloadType = 0,
  39040. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  39041. while (i < bytes.byteLength) {
  39042. // stop once we have hit the end of the sei_rbsp
  39043. if (bytes[i] === RBSP_TRAILING_BITS) {
  39044. break;
  39045. } // Parse payload type
  39046. while (bytes[i] === 0xFF) {
  39047. payloadType += 255;
  39048. i++;
  39049. }
  39050. payloadType += bytes[i++]; // Parse payload size
  39051. while (bytes[i] === 0xFF) {
  39052. payloadSize += 255;
  39053. i++;
  39054. }
  39055. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  39056. // there can only ever be one caption message in a frame's sei
  39057. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  39058. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  39059. if (userIdentifier === 'GA94') {
  39060. result.payloadType = payloadType;
  39061. result.payloadSize = payloadSize;
  39062. result.payload = bytes.subarray(i, i + payloadSize);
  39063. break;
  39064. } else {
  39065. result.payload = void 0;
  39066. }
  39067. } // skip the payload and parse the next message
  39068. i += payloadSize;
  39069. payloadType = 0;
  39070. payloadSize = 0;
  39071. }
  39072. return result;
  39073. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  39074. var parseUserData = function (sei) {
  39075. // itu_t_t35_contry_code must be 181 (United States) for
  39076. // captions
  39077. if (sei.payload[0] !== 181) {
  39078. return null;
  39079. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  39080. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  39081. return null;
  39082. } // the user_identifier should be "GA94" to indicate ATSC1 data
  39083. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  39084. return null;
  39085. } // finally, user_data_type_code should be 0x03 for caption data
  39086. if (sei.payload[7] !== 0x03) {
  39087. return null;
  39088. } // return the user_data_type_structure and strip the trailing
  39089. // marker bits
  39090. return sei.payload.subarray(8, sei.payload.length - 1);
  39091. }; // see CEA-708-D, section 4.4
  39092. var parseCaptionPackets = function (pts, userData) {
  39093. var results = [],
  39094. i,
  39095. count,
  39096. offset,
  39097. data; // if this is just filler, return immediately
  39098. if (!(userData[0] & 0x40)) {
  39099. return results;
  39100. } // parse out the cc_data_1 and cc_data_2 fields
  39101. count = userData[0] & 0x1f;
  39102. for (i = 0; i < count; i++) {
  39103. offset = i * 3;
  39104. data = {
  39105. type: userData[offset + 2] & 0x03,
  39106. pts: pts
  39107. }; // capture cc data when cc_valid is 1
  39108. if (userData[offset + 2] & 0x04) {
  39109. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  39110. results.push(data);
  39111. }
  39112. }
  39113. return results;
  39114. };
  39115. var discardEmulationPreventionBytes$1 = function (data) {
  39116. var length = data.byteLength,
  39117. emulationPreventionBytesPositions = [],
  39118. i = 1,
  39119. newLength,
  39120. newData; // Find all `Emulation Prevention Bytes`
  39121. while (i < length - 2) {
  39122. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  39123. emulationPreventionBytesPositions.push(i + 2);
  39124. i += 2;
  39125. } else {
  39126. i++;
  39127. }
  39128. } // If no Emulation Prevention Bytes were found just return the original
  39129. // array
  39130. if (emulationPreventionBytesPositions.length === 0) {
  39131. return data;
  39132. } // Create a new array to hold the NAL unit data
  39133. newLength = length - emulationPreventionBytesPositions.length;
  39134. newData = new Uint8Array(newLength);
  39135. var sourceIndex = 0;
  39136. for (i = 0; i < newLength; sourceIndex++, i++) {
  39137. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  39138. // Skip this byte
  39139. sourceIndex++; // Remove this position index
  39140. emulationPreventionBytesPositions.shift();
  39141. }
  39142. newData[i] = data[sourceIndex];
  39143. }
  39144. return newData;
  39145. }; // exports
  39146. var captionPacketParser = {
  39147. parseSei: parseSei,
  39148. parseUserData: parseUserData,
  39149. parseCaptionPackets: parseCaptionPackets,
  39150. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  39151. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  39152. };
  39153. /**
  39154. * mux.js
  39155. *
  39156. * Copyright (c) Brightcove
  39157. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  39158. *
  39159. * Reads in-band caption information from a video elementary
  39160. * stream. Captions must follow the CEA-708 standard for injection
  39161. * into an MPEG-2 transport streams.
  39162. * @see https://en.wikipedia.org/wiki/CEA-708
  39163. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  39164. */
  39165. // Link To Transport
  39166. // -----------------
  39167. var Stream$7 = stream;
  39168. var cea708Parser = captionPacketParser;
  39169. var CaptionStream$2 = function (options) {
  39170. options = options || {};
  39171. CaptionStream$2.prototype.init.call(this); // parse708captions flag, default to true
  39172. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  39173. this.captionPackets_ = [];
  39174. this.ccStreams_ = [new Cea608Stream(0, 0),
  39175. // eslint-disable-line no-use-before-define
  39176. new Cea608Stream(0, 1),
  39177. // eslint-disable-line no-use-before-define
  39178. new Cea608Stream(1, 0),
  39179. // eslint-disable-line no-use-before-define
  39180. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  39181. ];
  39182. if (this.parse708captions_) {
  39183. this.cc708Stream_ = new Cea708Stream({
  39184. captionServices: options.captionServices
  39185. }); // eslint-disable-line no-use-before-define
  39186. }
  39187. this.reset(); // forward data and done events from CCs to this CaptionStream
  39188. this.ccStreams_.forEach(function (cc) {
  39189. cc.on('data', this.trigger.bind(this, 'data'));
  39190. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  39191. cc.on('done', this.trigger.bind(this, 'done'));
  39192. }, this);
  39193. if (this.parse708captions_) {
  39194. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  39195. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  39196. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  39197. }
  39198. };
  39199. CaptionStream$2.prototype = new Stream$7();
  39200. CaptionStream$2.prototype.push = function (event) {
  39201. var sei, userData, newCaptionPackets; // only examine SEI NALs
  39202. if (event.nalUnitType !== 'sei_rbsp') {
  39203. return;
  39204. } // parse the sei
  39205. sei = cea708Parser.parseSei(event.escapedRBSP); // no payload data, skip
  39206. if (!sei.payload) {
  39207. return;
  39208. } // ignore everything but user_data_registered_itu_t_t35
  39209. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  39210. return;
  39211. } // parse out the user data payload
  39212. userData = cea708Parser.parseUserData(sei); // ignore unrecognized userData
  39213. if (!userData) {
  39214. return;
  39215. } // Sometimes, the same segment # will be downloaded twice. To stop the
  39216. // caption data from being processed twice, we track the latest dts we've
  39217. // received and ignore everything with a dts before that. However, since
  39218. // data for a specific dts can be split across packets on either side of
  39219. // a segment boundary, we need to make sure we *don't* ignore the packets
  39220. // from the *next* segment that have dts === this.latestDts_. By constantly
  39221. // tracking the number of packets received with dts === this.latestDts_, we
  39222. // know how many should be ignored once we start receiving duplicates.
  39223. if (event.dts < this.latestDts_) {
  39224. // We've started getting older data, so set the flag.
  39225. this.ignoreNextEqualDts_ = true;
  39226. return;
  39227. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  39228. this.numSameDts_--;
  39229. if (!this.numSameDts_) {
  39230. // We've received the last duplicate packet, time to start processing again
  39231. this.ignoreNextEqualDts_ = false;
  39232. }
  39233. return;
  39234. } // parse out CC data packets and save them for later
  39235. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  39236. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  39237. if (this.latestDts_ !== event.dts) {
  39238. this.numSameDts_ = 0;
  39239. }
  39240. this.numSameDts_++;
  39241. this.latestDts_ = event.dts;
  39242. };
  39243. CaptionStream$2.prototype.flushCCStreams = function (flushType) {
  39244. this.ccStreams_.forEach(function (cc) {
  39245. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  39246. }, this);
  39247. };
  39248. CaptionStream$2.prototype.flushStream = function (flushType) {
  39249. // make sure we actually parsed captions before proceeding
  39250. if (!this.captionPackets_.length) {
  39251. this.flushCCStreams(flushType);
  39252. return;
  39253. } // In Chrome, the Array#sort function is not stable so add a
  39254. // presortIndex that we can use to ensure we get a stable-sort
  39255. this.captionPackets_.forEach(function (elem, idx) {
  39256. elem.presortIndex = idx;
  39257. }); // sort caption byte-pairs based on their PTS values
  39258. this.captionPackets_.sort(function (a, b) {
  39259. if (a.pts === b.pts) {
  39260. return a.presortIndex - b.presortIndex;
  39261. }
  39262. return a.pts - b.pts;
  39263. });
  39264. this.captionPackets_.forEach(function (packet) {
  39265. if (packet.type < 2) {
  39266. // Dispatch packet to the right Cea608Stream
  39267. this.dispatchCea608Packet(packet);
  39268. } else {
  39269. // Dispatch packet to the Cea708Stream
  39270. this.dispatchCea708Packet(packet);
  39271. }
  39272. }, this);
  39273. this.captionPackets_.length = 0;
  39274. this.flushCCStreams(flushType);
  39275. };
  39276. CaptionStream$2.prototype.flush = function () {
  39277. return this.flushStream('flush');
  39278. }; // Only called if handling partial data
  39279. CaptionStream$2.prototype.partialFlush = function () {
  39280. return this.flushStream('partialFlush');
  39281. };
  39282. CaptionStream$2.prototype.reset = function () {
  39283. this.latestDts_ = null;
  39284. this.ignoreNextEqualDts_ = false;
  39285. this.numSameDts_ = 0;
  39286. this.activeCea608Channel_ = [null, null];
  39287. this.ccStreams_.forEach(function (ccStream) {
  39288. ccStream.reset();
  39289. });
  39290. }; // From the CEA-608 spec:
  39291. /*
  39292. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  39293. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  39294. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  39295. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  39296. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  39297. * to switch to captioning or Text.
  39298. */
  39299. // With that in mind, we ignore any data between an XDS control code and a
  39300. // subsequent closed-captioning control code.
  39301. CaptionStream$2.prototype.dispatchCea608Packet = function (packet) {
  39302. // NOTE: packet.type is the CEA608 field
  39303. if (this.setsTextOrXDSActive(packet)) {
  39304. this.activeCea608Channel_[packet.type] = null;
  39305. } else if (this.setsChannel1Active(packet)) {
  39306. this.activeCea608Channel_[packet.type] = 0;
  39307. } else if (this.setsChannel2Active(packet)) {
  39308. this.activeCea608Channel_[packet.type] = 1;
  39309. }
  39310. if (this.activeCea608Channel_[packet.type] === null) {
  39311. // If we haven't received anything to set the active channel, or the
  39312. // packets are Text/XDS data, discard the data; we don't want jumbled
  39313. // captions
  39314. return;
  39315. }
  39316. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  39317. };
  39318. CaptionStream$2.prototype.setsChannel1Active = function (packet) {
  39319. return (packet.ccData & 0x7800) === 0x1000;
  39320. };
  39321. CaptionStream$2.prototype.setsChannel2Active = function (packet) {
  39322. return (packet.ccData & 0x7800) === 0x1800;
  39323. };
  39324. CaptionStream$2.prototype.setsTextOrXDSActive = function (packet) {
  39325. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  39326. };
  39327. CaptionStream$2.prototype.dispatchCea708Packet = function (packet) {
  39328. if (this.parse708captions_) {
  39329. this.cc708Stream_.push(packet);
  39330. }
  39331. }; // ----------------------
  39332. // Session to Application
  39333. // ----------------------
  39334. // This hash maps special and extended character codes to their
  39335. // proper Unicode equivalent. The first one-byte key is just a
  39336. // non-standard character code. The two-byte keys that follow are
  39337. // the extended CEA708 character codes, along with the preceding
  39338. // 0x10 extended character byte to distinguish these codes from
  39339. // non-extended character codes. Every CEA708 character code that
  39340. // is not in this object maps directly to a standard unicode
  39341. // character code.
  39342. // The transparent space and non-breaking transparent space are
  39343. // technically not fully supported since there is no code to
  39344. // make them transparent, so they have normal non-transparent
  39345. // stand-ins.
  39346. // The special closed caption (CC) character isn't a standard
  39347. // unicode character, so a fairly similar unicode character was
  39348. // chosen in it's place.
  39349. var CHARACTER_TRANSLATION_708 = {
  39350. 0x7f: 0x266a,
  39351. // ♪
  39352. 0x1020: 0x20,
  39353. // Transparent Space
  39354. 0x1021: 0xa0,
  39355. // Nob-breaking Transparent Space
  39356. 0x1025: 0x2026,
  39357. // …
  39358. 0x102a: 0x0160,
  39359. // Š
  39360. 0x102c: 0x0152,
  39361. // Œ
  39362. 0x1030: 0x2588,
  39363. // █
  39364. 0x1031: 0x2018,
  39365. // ‘
  39366. 0x1032: 0x2019,
  39367. // ’
  39368. 0x1033: 0x201c,
  39369. // “
  39370. 0x1034: 0x201d,
  39371. // ”
  39372. 0x1035: 0x2022,
  39373. // •
  39374. 0x1039: 0x2122,
  39375. // ™
  39376. 0x103a: 0x0161,
  39377. // š
  39378. 0x103c: 0x0153,
  39379. // œ
  39380. 0x103d: 0x2120,
  39381. // ℠
  39382. 0x103f: 0x0178,
  39383. // Ÿ
  39384. 0x1076: 0x215b,
  39385. // ⅛
  39386. 0x1077: 0x215c,
  39387. // ⅜
  39388. 0x1078: 0x215d,
  39389. // ⅝
  39390. 0x1079: 0x215e,
  39391. // ⅞
  39392. 0x107a: 0x23d0,
  39393. // ⏐
  39394. 0x107b: 0x23a4,
  39395. // ⎤
  39396. 0x107c: 0x23a3,
  39397. // ⎣
  39398. 0x107d: 0x23af,
  39399. // ⎯
  39400. 0x107e: 0x23a6,
  39401. // ⎦
  39402. 0x107f: 0x23a1,
  39403. // ⎡
  39404. 0x10a0: 0x3138 // ㄸ (CC char)
  39405. };
  39406. var get708CharFromCode = function (code) {
  39407. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  39408. if (code & 0x1000 && code === newCode) {
  39409. // Invalid extended code
  39410. return '';
  39411. }
  39412. return String.fromCharCode(newCode);
  39413. };
  39414. var within708TextBlock = function (b) {
  39415. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  39416. };
  39417. var Cea708Window = function (windowNum) {
  39418. this.windowNum = windowNum;
  39419. this.reset();
  39420. };
  39421. Cea708Window.prototype.reset = function () {
  39422. this.clearText();
  39423. this.pendingNewLine = false;
  39424. this.winAttr = {};
  39425. this.penAttr = {};
  39426. this.penLoc = {};
  39427. this.penColor = {}; // These default values are arbitrary,
  39428. // defineWindow will usually override them
  39429. this.visible = 0;
  39430. this.rowLock = 0;
  39431. this.columnLock = 0;
  39432. this.priority = 0;
  39433. this.relativePositioning = 0;
  39434. this.anchorVertical = 0;
  39435. this.anchorHorizontal = 0;
  39436. this.anchorPoint = 0;
  39437. this.rowCount = 1;
  39438. this.virtualRowCount = this.rowCount + 1;
  39439. this.columnCount = 41;
  39440. this.windowStyle = 0;
  39441. this.penStyle = 0;
  39442. };
  39443. Cea708Window.prototype.getText = function () {
  39444. return this.rows.join('\n');
  39445. };
  39446. Cea708Window.prototype.clearText = function () {
  39447. this.rows = [''];
  39448. this.rowIdx = 0;
  39449. };
  39450. Cea708Window.prototype.newLine = function (pts) {
  39451. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  39452. this.beforeRowOverflow(pts);
  39453. }
  39454. if (this.rows.length > 0) {
  39455. this.rows.push('');
  39456. this.rowIdx++;
  39457. } // Show all virtual rows since there's no visible scrolling
  39458. while (this.rows.length > this.virtualRowCount) {
  39459. this.rows.shift();
  39460. this.rowIdx--;
  39461. }
  39462. };
  39463. Cea708Window.prototype.isEmpty = function () {
  39464. if (this.rows.length === 0) {
  39465. return true;
  39466. } else if (this.rows.length === 1) {
  39467. return this.rows[0] === '';
  39468. }
  39469. return false;
  39470. };
  39471. Cea708Window.prototype.addText = function (text) {
  39472. this.rows[this.rowIdx] += text;
  39473. };
  39474. Cea708Window.prototype.backspace = function () {
  39475. if (!this.isEmpty()) {
  39476. var row = this.rows[this.rowIdx];
  39477. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  39478. }
  39479. };
  39480. var Cea708Service = function (serviceNum, encoding, stream) {
  39481. this.serviceNum = serviceNum;
  39482. this.text = '';
  39483. this.currentWindow = new Cea708Window(-1);
  39484. this.windows = [];
  39485. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  39486. if (typeof encoding === 'string') {
  39487. this.createTextDecoder(encoding);
  39488. }
  39489. };
  39490. /**
  39491. * Initialize service windows
  39492. * Must be run before service use
  39493. *
  39494. * @param {Integer} pts PTS value
  39495. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  39496. */
  39497. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  39498. this.startPts = pts;
  39499. for (var win = 0; win < 8; win++) {
  39500. this.windows[win] = new Cea708Window(win);
  39501. if (typeof beforeRowOverflow === 'function') {
  39502. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  39503. }
  39504. }
  39505. };
  39506. /**
  39507. * Set current window of service to be affected by commands
  39508. *
  39509. * @param {Integer} windowNum Window number
  39510. */
  39511. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  39512. this.currentWindow = this.windows[windowNum];
  39513. };
  39514. /**
  39515. * Try to create a TextDecoder if it is natively supported
  39516. */
  39517. Cea708Service.prototype.createTextDecoder = function (encoding) {
  39518. if (typeof TextDecoder === 'undefined') {
  39519. this.stream.trigger('log', {
  39520. level: 'warn',
  39521. message: 'The `encoding` option is unsupported without TextDecoder support'
  39522. });
  39523. } else {
  39524. try {
  39525. this.textDecoder_ = new TextDecoder(encoding);
  39526. } catch (error) {
  39527. this.stream.trigger('log', {
  39528. level: 'warn',
  39529. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  39530. });
  39531. }
  39532. }
  39533. };
  39534. var Cea708Stream = function (options) {
  39535. options = options || {};
  39536. Cea708Stream.prototype.init.call(this);
  39537. var self = this;
  39538. var captionServices = options.captionServices || {};
  39539. var captionServiceEncodings = {};
  39540. var serviceProps; // Get service encodings from captionServices option block
  39541. Object.keys(captionServices).forEach(serviceName => {
  39542. serviceProps = captionServices[serviceName];
  39543. if (/^SERVICE/.test(serviceName)) {
  39544. captionServiceEncodings[serviceName] = serviceProps.encoding;
  39545. }
  39546. });
  39547. this.serviceEncodings = captionServiceEncodings;
  39548. this.current708Packet = null;
  39549. this.services = {};
  39550. this.push = function (packet) {
  39551. if (packet.type === 3) {
  39552. // 708 packet start
  39553. self.new708Packet();
  39554. self.add708Bytes(packet);
  39555. } else {
  39556. if (self.current708Packet === null) {
  39557. // This should only happen at the start of a file if there's no packet start.
  39558. self.new708Packet();
  39559. }
  39560. self.add708Bytes(packet);
  39561. }
  39562. };
  39563. };
  39564. Cea708Stream.prototype = new Stream$7();
  39565. /**
  39566. * Push current 708 packet, create new 708 packet.
  39567. */
  39568. Cea708Stream.prototype.new708Packet = function () {
  39569. if (this.current708Packet !== null) {
  39570. this.push708Packet();
  39571. }
  39572. this.current708Packet = {
  39573. data: [],
  39574. ptsVals: []
  39575. };
  39576. };
  39577. /**
  39578. * Add pts and both bytes from packet into current 708 packet.
  39579. */
  39580. Cea708Stream.prototype.add708Bytes = function (packet) {
  39581. var data = packet.ccData;
  39582. var byte0 = data >>> 8;
  39583. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  39584. // that service blocks will always line up with byte pairs.
  39585. this.current708Packet.ptsVals.push(packet.pts);
  39586. this.current708Packet.data.push(byte0);
  39587. this.current708Packet.data.push(byte1);
  39588. };
  39589. /**
  39590. * Parse completed 708 packet into service blocks and push each service block.
  39591. */
  39592. Cea708Stream.prototype.push708Packet = function () {
  39593. var packet708 = this.current708Packet;
  39594. var packetData = packet708.data;
  39595. var serviceNum = null;
  39596. var blockSize = null;
  39597. var i = 0;
  39598. var b = packetData[i++];
  39599. packet708.seq = b >> 6;
  39600. packet708.sizeCode = b & 0x3f; // 0b00111111;
  39601. for (; i < packetData.length; i++) {
  39602. b = packetData[i++];
  39603. serviceNum = b >> 5;
  39604. blockSize = b & 0x1f; // 0b00011111
  39605. if (serviceNum === 7 && blockSize > 0) {
  39606. // Extended service num
  39607. b = packetData[i++];
  39608. serviceNum = b;
  39609. }
  39610. this.pushServiceBlock(serviceNum, i, blockSize);
  39611. if (blockSize > 0) {
  39612. i += blockSize - 1;
  39613. }
  39614. }
  39615. };
  39616. /**
  39617. * Parse service block, execute commands, read text.
  39618. *
  39619. * Note: While many of these commands serve important purposes,
  39620. * many others just parse out the parameters or attributes, but
  39621. * nothing is done with them because this is not a full and complete
  39622. * implementation of the entire 708 spec.
  39623. *
  39624. * @param {Integer} serviceNum Service number
  39625. * @param {Integer} start Start index of the 708 packet data
  39626. * @param {Integer} size Block size
  39627. */
  39628. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  39629. var b;
  39630. var i = start;
  39631. var packetData = this.current708Packet.data;
  39632. var service = this.services[serviceNum];
  39633. if (!service) {
  39634. service = this.initService(serviceNum, i);
  39635. }
  39636. for (; i < start + size && i < packetData.length; i++) {
  39637. b = packetData[i];
  39638. if (within708TextBlock(b)) {
  39639. i = this.handleText(i, service);
  39640. } else if (b === 0x18) {
  39641. i = this.multiByteCharacter(i, service);
  39642. } else if (b === 0x10) {
  39643. i = this.extendedCommands(i, service);
  39644. } else if (0x80 <= b && b <= 0x87) {
  39645. i = this.setCurrentWindow(i, service);
  39646. } else if (0x98 <= b && b <= 0x9f) {
  39647. i = this.defineWindow(i, service);
  39648. } else if (b === 0x88) {
  39649. i = this.clearWindows(i, service);
  39650. } else if (b === 0x8c) {
  39651. i = this.deleteWindows(i, service);
  39652. } else if (b === 0x89) {
  39653. i = this.displayWindows(i, service);
  39654. } else if (b === 0x8a) {
  39655. i = this.hideWindows(i, service);
  39656. } else if (b === 0x8b) {
  39657. i = this.toggleWindows(i, service);
  39658. } else if (b === 0x97) {
  39659. i = this.setWindowAttributes(i, service);
  39660. } else if (b === 0x90) {
  39661. i = this.setPenAttributes(i, service);
  39662. } else if (b === 0x91) {
  39663. i = this.setPenColor(i, service);
  39664. } else if (b === 0x92) {
  39665. i = this.setPenLocation(i, service);
  39666. } else if (b === 0x8f) {
  39667. service = this.reset(i, service);
  39668. } else if (b === 0x08) {
  39669. // BS: Backspace
  39670. service.currentWindow.backspace();
  39671. } else if (b === 0x0c) {
  39672. // FF: Form feed
  39673. service.currentWindow.clearText();
  39674. } else if (b === 0x0d) {
  39675. // CR: Carriage return
  39676. service.currentWindow.pendingNewLine = true;
  39677. } else if (b === 0x0e) {
  39678. // HCR: Horizontal carriage return
  39679. service.currentWindow.clearText();
  39680. } else if (b === 0x8d) {
  39681. // DLY: Delay, nothing to do
  39682. i++;
  39683. } else ;
  39684. }
  39685. };
  39686. /**
  39687. * Execute an extended command
  39688. *
  39689. * @param {Integer} i Current index in the 708 packet
  39690. * @param {Service} service The service object to be affected
  39691. * @return {Integer} New index after parsing
  39692. */
  39693. Cea708Stream.prototype.extendedCommands = function (i, service) {
  39694. var packetData = this.current708Packet.data;
  39695. var b = packetData[++i];
  39696. if (within708TextBlock(b)) {
  39697. i = this.handleText(i, service, {
  39698. isExtended: true
  39699. });
  39700. }
  39701. return i;
  39702. };
  39703. /**
  39704. * Get PTS value of a given byte index
  39705. *
  39706. * @param {Integer} byteIndex Index of the byte
  39707. * @return {Integer} PTS
  39708. */
  39709. Cea708Stream.prototype.getPts = function (byteIndex) {
  39710. // There's 1 pts value per 2 bytes
  39711. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  39712. };
  39713. /**
  39714. * Initializes a service
  39715. *
  39716. * @param {Integer} serviceNum Service number
  39717. * @return {Service} Initialized service object
  39718. */
  39719. Cea708Stream.prototype.initService = function (serviceNum, i) {
  39720. var serviceName = 'SERVICE' + serviceNum;
  39721. var self = this;
  39722. var serviceName;
  39723. var encoding;
  39724. if (serviceName in this.serviceEncodings) {
  39725. encoding = this.serviceEncodings[serviceName];
  39726. }
  39727. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  39728. this.services[serviceNum].init(this.getPts(i), function (pts) {
  39729. self.flushDisplayed(pts, self.services[serviceNum]);
  39730. });
  39731. return this.services[serviceNum];
  39732. };
  39733. /**
  39734. * Execute text writing to current window
  39735. *
  39736. * @param {Integer} i Current index in the 708 packet
  39737. * @param {Service} service The service object to be affected
  39738. * @return {Integer} New index after parsing
  39739. */
  39740. Cea708Stream.prototype.handleText = function (i, service, options) {
  39741. var isExtended = options && options.isExtended;
  39742. var isMultiByte = options && options.isMultiByte;
  39743. var packetData = this.current708Packet.data;
  39744. var extended = isExtended ? 0x1000 : 0x0000;
  39745. var currentByte = packetData[i];
  39746. var nextByte = packetData[i + 1];
  39747. var win = service.currentWindow;
  39748. var char;
  39749. var charCodeArray; // Use the TextDecoder if one was created for this service
  39750. if (service.textDecoder_ && !isExtended) {
  39751. if (isMultiByte) {
  39752. charCodeArray = [currentByte, nextByte];
  39753. i++;
  39754. } else {
  39755. charCodeArray = [currentByte];
  39756. }
  39757. char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  39758. } else {
  39759. char = get708CharFromCode(extended | currentByte);
  39760. }
  39761. if (win.pendingNewLine && !win.isEmpty()) {
  39762. win.newLine(this.getPts(i));
  39763. }
  39764. win.pendingNewLine = false;
  39765. win.addText(char);
  39766. return i;
  39767. };
  39768. /**
  39769. * Handle decoding of multibyte character
  39770. *
  39771. * @param {Integer} i Current index in the 708 packet
  39772. * @param {Service} service The service object to be affected
  39773. * @return {Integer} New index after parsing
  39774. */
  39775. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  39776. var packetData = this.current708Packet.data;
  39777. var firstByte = packetData[i + 1];
  39778. var secondByte = packetData[i + 2];
  39779. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  39780. i = this.handleText(++i, service, {
  39781. isMultiByte: true
  39782. });
  39783. }
  39784. return i;
  39785. };
  39786. /**
  39787. * Parse and execute the CW# command.
  39788. *
  39789. * Set the current window.
  39790. *
  39791. * @param {Integer} i Current index in the 708 packet
  39792. * @param {Service} service The service object to be affected
  39793. * @return {Integer} New index after parsing
  39794. */
  39795. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  39796. var packetData = this.current708Packet.data;
  39797. var b = packetData[i];
  39798. var windowNum = b & 0x07;
  39799. service.setCurrentWindow(windowNum);
  39800. return i;
  39801. };
  39802. /**
  39803. * Parse and execute the DF# command.
  39804. *
  39805. * Define a window and set it as the current window.
  39806. *
  39807. * @param {Integer} i Current index in the 708 packet
  39808. * @param {Service} service The service object to be affected
  39809. * @return {Integer} New index after parsing
  39810. */
  39811. Cea708Stream.prototype.defineWindow = function (i, service) {
  39812. var packetData = this.current708Packet.data;
  39813. var b = packetData[i];
  39814. var windowNum = b & 0x07;
  39815. service.setCurrentWindow(windowNum);
  39816. var win = service.currentWindow;
  39817. b = packetData[++i];
  39818. win.visible = (b & 0x20) >> 5; // v
  39819. win.rowLock = (b & 0x10) >> 4; // rl
  39820. win.columnLock = (b & 0x08) >> 3; // cl
  39821. win.priority = b & 0x07; // p
  39822. b = packetData[++i];
  39823. win.relativePositioning = (b & 0x80) >> 7; // rp
  39824. win.anchorVertical = b & 0x7f; // av
  39825. b = packetData[++i];
  39826. win.anchorHorizontal = b; // ah
  39827. b = packetData[++i];
  39828. win.anchorPoint = (b & 0xf0) >> 4; // ap
  39829. win.rowCount = b & 0x0f; // rc
  39830. b = packetData[++i];
  39831. win.columnCount = b & 0x3f; // cc
  39832. b = packetData[++i];
  39833. win.windowStyle = (b & 0x38) >> 3; // ws
  39834. win.penStyle = b & 0x07; // ps
  39835. // The spec says there are (rowCount+1) "virtual rows"
  39836. win.virtualRowCount = win.rowCount + 1;
  39837. return i;
  39838. };
  39839. /**
  39840. * Parse and execute the SWA command.
  39841. *
  39842. * Set attributes of the current window.
  39843. *
  39844. * @param {Integer} i Current index in the 708 packet
  39845. * @param {Service} service The service object to be affected
  39846. * @return {Integer} New index after parsing
  39847. */
  39848. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  39849. var packetData = this.current708Packet.data;
  39850. var b = packetData[i];
  39851. var winAttr = service.currentWindow.winAttr;
  39852. b = packetData[++i];
  39853. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  39854. winAttr.fillRed = (b & 0x30) >> 4; // fr
  39855. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  39856. winAttr.fillBlue = b & 0x03; // fb
  39857. b = packetData[++i];
  39858. winAttr.borderType = (b & 0xc0) >> 6; // bt
  39859. winAttr.borderRed = (b & 0x30) >> 4; // br
  39860. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  39861. winAttr.borderBlue = b & 0x03; // bb
  39862. b = packetData[++i];
  39863. winAttr.borderType += (b & 0x80) >> 5; // bt
  39864. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  39865. winAttr.printDirection = (b & 0x30) >> 4; // pd
  39866. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  39867. winAttr.justify = b & 0x03; // j
  39868. b = packetData[++i];
  39869. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  39870. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  39871. winAttr.displayEffect = b & 0x03; // de
  39872. return i;
  39873. };
  39874. /**
  39875. * Gather text from all displayed windows and push a caption to output.
  39876. *
  39877. * @param {Integer} i Current index in the 708 packet
  39878. * @param {Service} service The service object to be affected
  39879. */
  39880. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  39881. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  39882. // display text in the correct order, but sample files so far have not shown any issue.
  39883. for (var winId = 0; winId < 8; winId++) {
  39884. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  39885. displayedText.push(service.windows[winId].getText());
  39886. }
  39887. }
  39888. service.endPts = pts;
  39889. service.text = displayedText.join('\n\n');
  39890. this.pushCaption(service);
  39891. service.startPts = pts;
  39892. };
  39893. /**
  39894. * Push a caption to output if the caption contains text.
  39895. *
  39896. * @param {Service} service The service object to be affected
  39897. */
  39898. Cea708Stream.prototype.pushCaption = function (service) {
  39899. if (service.text !== '') {
  39900. this.trigger('data', {
  39901. startPts: service.startPts,
  39902. endPts: service.endPts,
  39903. text: service.text,
  39904. stream: 'cc708_' + service.serviceNum
  39905. });
  39906. service.text = '';
  39907. service.startPts = service.endPts;
  39908. }
  39909. };
  39910. /**
  39911. * Parse and execute the DSW command.
  39912. *
  39913. * Set visible property of windows based on the parsed bitmask.
  39914. *
  39915. * @param {Integer} i Current index in the 708 packet
  39916. * @param {Service} service The service object to be affected
  39917. * @return {Integer} New index after parsing
  39918. */
  39919. Cea708Stream.prototype.displayWindows = function (i, service) {
  39920. var packetData = this.current708Packet.data;
  39921. var b = packetData[++i];
  39922. var pts = this.getPts(i);
  39923. this.flushDisplayed(pts, service);
  39924. for (var winId = 0; winId < 8; winId++) {
  39925. if (b & 0x01 << winId) {
  39926. service.windows[winId].visible = 1;
  39927. }
  39928. }
  39929. return i;
  39930. };
  39931. /**
  39932. * Parse and execute the HDW command.
  39933. *
  39934. * Set visible property of windows based on the parsed bitmask.
  39935. *
  39936. * @param {Integer} i Current index in the 708 packet
  39937. * @param {Service} service The service object to be affected
  39938. * @return {Integer} New index after parsing
  39939. */
  39940. Cea708Stream.prototype.hideWindows = function (i, service) {
  39941. var packetData = this.current708Packet.data;
  39942. var b = packetData[++i];
  39943. var pts = this.getPts(i);
  39944. this.flushDisplayed(pts, service);
  39945. for (var winId = 0; winId < 8; winId++) {
  39946. if (b & 0x01 << winId) {
  39947. service.windows[winId].visible = 0;
  39948. }
  39949. }
  39950. return i;
  39951. };
  39952. /**
  39953. * Parse and execute the TGW command.
  39954. *
  39955. * Set visible property of windows based on the parsed bitmask.
  39956. *
  39957. * @param {Integer} i Current index in the 708 packet
  39958. * @param {Service} service The service object to be affected
  39959. * @return {Integer} New index after parsing
  39960. */
  39961. Cea708Stream.prototype.toggleWindows = function (i, service) {
  39962. var packetData = this.current708Packet.data;
  39963. var b = packetData[++i];
  39964. var pts = this.getPts(i);
  39965. this.flushDisplayed(pts, service);
  39966. for (var winId = 0; winId < 8; winId++) {
  39967. if (b & 0x01 << winId) {
  39968. service.windows[winId].visible ^= 1;
  39969. }
  39970. }
  39971. return i;
  39972. };
  39973. /**
  39974. * Parse and execute the CLW command.
  39975. *
  39976. * Clear text of windows based on the parsed bitmask.
  39977. *
  39978. * @param {Integer} i Current index in the 708 packet
  39979. * @param {Service} service The service object to be affected
  39980. * @return {Integer} New index after parsing
  39981. */
  39982. Cea708Stream.prototype.clearWindows = function (i, service) {
  39983. var packetData = this.current708Packet.data;
  39984. var b = packetData[++i];
  39985. var pts = this.getPts(i);
  39986. this.flushDisplayed(pts, service);
  39987. for (var winId = 0; winId < 8; winId++) {
  39988. if (b & 0x01 << winId) {
  39989. service.windows[winId].clearText();
  39990. }
  39991. }
  39992. return i;
  39993. };
  39994. /**
  39995. * Parse and execute the DLW command.
  39996. *
  39997. * Re-initialize windows based on the parsed bitmask.
  39998. *
  39999. * @param {Integer} i Current index in the 708 packet
  40000. * @param {Service} service The service object to be affected
  40001. * @return {Integer} New index after parsing
  40002. */
  40003. Cea708Stream.prototype.deleteWindows = function (i, service) {
  40004. var packetData = this.current708Packet.data;
  40005. var b = packetData[++i];
  40006. var pts = this.getPts(i);
  40007. this.flushDisplayed(pts, service);
  40008. for (var winId = 0; winId < 8; winId++) {
  40009. if (b & 0x01 << winId) {
  40010. service.windows[winId].reset();
  40011. }
  40012. }
  40013. return i;
  40014. };
  40015. /**
  40016. * Parse and execute the SPA command.
  40017. *
  40018. * Set pen attributes of the current window.
  40019. *
  40020. * @param {Integer} i Current index in the 708 packet
  40021. * @param {Service} service The service object to be affected
  40022. * @return {Integer} New index after parsing
  40023. */
  40024. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  40025. var packetData = this.current708Packet.data;
  40026. var b = packetData[i];
  40027. var penAttr = service.currentWindow.penAttr;
  40028. b = packetData[++i];
  40029. penAttr.textTag = (b & 0xf0) >> 4; // tt
  40030. penAttr.offset = (b & 0x0c) >> 2; // o
  40031. penAttr.penSize = b & 0x03; // s
  40032. b = packetData[++i];
  40033. penAttr.italics = (b & 0x80) >> 7; // i
  40034. penAttr.underline = (b & 0x40) >> 6; // u
  40035. penAttr.edgeType = (b & 0x38) >> 3; // et
  40036. penAttr.fontStyle = b & 0x07; // fs
  40037. return i;
  40038. };
  40039. /**
  40040. * Parse and execute the SPC command.
  40041. *
  40042. * Set pen color of the current window.
  40043. *
  40044. * @param {Integer} i Current index in the 708 packet
  40045. * @param {Service} service The service object to be affected
  40046. * @return {Integer} New index after parsing
  40047. */
  40048. Cea708Stream.prototype.setPenColor = function (i, service) {
  40049. var packetData = this.current708Packet.data;
  40050. var b = packetData[i];
  40051. var penColor = service.currentWindow.penColor;
  40052. b = packetData[++i];
  40053. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  40054. penColor.fgRed = (b & 0x30) >> 4; // fr
  40055. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  40056. penColor.fgBlue = b & 0x03; // fb
  40057. b = packetData[++i];
  40058. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  40059. penColor.bgRed = (b & 0x30) >> 4; // br
  40060. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  40061. penColor.bgBlue = b & 0x03; // bb
  40062. b = packetData[++i];
  40063. penColor.edgeRed = (b & 0x30) >> 4; // er
  40064. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  40065. penColor.edgeBlue = b & 0x03; // eb
  40066. return i;
  40067. };
  40068. /**
  40069. * Parse and execute the SPL command.
  40070. *
  40071. * Set pen location of the current window.
  40072. *
  40073. * @param {Integer} i Current index in the 708 packet
  40074. * @param {Service} service The service object to be affected
  40075. * @return {Integer} New index after parsing
  40076. */
  40077. Cea708Stream.prototype.setPenLocation = function (i, service) {
  40078. var packetData = this.current708Packet.data;
  40079. var b = packetData[i];
  40080. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  40081. service.currentWindow.pendingNewLine = true;
  40082. b = packetData[++i];
  40083. penLoc.row = b & 0x0f; // r
  40084. b = packetData[++i];
  40085. penLoc.column = b & 0x3f; // c
  40086. return i;
  40087. };
  40088. /**
  40089. * Execute the RST command.
  40090. *
  40091. * Reset service to a clean slate. Re-initialize.
  40092. *
  40093. * @param {Integer} i Current index in the 708 packet
  40094. * @param {Service} service The service object to be affected
  40095. * @return {Service} Re-initialized service
  40096. */
  40097. Cea708Stream.prototype.reset = function (i, service) {
  40098. var pts = this.getPts(i);
  40099. this.flushDisplayed(pts, service);
  40100. return this.initService(service.serviceNum, i);
  40101. }; // This hash maps non-ASCII, special, and extended character codes to their
  40102. // proper Unicode equivalent. The first keys that are only a single byte
  40103. // are the non-standard ASCII characters, which simply map the CEA608 byte
  40104. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  40105. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  40106. // can be performed regardless of the field and data channel on which the
  40107. // character code was received.
  40108. var CHARACTER_TRANSLATION = {
  40109. 0x2a: 0xe1,
  40110. // á
  40111. 0x5c: 0xe9,
  40112. // é
  40113. 0x5e: 0xed,
  40114. // í
  40115. 0x5f: 0xf3,
  40116. // ó
  40117. 0x60: 0xfa,
  40118. // ú
  40119. 0x7b: 0xe7,
  40120. // ç
  40121. 0x7c: 0xf7,
  40122. // ÷
  40123. 0x7d: 0xd1,
  40124. // Ñ
  40125. 0x7e: 0xf1,
  40126. // ñ
  40127. 0x7f: 0x2588,
  40128. // █
  40129. 0x0130: 0xae,
  40130. // ®
  40131. 0x0131: 0xb0,
  40132. // °
  40133. 0x0132: 0xbd,
  40134. // ½
  40135. 0x0133: 0xbf,
  40136. // ¿
  40137. 0x0134: 0x2122,
  40138. // ™
  40139. 0x0135: 0xa2,
  40140. // ¢
  40141. 0x0136: 0xa3,
  40142. // £
  40143. 0x0137: 0x266a,
  40144. // ♪
  40145. 0x0138: 0xe0,
  40146. // à
  40147. 0x0139: 0xa0,
  40148. //
  40149. 0x013a: 0xe8,
  40150. // è
  40151. 0x013b: 0xe2,
  40152. // â
  40153. 0x013c: 0xea,
  40154. // ê
  40155. 0x013d: 0xee,
  40156. // î
  40157. 0x013e: 0xf4,
  40158. // ô
  40159. 0x013f: 0xfb,
  40160. // û
  40161. 0x0220: 0xc1,
  40162. // Á
  40163. 0x0221: 0xc9,
  40164. // É
  40165. 0x0222: 0xd3,
  40166. // Ó
  40167. 0x0223: 0xda,
  40168. // Ú
  40169. 0x0224: 0xdc,
  40170. // Ü
  40171. 0x0225: 0xfc,
  40172. // ü
  40173. 0x0226: 0x2018,
  40174. // ‘
  40175. 0x0227: 0xa1,
  40176. // ¡
  40177. 0x0228: 0x2a,
  40178. // *
  40179. 0x0229: 0x27,
  40180. // '
  40181. 0x022a: 0x2014,
  40182. // —
  40183. 0x022b: 0xa9,
  40184. // ©
  40185. 0x022c: 0x2120,
  40186. // ℠
  40187. 0x022d: 0x2022,
  40188. // •
  40189. 0x022e: 0x201c,
  40190. // “
  40191. 0x022f: 0x201d,
  40192. // ”
  40193. 0x0230: 0xc0,
  40194. // À
  40195. 0x0231: 0xc2,
  40196. // Â
  40197. 0x0232: 0xc7,
  40198. // Ç
  40199. 0x0233: 0xc8,
  40200. // È
  40201. 0x0234: 0xca,
  40202. // Ê
  40203. 0x0235: 0xcb,
  40204. // Ë
  40205. 0x0236: 0xeb,
  40206. // ë
  40207. 0x0237: 0xce,
  40208. // Î
  40209. 0x0238: 0xcf,
  40210. // Ï
  40211. 0x0239: 0xef,
  40212. // ï
  40213. 0x023a: 0xd4,
  40214. // Ô
  40215. 0x023b: 0xd9,
  40216. // Ù
  40217. 0x023c: 0xf9,
  40218. // ù
  40219. 0x023d: 0xdb,
  40220. // Û
  40221. 0x023e: 0xab,
  40222. // «
  40223. 0x023f: 0xbb,
  40224. // »
  40225. 0x0320: 0xc3,
  40226. // Ã
  40227. 0x0321: 0xe3,
  40228. // ã
  40229. 0x0322: 0xcd,
  40230. // Í
  40231. 0x0323: 0xcc,
  40232. // Ì
  40233. 0x0324: 0xec,
  40234. // ì
  40235. 0x0325: 0xd2,
  40236. // Ò
  40237. 0x0326: 0xf2,
  40238. // ò
  40239. 0x0327: 0xd5,
  40240. // Õ
  40241. 0x0328: 0xf5,
  40242. // õ
  40243. 0x0329: 0x7b,
  40244. // {
  40245. 0x032a: 0x7d,
  40246. // }
  40247. 0x032b: 0x5c,
  40248. // \
  40249. 0x032c: 0x5e,
  40250. // ^
  40251. 0x032d: 0x5f,
  40252. // _
  40253. 0x032e: 0x7c,
  40254. // |
  40255. 0x032f: 0x7e,
  40256. // ~
  40257. 0x0330: 0xc4,
  40258. // Ä
  40259. 0x0331: 0xe4,
  40260. // ä
  40261. 0x0332: 0xd6,
  40262. // Ö
  40263. 0x0333: 0xf6,
  40264. // ö
  40265. 0x0334: 0xdf,
  40266. // ß
  40267. 0x0335: 0xa5,
  40268. // ¥
  40269. 0x0336: 0xa4,
  40270. // ¤
  40271. 0x0337: 0x2502,
  40272. // │
  40273. 0x0338: 0xc5,
  40274. // Å
  40275. 0x0339: 0xe5,
  40276. // å
  40277. 0x033a: 0xd8,
  40278. // Ø
  40279. 0x033b: 0xf8,
  40280. // ø
  40281. 0x033c: 0x250c,
  40282. // ┌
  40283. 0x033d: 0x2510,
  40284. // ┐
  40285. 0x033e: 0x2514,
  40286. // └
  40287. 0x033f: 0x2518 // ┘
  40288. };
  40289. var getCharFromCode = function (code) {
  40290. if (code === null) {
  40291. return '';
  40292. }
  40293. code = CHARACTER_TRANSLATION[code] || code;
  40294. return String.fromCharCode(code);
  40295. }; // the index of the last row in a CEA-608 display buffer
  40296. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  40297. // getting it through bit logic.
  40298. 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
  40299. // cells. The "bottom" row is the last element in the outer array.
  40300. var createDisplayBuffer = function () {
  40301. var result = [],
  40302. i = BOTTOM_ROW + 1;
  40303. while (i--) {
  40304. result.push('');
  40305. }
  40306. return result;
  40307. };
  40308. var Cea608Stream = function (field, dataChannel) {
  40309. Cea608Stream.prototype.init.call(this);
  40310. this.field_ = field || 0;
  40311. this.dataChannel_ = dataChannel || 0;
  40312. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  40313. this.setConstants();
  40314. this.reset();
  40315. this.push = function (packet) {
  40316. var data, swap, char0, char1, text; // remove the parity bits
  40317. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  40318. if (data === this.lastControlCode_) {
  40319. this.lastControlCode_ = null;
  40320. return;
  40321. } // Store control codes
  40322. if ((data & 0xf000) === 0x1000) {
  40323. this.lastControlCode_ = data;
  40324. } else if (data !== this.PADDING_) {
  40325. this.lastControlCode_ = null;
  40326. }
  40327. char0 = data >>> 8;
  40328. char1 = data & 0xff;
  40329. if (data === this.PADDING_) {
  40330. return;
  40331. } else if (data === this.RESUME_CAPTION_LOADING_) {
  40332. this.mode_ = 'popOn';
  40333. } else if (data === this.END_OF_CAPTION_) {
  40334. // If an EOC is received while in paint-on mode, the displayed caption
  40335. // text should be swapped to non-displayed memory as if it was a pop-on
  40336. // caption. Because of that, we should explicitly switch back to pop-on
  40337. // mode
  40338. this.mode_ = 'popOn';
  40339. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  40340. this.flushDisplayed(packet.pts); // flip memory
  40341. swap = this.displayed_;
  40342. this.displayed_ = this.nonDisplayed_;
  40343. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  40344. this.startPts_ = packet.pts;
  40345. } else if (data === this.ROLL_UP_2_ROWS_) {
  40346. this.rollUpRows_ = 2;
  40347. this.setRollUp(packet.pts);
  40348. } else if (data === this.ROLL_UP_3_ROWS_) {
  40349. this.rollUpRows_ = 3;
  40350. this.setRollUp(packet.pts);
  40351. } else if (data === this.ROLL_UP_4_ROWS_) {
  40352. this.rollUpRows_ = 4;
  40353. this.setRollUp(packet.pts);
  40354. } else if (data === this.CARRIAGE_RETURN_) {
  40355. this.clearFormatting(packet.pts);
  40356. this.flushDisplayed(packet.pts);
  40357. this.shiftRowsUp_();
  40358. this.startPts_ = packet.pts;
  40359. } else if (data === this.BACKSPACE_) {
  40360. if (this.mode_ === 'popOn') {
  40361. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  40362. } else {
  40363. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  40364. }
  40365. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  40366. this.flushDisplayed(packet.pts);
  40367. this.displayed_ = createDisplayBuffer();
  40368. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  40369. this.nonDisplayed_ = createDisplayBuffer();
  40370. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  40371. if (this.mode_ !== 'paintOn') {
  40372. // NOTE: This should be removed when proper caption positioning is
  40373. // implemented
  40374. this.flushDisplayed(packet.pts);
  40375. this.displayed_ = createDisplayBuffer();
  40376. }
  40377. this.mode_ = 'paintOn';
  40378. this.startPts_ = packet.pts; // Append special characters to caption text
  40379. } else if (this.isSpecialCharacter(char0, char1)) {
  40380. // Bitmask char0 so that we can apply character transformations
  40381. // regardless of field and data channel.
  40382. // Then byte-shift to the left and OR with char1 so we can pass the
  40383. // entire character code to `getCharFromCode`.
  40384. char0 = (char0 & 0x03) << 8;
  40385. text = getCharFromCode(char0 | char1);
  40386. this[this.mode_](packet.pts, text);
  40387. this.column_++; // Append extended characters to caption text
  40388. } else if (this.isExtCharacter(char0, char1)) {
  40389. // Extended characters always follow their "non-extended" equivalents.
  40390. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  40391. // decoders are supposed to drop the "è", while compliant decoders
  40392. // backspace the "e" and insert "è".
  40393. // Delete the previous character
  40394. if (this.mode_ === 'popOn') {
  40395. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  40396. } else {
  40397. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  40398. } // Bitmask char0 so that we can apply character transformations
  40399. // regardless of field and data channel.
  40400. // Then byte-shift to the left and OR with char1 so we can pass the
  40401. // entire character code to `getCharFromCode`.
  40402. char0 = (char0 & 0x03) << 8;
  40403. text = getCharFromCode(char0 | char1);
  40404. this[this.mode_](packet.pts, text);
  40405. this.column_++; // Process mid-row codes
  40406. } else if (this.isMidRowCode(char0, char1)) {
  40407. // Attributes are not additive, so clear all formatting
  40408. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  40409. // should be replaced with spaces, so add one now
  40410. this[this.mode_](packet.pts, ' ');
  40411. this.column_++;
  40412. if ((char1 & 0xe) === 0xe) {
  40413. this.addFormatting(packet.pts, ['i']);
  40414. }
  40415. if ((char1 & 0x1) === 0x1) {
  40416. this.addFormatting(packet.pts, ['u']);
  40417. } // Detect offset control codes and adjust cursor
  40418. } else if (this.isOffsetControlCode(char0, char1)) {
  40419. // Cursor position is set by indent PAC (see below) in 4-column
  40420. // increments, with an additional offset code of 1-3 to reach any
  40421. // of the 32 columns specified by CEA-608. So all we need to do
  40422. // here is increment the column cursor by the given offset.
  40423. this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
  40424. } else if (this.isPAC(char0, char1)) {
  40425. // There's no logic for PAC -> row mapping, so we have to just
  40426. // find the row code in an array and use its index :(
  40427. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  40428. if (this.mode_ === 'rollUp') {
  40429. // This implies that the base row is incorrectly set.
  40430. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  40431. // of roll-up rows set.
  40432. if (row - this.rollUpRows_ + 1 < 0) {
  40433. row = this.rollUpRows_ - 1;
  40434. }
  40435. this.setRollUp(packet.pts, row);
  40436. }
  40437. if (row !== this.row_) {
  40438. // formatting is only persistent for current row
  40439. this.clearFormatting(packet.pts);
  40440. this.row_ = row;
  40441. } // All PACs can apply underline, so detect and apply
  40442. // (All odd-numbered second bytes set underline)
  40443. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  40444. this.addFormatting(packet.pts, ['u']);
  40445. }
  40446. if ((data & 0x10) === 0x10) {
  40447. // We've got an indent level code. Each successive even number
  40448. // increments the column cursor by 4, so we can get the desired
  40449. // column position by bit-shifting to the right (to get n/2)
  40450. // and multiplying by 4.
  40451. this.column_ = ((data & 0xe) >> 1) * 4;
  40452. }
  40453. if (this.isColorPAC(char1)) {
  40454. // it's a color code, though we only support white, which
  40455. // can be either normal or italicized. white italics can be
  40456. // either 0x4e or 0x6e depending on the row, so we just
  40457. // bitwise-and with 0xe to see if italics should be turned on
  40458. if ((char1 & 0xe) === 0xe) {
  40459. this.addFormatting(packet.pts, ['i']);
  40460. }
  40461. } // We have a normal character in char0, and possibly one in char1
  40462. } else if (this.isNormalChar(char0)) {
  40463. if (char1 === 0x00) {
  40464. char1 = null;
  40465. }
  40466. text = getCharFromCode(char0);
  40467. text += getCharFromCode(char1);
  40468. this[this.mode_](packet.pts, text);
  40469. this.column_ += text.length;
  40470. } // finish data processing
  40471. };
  40472. };
  40473. Cea608Stream.prototype = new Stream$7(); // Trigger a cue point that captures the current state of the
  40474. // display buffer
  40475. Cea608Stream.prototype.flushDisplayed = function (pts) {
  40476. var content = this.displayed_ // remove spaces from the start and end of the string
  40477. .map(function (row, index) {
  40478. try {
  40479. return row.trim();
  40480. } catch (e) {
  40481. // Ordinarily, this shouldn't happen. However, caption
  40482. // parsing errors should not throw exceptions and
  40483. // break playback.
  40484. this.trigger('log', {
  40485. level: 'warn',
  40486. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  40487. });
  40488. return '';
  40489. }
  40490. }, this) // combine all text rows to display in one cue
  40491. .join('\n') // and remove blank rows from the start and end, but not the middle
  40492. .replace(/^\n+|\n+$/g, '');
  40493. if (content.length) {
  40494. this.trigger('data', {
  40495. startPts: this.startPts_,
  40496. endPts: pts,
  40497. text: content,
  40498. stream: this.name_
  40499. });
  40500. }
  40501. };
  40502. /**
  40503. * Zero out the data, used for startup and on seek
  40504. */
  40505. Cea608Stream.prototype.reset = function () {
  40506. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  40507. // actually display captions. If a caption is shifted to a row
  40508. // with a lower index than this, it is cleared from the display
  40509. // buffer
  40510. this.topRow_ = 0;
  40511. this.startPts_ = 0;
  40512. this.displayed_ = createDisplayBuffer();
  40513. this.nonDisplayed_ = createDisplayBuffer();
  40514. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  40515. this.column_ = 0;
  40516. this.row_ = BOTTOM_ROW;
  40517. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  40518. this.formatting_ = [];
  40519. };
  40520. /**
  40521. * Sets up control code and related constants for this instance
  40522. */
  40523. Cea608Stream.prototype.setConstants = function () {
  40524. // The following attributes have these uses:
  40525. // ext_ : char0 for mid-row codes, and the base for extended
  40526. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  40527. // extended codes)
  40528. // control_: char0 for control codes, except byte-shifted to the
  40529. // left so that we can do this.control_ | CONTROL_CODE
  40530. // offset_: char0 for tab offset codes
  40531. //
  40532. // It's also worth noting that control codes, and _only_ control codes,
  40533. // differ between field 1 and field2. Field 2 control codes are always
  40534. // their field 1 value plus 1. That's why there's the "| field" on the
  40535. // control value.
  40536. if (this.dataChannel_ === 0) {
  40537. this.BASE_ = 0x10;
  40538. this.EXT_ = 0x11;
  40539. this.CONTROL_ = (0x14 | this.field_) << 8;
  40540. this.OFFSET_ = 0x17;
  40541. } else if (this.dataChannel_ === 1) {
  40542. this.BASE_ = 0x18;
  40543. this.EXT_ = 0x19;
  40544. this.CONTROL_ = (0x1c | this.field_) << 8;
  40545. this.OFFSET_ = 0x1f;
  40546. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  40547. // list is not exhaustive. For a more comprehensive listing and semantics see
  40548. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  40549. // Padding
  40550. this.PADDING_ = 0x0000; // Pop-on Mode
  40551. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  40552. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  40553. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  40554. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  40555. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  40556. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  40557. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  40558. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  40559. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  40560. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  40561. };
  40562. /**
  40563. * Detects if the 2-byte packet data is a special character
  40564. *
  40565. * Special characters have a second byte in the range 0x30 to 0x3f,
  40566. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  40567. * data channel 2).
  40568. *
  40569. * @param {Integer} char0 The first byte
  40570. * @param {Integer} char1 The second byte
  40571. * @return {Boolean} Whether the 2 bytes are an special character
  40572. */
  40573. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  40574. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  40575. };
  40576. /**
  40577. * Detects if the 2-byte packet data is an extended character
  40578. *
  40579. * Extended characters have a second byte in the range 0x20 to 0x3f,
  40580. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  40581. * 0x1a or 0x1b (for data channel 2).
  40582. *
  40583. * @param {Integer} char0 The first byte
  40584. * @param {Integer} char1 The second byte
  40585. * @return {Boolean} Whether the 2 bytes are an extended character
  40586. */
  40587. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  40588. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  40589. };
  40590. /**
  40591. * Detects if the 2-byte packet is a mid-row code
  40592. *
  40593. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  40594. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  40595. * channel 2).
  40596. *
  40597. * @param {Integer} char0 The first byte
  40598. * @param {Integer} char1 The second byte
  40599. * @return {Boolean} Whether the 2 bytes are a mid-row code
  40600. */
  40601. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  40602. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  40603. };
  40604. /**
  40605. * Detects if the 2-byte packet is an offset control code
  40606. *
  40607. * Offset control codes have a second byte in the range 0x21 to 0x23,
  40608. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  40609. * data channel 2).
  40610. *
  40611. * @param {Integer} char0 The first byte
  40612. * @param {Integer} char1 The second byte
  40613. * @return {Boolean} Whether the 2 bytes are an offset control code
  40614. */
  40615. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  40616. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  40617. };
  40618. /**
  40619. * Detects if the 2-byte packet is a Preamble Address Code
  40620. *
  40621. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  40622. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  40623. * range 0x40 to 0x7f.
  40624. *
  40625. * @param {Integer} char0 The first byte
  40626. * @param {Integer} char1 The second byte
  40627. * @return {Boolean} Whether the 2 bytes are a PAC
  40628. */
  40629. Cea608Stream.prototype.isPAC = function (char0, char1) {
  40630. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  40631. };
  40632. /**
  40633. * Detects if a packet's second byte is in the range of a PAC color code
  40634. *
  40635. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  40636. * 0x60 to 0x6f.
  40637. *
  40638. * @param {Integer} char1 The second byte
  40639. * @return {Boolean} Whether the byte is a color PAC
  40640. */
  40641. Cea608Stream.prototype.isColorPAC = function (char1) {
  40642. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  40643. };
  40644. /**
  40645. * Detects if a single byte is in the range of a normal character
  40646. *
  40647. * Normal text bytes are in the range 0x20 to 0x7f.
  40648. *
  40649. * @param {Integer} char The byte
  40650. * @return {Boolean} Whether the byte is a normal character
  40651. */
  40652. Cea608Stream.prototype.isNormalChar = function (char) {
  40653. return char >= 0x20 && char <= 0x7f;
  40654. };
  40655. /**
  40656. * Configures roll-up
  40657. *
  40658. * @param {Integer} pts Current PTS
  40659. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  40660. * a new position
  40661. */
  40662. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  40663. // Reset the base row to the bottom row when switching modes
  40664. if (this.mode_ !== 'rollUp') {
  40665. this.row_ = BOTTOM_ROW;
  40666. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  40667. this.flushDisplayed(pts);
  40668. this.nonDisplayed_ = createDisplayBuffer();
  40669. this.displayed_ = createDisplayBuffer();
  40670. }
  40671. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  40672. // move currently displayed captions (up or down) to the new base row
  40673. for (var i = 0; i < this.rollUpRows_; i++) {
  40674. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  40675. this.displayed_[this.row_ - i] = '';
  40676. }
  40677. }
  40678. if (newBaseRow === undefined) {
  40679. newBaseRow = this.row_;
  40680. }
  40681. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  40682. }; // Adds the opening HTML tag for the passed character to the caption text,
  40683. // and keeps track of it for later closing
  40684. Cea608Stream.prototype.addFormatting = function (pts, format) {
  40685. this.formatting_ = this.formatting_.concat(format);
  40686. var text = format.reduce(function (text, format) {
  40687. return text + '<' + format + '>';
  40688. }, '');
  40689. this[this.mode_](pts, text);
  40690. }; // Adds HTML closing tags for current formatting to caption text and
  40691. // clears remembered formatting
  40692. Cea608Stream.prototype.clearFormatting = function (pts) {
  40693. if (!this.formatting_.length) {
  40694. return;
  40695. }
  40696. var text = this.formatting_.reverse().reduce(function (text, format) {
  40697. return text + '</' + format + '>';
  40698. }, '');
  40699. this.formatting_ = [];
  40700. this[this.mode_](pts, text);
  40701. }; // Mode Implementations
  40702. Cea608Stream.prototype.popOn = function (pts, text) {
  40703. var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
  40704. baseRow += text;
  40705. this.nonDisplayed_[this.row_] = baseRow;
  40706. };
  40707. Cea608Stream.prototype.rollUp = function (pts, text) {
  40708. var baseRow = this.displayed_[this.row_];
  40709. baseRow += text;
  40710. this.displayed_[this.row_] = baseRow;
  40711. };
  40712. Cea608Stream.prototype.shiftRowsUp_ = function () {
  40713. var i; // clear out inactive rows
  40714. for (i = 0; i < this.topRow_; i++) {
  40715. this.displayed_[i] = '';
  40716. }
  40717. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  40718. this.displayed_[i] = '';
  40719. } // shift displayed rows up
  40720. for (i = this.topRow_; i < this.row_; i++) {
  40721. this.displayed_[i] = this.displayed_[i + 1];
  40722. } // clear out the bottom row
  40723. this.displayed_[this.row_] = '';
  40724. };
  40725. Cea608Stream.prototype.paintOn = function (pts, text) {
  40726. var baseRow = this.displayed_[this.row_];
  40727. baseRow += text;
  40728. this.displayed_[this.row_] = baseRow;
  40729. }; // exports
  40730. var captionStream = {
  40731. CaptionStream: CaptionStream$2,
  40732. Cea608Stream: Cea608Stream,
  40733. Cea708Stream: Cea708Stream
  40734. };
  40735. /**
  40736. * mux.js
  40737. *
  40738. * Copyright (c) Brightcove
  40739. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  40740. */
  40741. var streamTypes = {
  40742. H264_STREAM_TYPE: 0x1B,
  40743. ADTS_STREAM_TYPE: 0x0F,
  40744. METADATA_STREAM_TYPE: 0x15
  40745. };
  40746. /**
  40747. * mux.js
  40748. *
  40749. * Copyright (c) Brightcove
  40750. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  40751. *
  40752. * Accepts program elementary stream (PES) data events and corrects
  40753. * decode and presentation time stamps to account for a rollover
  40754. * of the 33 bit value.
  40755. */
  40756. var Stream$6 = stream;
  40757. var MAX_TS = 8589934592;
  40758. var RO_THRESH = 4294967296;
  40759. var TYPE_SHARED = 'shared';
  40760. var handleRollover$1 = function (value, reference) {
  40761. var direction = 1;
  40762. if (value > reference) {
  40763. // If the current timestamp value is greater than our reference timestamp and we detect a
  40764. // timestamp rollover, this means the roll over is happening in the opposite direction.
  40765. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  40766. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  40767. // rollover point. In loading this segment, the timestamp values will be very large,
  40768. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  40769. // the time stamp to be `value - 2^33`.
  40770. direction = -1;
  40771. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  40772. // cause an incorrect adjustment.
  40773. while (Math.abs(reference - value) > RO_THRESH) {
  40774. value += direction * MAX_TS;
  40775. }
  40776. return value;
  40777. };
  40778. var TimestampRolloverStream$1 = function (type) {
  40779. var lastDTS, referenceDTS;
  40780. TimestampRolloverStream$1.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  40781. // video and audio. We could use `undefined` here, but having a string
  40782. // makes debugging a little clearer.
  40783. this.type_ = type || TYPE_SHARED;
  40784. this.push = function (data) {
  40785. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  40786. // streams will only accept data that matches their type.
  40787. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  40788. return;
  40789. }
  40790. if (referenceDTS === undefined) {
  40791. referenceDTS = data.dts;
  40792. }
  40793. data.dts = handleRollover$1(data.dts, referenceDTS);
  40794. data.pts = handleRollover$1(data.pts, referenceDTS);
  40795. lastDTS = data.dts;
  40796. this.trigger('data', data);
  40797. };
  40798. this.flush = function () {
  40799. referenceDTS = lastDTS;
  40800. this.trigger('done');
  40801. };
  40802. this.endTimeline = function () {
  40803. this.flush();
  40804. this.trigger('endedtimeline');
  40805. };
  40806. this.discontinuity = function () {
  40807. referenceDTS = void 0;
  40808. lastDTS = void 0;
  40809. };
  40810. this.reset = function () {
  40811. this.discontinuity();
  40812. this.trigger('reset');
  40813. };
  40814. };
  40815. TimestampRolloverStream$1.prototype = new Stream$6();
  40816. var timestampRolloverStream = {
  40817. TimestampRolloverStream: TimestampRolloverStream$1,
  40818. handleRollover: handleRollover$1
  40819. }; // Once IE11 support is dropped, this function should be removed.
  40820. var typedArrayIndexOf$1 = (typedArray, element, fromIndex) => {
  40821. if (!typedArray) {
  40822. return -1;
  40823. }
  40824. var currentIndex = fromIndex;
  40825. for (; currentIndex < typedArray.length; currentIndex++) {
  40826. if (typedArray[currentIndex] === element) {
  40827. return currentIndex;
  40828. }
  40829. }
  40830. return -1;
  40831. };
  40832. var typedArray = {
  40833. typedArrayIndexOf: typedArrayIndexOf$1
  40834. };
  40835. /**
  40836. * mux.js
  40837. *
  40838. * Copyright (c) Brightcove
  40839. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  40840. *
  40841. * Tools for parsing ID3 frame data
  40842. * @see http://id3.org/id3v2.3.0
  40843. */
  40844. var typedArrayIndexOf = typedArray.typedArrayIndexOf,
  40845. // Frames that allow different types of text encoding contain a text
  40846. // encoding description byte [ID3v2.4.0 section 4.]
  40847. textEncodingDescriptionByte = {
  40848. Iso88591: 0x00,
  40849. // ISO-8859-1, terminated with \0.
  40850. Utf16: 0x01,
  40851. // UTF-16 encoded Unicode BOM, terminated with \0\0
  40852. Utf16be: 0x02,
  40853. // UTF-16BE encoded Unicode, without BOM, terminated with \0\0
  40854. Utf8: 0x03 // UTF-8 encoded Unicode, terminated with \0
  40855. },
  40856. // return a percent-encoded representation of the specified byte range
  40857. // @see http://en.wikipedia.org/wiki/Percent-encoding
  40858. percentEncode$1 = function (bytes, start, end) {
  40859. var i,
  40860. result = '';
  40861. for (i = start; i < end; i++) {
  40862. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  40863. }
  40864. return result;
  40865. },
  40866. // return the string representation of the specified byte range,
  40867. // interpreted as UTf-8.
  40868. parseUtf8 = function (bytes, start, end) {
  40869. return decodeURIComponent(percentEncode$1(bytes, start, end));
  40870. },
  40871. // return the string representation of the specified byte range,
  40872. // interpreted as ISO-8859-1.
  40873. parseIso88591$1 = function (bytes, start, end) {
  40874. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  40875. },
  40876. parseSyncSafeInteger$1 = function (data) {
  40877. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  40878. },
  40879. frameParsers = {
  40880. 'APIC': function (frame) {
  40881. var i = 1,
  40882. mimeTypeEndIndex,
  40883. descriptionEndIndex,
  40884. LINK_MIME_TYPE = '-->';
  40885. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  40886. // ignore frames with unrecognized character encodings
  40887. return;
  40888. } // parsing fields [ID3v2.4.0 section 4.14.]
  40889. mimeTypeEndIndex = typedArrayIndexOf(frame.data, 0, i);
  40890. if (mimeTypeEndIndex < 0) {
  40891. // malformed frame
  40892. return;
  40893. } // parsing Mime type field (terminated with \0)
  40894. frame.mimeType = parseIso88591$1(frame.data, i, mimeTypeEndIndex);
  40895. i = mimeTypeEndIndex + 1; // parsing 1-byte Picture Type field
  40896. frame.pictureType = frame.data[i];
  40897. i++;
  40898. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, i);
  40899. if (descriptionEndIndex < 0) {
  40900. // malformed frame
  40901. return;
  40902. } // parsing Description field (terminated with \0)
  40903. frame.description = parseUtf8(frame.data, i, descriptionEndIndex);
  40904. i = descriptionEndIndex + 1;
  40905. if (frame.mimeType === LINK_MIME_TYPE) {
  40906. // parsing Picture Data field as URL (always represented as ISO-8859-1 [ID3v2.4.0 section 4.])
  40907. frame.url = parseIso88591$1(frame.data, i, frame.data.length);
  40908. } else {
  40909. // parsing Picture Data field as binary data
  40910. frame.pictureData = frame.data.subarray(i, frame.data.length);
  40911. }
  40912. },
  40913. 'T*': function (frame) {
  40914. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  40915. // ignore frames with unrecognized character encodings
  40916. return;
  40917. } // parse text field, do not include null terminator in the frame value
  40918. // frames that allow different types of encoding contain terminated text [ID3v2.4.0 section 4.]
  40919. 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.]
  40920. frame.values = frame.value.split('\0');
  40921. },
  40922. 'TXXX': function (frame) {
  40923. var descriptionEndIndex;
  40924. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  40925. // ignore frames with unrecognized character encodings
  40926. return;
  40927. }
  40928. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  40929. if (descriptionEndIndex === -1) {
  40930. return;
  40931. } // parse the text fields
  40932. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // do not include the null terminator in the tag value
  40933. // frames that allow different types of encoding contain terminated text
  40934. // [ID3v2.4.0 section 4.]
  40935. frame.value = parseUtf8(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0*$/, '');
  40936. frame.data = frame.value;
  40937. },
  40938. 'W*': function (frame) {
  40939. // parse URL field; URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  40940. // if the value is followed by a string termination all the following information should be ignored [ID3v2.4.0 section 4.3]
  40941. frame.url = parseIso88591$1(frame.data, 0, frame.data.length).replace(/\0.*$/, '');
  40942. },
  40943. 'WXXX': function (frame) {
  40944. var descriptionEndIndex;
  40945. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  40946. // ignore frames with unrecognized character encodings
  40947. return;
  40948. }
  40949. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  40950. if (descriptionEndIndex === -1) {
  40951. return;
  40952. } // parse the description and URL fields
  40953. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  40954. // if the value is followed by a string termination all the following information
  40955. // should be ignored [ID3v2.4.0 section 4.3]
  40956. frame.url = parseIso88591$1(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0.*$/, '');
  40957. },
  40958. 'PRIV': function (frame) {
  40959. var i;
  40960. for (i = 0; i < frame.data.length; i++) {
  40961. if (frame.data[i] === 0) {
  40962. // parse the description and URL fields
  40963. frame.owner = parseIso88591$1(frame.data, 0, i);
  40964. break;
  40965. }
  40966. }
  40967. frame.privateData = frame.data.subarray(i + 1);
  40968. frame.data = frame.privateData;
  40969. }
  40970. };
  40971. var parseId3Frames$1 = function (data) {
  40972. var frameSize,
  40973. frameHeader,
  40974. frameStart = 10,
  40975. tagSize = 0,
  40976. frames = []; // If we don't have enough data for a header, 10 bytes,
  40977. // or 'ID3' in the first 3 bytes this is not a valid ID3 tag.
  40978. if (data.length < 10 || data[0] !== 'I'.charCodeAt(0) || data[1] !== 'D'.charCodeAt(0) || data[2] !== '3'.charCodeAt(0)) {
  40979. return;
  40980. } // the frame size is transmitted as a 28-bit integer in the
  40981. // last four bytes of the ID3 header.
  40982. // The most significant bit of each byte is dropped and the
  40983. // results concatenated to recover the actual value.
  40984. tagSize = parseSyncSafeInteger$1(data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  40985. // convenient for our comparisons to include it
  40986. tagSize += 10; // check bit 6 of byte 5 for the extended header flag.
  40987. var hasExtendedHeader = data[5] & 0x40;
  40988. if (hasExtendedHeader) {
  40989. // advance the frame start past the extended header
  40990. frameStart += 4; // header size field
  40991. frameStart += parseSyncSafeInteger$1(data.subarray(10, 14));
  40992. tagSize -= parseSyncSafeInteger$1(data.subarray(16, 20)); // clip any padding off the end
  40993. } // parse one or more ID3 frames
  40994. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  40995. do {
  40996. // determine the number of bytes in this frame
  40997. frameSize = parseSyncSafeInteger$1(data.subarray(frameStart + 4, frameStart + 8));
  40998. if (frameSize < 1) {
  40999. break;
  41000. }
  41001. frameHeader = String.fromCharCode(data[frameStart], data[frameStart + 1], data[frameStart + 2], data[frameStart + 3]);
  41002. var frame = {
  41003. id: frameHeader,
  41004. data: data.subarray(frameStart + 10, frameStart + frameSize + 10)
  41005. };
  41006. frame.key = frame.id; // parse frame values
  41007. if (frameParsers[frame.id]) {
  41008. // use frame specific parser
  41009. frameParsers[frame.id](frame);
  41010. } else if (frame.id[0] === 'T') {
  41011. // use text frame generic parser
  41012. frameParsers['T*'](frame);
  41013. } else if (frame.id[0] === 'W') {
  41014. // use URL link frame generic parser
  41015. frameParsers['W*'](frame);
  41016. }
  41017. frames.push(frame);
  41018. frameStart += 10; // advance past the frame header
  41019. frameStart += frameSize; // advance past the frame body
  41020. } while (frameStart < tagSize);
  41021. return frames;
  41022. };
  41023. var parseId3 = {
  41024. parseId3Frames: parseId3Frames$1,
  41025. parseSyncSafeInteger: parseSyncSafeInteger$1,
  41026. frameParsers: frameParsers
  41027. };
  41028. /**
  41029. * mux.js
  41030. *
  41031. * Copyright (c) Brightcove
  41032. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  41033. *
  41034. * Accepts program elementary stream (PES) data events and parses out
  41035. * ID3 metadata from them, if present.
  41036. * @see http://id3.org/id3v2.3.0
  41037. */
  41038. var Stream$5 = stream,
  41039. StreamTypes$3 = streamTypes,
  41040. id3 = parseId3,
  41041. MetadataStream;
  41042. MetadataStream = function (options) {
  41043. var settings = {
  41044. // the bytes of the program-level descriptor field in MP2T
  41045. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  41046. // program element descriptors"
  41047. descriptor: options && options.descriptor
  41048. },
  41049. // the total size in bytes of the ID3 tag being parsed
  41050. tagSize = 0,
  41051. // tag data that is not complete enough to be parsed
  41052. buffer = [],
  41053. // the total number of bytes currently in the buffer
  41054. bufferSize = 0,
  41055. i;
  41056. MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  41057. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  41058. this.dispatchType = StreamTypes$3.METADATA_STREAM_TYPE.toString(16);
  41059. if (settings.descriptor) {
  41060. for (i = 0; i < settings.descriptor.length; i++) {
  41061. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  41062. }
  41063. }
  41064. this.push = function (chunk) {
  41065. var tag, frameStart, frameSize, frame, i, frameHeader;
  41066. if (chunk.type !== 'timed-metadata') {
  41067. return;
  41068. } // if data_alignment_indicator is set in the PES header,
  41069. // we must have the start of a new ID3 tag. Assume anything
  41070. // remaining in the buffer was malformed and throw it out
  41071. if (chunk.dataAlignmentIndicator) {
  41072. bufferSize = 0;
  41073. buffer.length = 0;
  41074. } // ignore events that don't look like ID3 data
  41075. 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))) {
  41076. this.trigger('log', {
  41077. level: 'warn',
  41078. message: 'Skipping unrecognized metadata packet'
  41079. });
  41080. return;
  41081. } // add this chunk to the data we've collected so far
  41082. buffer.push(chunk);
  41083. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  41084. if (buffer.length === 1) {
  41085. // the frame size is transmitted as a 28-bit integer in the
  41086. // last four bytes of the ID3 header.
  41087. // The most significant bit of each byte is dropped and the
  41088. // results concatenated to recover the actual value.
  41089. tagSize = id3.parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  41090. // convenient for our comparisons to include it
  41091. tagSize += 10;
  41092. } // if the entire frame has not arrived, wait for more data
  41093. if (bufferSize < tagSize) {
  41094. return;
  41095. } // collect the entire frame so it can be parsed
  41096. tag = {
  41097. data: new Uint8Array(tagSize),
  41098. frames: [],
  41099. pts: buffer[0].pts,
  41100. dts: buffer[0].dts
  41101. };
  41102. for (i = 0; i < tagSize;) {
  41103. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  41104. i += buffer[0].data.byteLength;
  41105. bufferSize -= buffer[0].data.byteLength;
  41106. buffer.shift();
  41107. } // find the start of the first frame and the end of the tag
  41108. frameStart = 10;
  41109. if (tag.data[5] & 0x40) {
  41110. // advance the frame start past the extended header
  41111. frameStart += 4; // header size field
  41112. frameStart += id3.parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end
  41113. tagSize -= id3.parseSyncSafeInteger(tag.data.subarray(16, 20));
  41114. } // parse one or more ID3 frames
  41115. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  41116. do {
  41117. // determine the number of bytes in this frame
  41118. frameSize = id3.parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  41119. if (frameSize < 1) {
  41120. this.trigger('log', {
  41121. level: 'warn',
  41122. message: 'Malformed ID3 frame encountered. Skipping remaining metadata parsing.'
  41123. }); // If the frame is malformed, don't parse any further frames but allow previous valid parsed frames
  41124. // to be sent along.
  41125. break;
  41126. }
  41127. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  41128. frame = {
  41129. id: frameHeader,
  41130. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  41131. };
  41132. frame.key = frame.id; // parse frame values
  41133. if (id3.frameParsers[frame.id]) {
  41134. // use frame specific parser
  41135. id3.frameParsers[frame.id](frame);
  41136. } else if (frame.id[0] === 'T') {
  41137. // use text frame generic parser
  41138. id3.frameParsers['T*'](frame);
  41139. } else if (frame.id[0] === 'W') {
  41140. // use URL link frame generic parser
  41141. id3.frameParsers['W*'](frame);
  41142. } // handle the special PRIV frame used to indicate the start
  41143. // time for raw AAC data
  41144. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  41145. var d = frame.data,
  41146. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  41147. size *= 4;
  41148. size += d[7] & 0x03;
  41149. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  41150. // on the value of this frame
  41151. // we couldn't have known the appropriate pts and dts before
  41152. // parsing this ID3 tag so set those values now
  41153. if (tag.pts === undefined && tag.dts === undefined) {
  41154. tag.pts = frame.timeStamp;
  41155. tag.dts = frame.timeStamp;
  41156. }
  41157. this.trigger('timestamp', frame);
  41158. }
  41159. tag.frames.push(frame);
  41160. frameStart += 10; // advance past the frame header
  41161. frameStart += frameSize; // advance past the frame body
  41162. } while (frameStart < tagSize);
  41163. this.trigger('data', tag);
  41164. };
  41165. };
  41166. MetadataStream.prototype = new Stream$5();
  41167. var metadataStream = MetadataStream;
  41168. /**
  41169. * mux.js
  41170. *
  41171. * Copyright (c) Brightcove
  41172. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  41173. *
  41174. * A stream-based mp2t to mp4 converter. This utility can be used to
  41175. * deliver mp4s to a SourceBuffer on platforms that support native
  41176. * Media Source Extensions.
  41177. */
  41178. var Stream$4 = stream,
  41179. CaptionStream$1 = captionStream,
  41180. StreamTypes$2 = streamTypes,
  41181. TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  41182. var TransportPacketStream, TransportParseStream, ElementaryStream; // constants
  41183. var MP2T_PACKET_LENGTH$1 = 188,
  41184. // bytes
  41185. SYNC_BYTE$1 = 0x47;
  41186. /**
  41187. * Splits an incoming stream of binary data into MPEG-2 Transport
  41188. * Stream packets.
  41189. */
  41190. TransportPacketStream = function () {
  41191. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  41192. bytesInBuffer = 0;
  41193. TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  41194. /**
  41195. * Split a stream of data into M2TS packets
  41196. **/
  41197. this.push = function (bytes) {
  41198. var startIndex = 0,
  41199. endIndex = MP2T_PACKET_LENGTH$1,
  41200. everything; // If there are bytes remaining from the last segment, prepend them to the
  41201. // bytes that were pushed in
  41202. if (bytesInBuffer) {
  41203. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  41204. everything.set(buffer.subarray(0, bytesInBuffer));
  41205. everything.set(bytes, bytesInBuffer);
  41206. bytesInBuffer = 0;
  41207. } else {
  41208. everything = bytes;
  41209. } // While we have enough data for a packet
  41210. while (endIndex < everything.byteLength) {
  41211. // Look for a pair of start and end sync bytes in the data..
  41212. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  41213. // We found a packet so emit it and jump one whole packet forward in
  41214. // the stream
  41215. this.trigger('data', everything.subarray(startIndex, endIndex));
  41216. startIndex += MP2T_PACKET_LENGTH$1;
  41217. endIndex += MP2T_PACKET_LENGTH$1;
  41218. continue;
  41219. } // If we get here, we have somehow become de-synchronized and we need to step
  41220. // forward one byte at a time until we find a pair of sync bytes that denote
  41221. // a packet
  41222. startIndex++;
  41223. endIndex++;
  41224. } // If there was some data left over at the end of the segment that couldn't
  41225. // possibly be a whole packet, keep it because it might be the start of a packet
  41226. // that continues in the next segment
  41227. if (startIndex < everything.byteLength) {
  41228. buffer.set(everything.subarray(startIndex), 0);
  41229. bytesInBuffer = everything.byteLength - startIndex;
  41230. }
  41231. };
  41232. /**
  41233. * Passes identified M2TS packets to the TransportParseStream to be parsed
  41234. **/
  41235. this.flush = function () {
  41236. // If the buffer contains a whole packet when we are being flushed, emit it
  41237. // and empty the buffer. Otherwise hold onto the data because it may be
  41238. // important for decoding the next segment
  41239. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  41240. this.trigger('data', buffer);
  41241. bytesInBuffer = 0;
  41242. }
  41243. this.trigger('done');
  41244. };
  41245. this.endTimeline = function () {
  41246. this.flush();
  41247. this.trigger('endedtimeline');
  41248. };
  41249. this.reset = function () {
  41250. bytesInBuffer = 0;
  41251. this.trigger('reset');
  41252. };
  41253. };
  41254. TransportPacketStream.prototype = new Stream$4();
  41255. /**
  41256. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  41257. * forms of the individual transport stream packets.
  41258. */
  41259. TransportParseStream = function () {
  41260. var parsePsi, parsePat, parsePmt, self;
  41261. TransportParseStream.prototype.init.call(this);
  41262. self = this;
  41263. this.packetsWaitingForPmt = [];
  41264. this.programMapTable = undefined;
  41265. parsePsi = function (payload, psi) {
  41266. var offset = 0; // PSI packets may be split into multiple sections and those
  41267. // sections may be split into multiple packets. If a PSI
  41268. // section starts in this packet, the payload_unit_start_indicator
  41269. // will be true and the first byte of the payload will indicate
  41270. // the offset from the current position to the start of the
  41271. // section.
  41272. if (psi.payloadUnitStartIndicator) {
  41273. offset += payload[offset] + 1;
  41274. }
  41275. if (psi.type === 'pat') {
  41276. parsePat(payload.subarray(offset), psi);
  41277. } else {
  41278. parsePmt(payload.subarray(offset), psi);
  41279. }
  41280. };
  41281. parsePat = function (payload, pat) {
  41282. pat.section_number = payload[7]; // eslint-disable-line camelcase
  41283. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  41284. // skip the PSI header and parse the first PMT entry
  41285. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  41286. pat.pmtPid = self.pmtPid;
  41287. };
  41288. /**
  41289. * Parse out the relevant fields of a Program Map Table (PMT).
  41290. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  41291. * packet. The first byte in this array should be the table_id
  41292. * field.
  41293. * @param pmt {object} the object that should be decorated with
  41294. * fields parsed from the PMT.
  41295. */
  41296. parsePmt = function (payload, pmt) {
  41297. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  41298. // take effect. We don't believe this should ever be the case
  41299. // for HLS but we'll ignore "forward" PMT declarations if we see
  41300. // them. Future PMT declarations have the current_next_indicator
  41301. // set to zero.
  41302. if (!(payload[5] & 0x01)) {
  41303. return;
  41304. } // overwrite any existing program map table
  41305. self.programMapTable = {
  41306. video: null,
  41307. audio: null,
  41308. 'timed-metadata': {}
  41309. }; // the mapping table ends at the end of the current section
  41310. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  41311. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  41312. // long the program info descriptors are
  41313. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  41314. offset = 12 + programInfoLength;
  41315. while (offset < tableEnd) {
  41316. var streamType = payload[offset];
  41317. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  41318. // TODO: should this be done for metadata too? for now maintain behavior of
  41319. // multiple metadata streams
  41320. if (streamType === StreamTypes$2.H264_STREAM_TYPE && self.programMapTable.video === null) {
  41321. self.programMapTable.video = pid;
  41322. } else if (streamType === StreamTypes$2.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  41323. self.programMapTable.audio = pid;
  41324. } else if (streamType === StreamTypes$2.METADATA_STREAM_TYPE) {
  41325. // map pid to stream type for metadata streams
  41326. self.programMapTable['timed-metadata'][pid] = streamType;
  41327. } // move to the next table entry
  41328. // skip past the elementary stream descriptors, if present
  41329. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  41330. } // record the map on the packet as well
  41331. pmt.programMapTable = self.programMapTable;
  41332. };
  41333. /**
  41334. * Deliver a new MP2T packet to the next stream in the pipeline.
  41335. */
  41336. this.push = function (packet) {
  41337. var result = {},
  41338. offset = 4;
  41339. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  41340. result.pid = packet[1] & 0x1f;
  41341. result.pid <<= 8;
  41342. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  41343. // fifth byte of the TS packet header. The adaptation field is
  41344. // used to add stuffing to PES packets that don't fill a complete
  41345. // TS packet, and to specify some forms of timing and control data
  41346. // that we do not currently use.
  41347. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  41348. offset += packet[offset] + 1;
  41349. } // parse the rest of the packet based on the type
  41350. if (result.pid === 0) {
  41351. result.type = 'pat';
  41352. parsePsi(packet.subarray(offset), result);
  41353. this.trigger('data', result);
  41354. } else if (result.pid === this.pmtPid) {
  41355. result.type = 'pmt';
  41356. parsePsi(packet.subarray(offset), result);
  41357. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  41358. while (this.packetsWaitingForPmt.length) {
  41359. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  41360. }
  41361. } else if (this.programMapTable === undefined) {
  41362. // When we have not seen a PMT yet, defer further processing of
  41363. // PES packets until one has been parsed
  41364. this.packetsWaitingForPmt.push([packet, offset, result]);
  41365. } else {
  41366. this.processPes_(packet, offset, result);
  41367. }
  41368. };
  41369. this.processPes_ = function (packet, offset, result) {
  41370. // set the appropriate stream type
  41371. if (result.pid === this.programMapTable.video) {
  41372. result.streamType = StreamTypes$2.H264_STREAM_TYPE;
  41373. } else if (result.pid === this.programMapTable.audio) {
  41374. result.streamType = StreamTypes$2.ADTS_STREAM_TYPE;
  41375. } else {
  41376. // if not video or audio, it is timed-metadata or unknown
  41377. // if unknown, streamType will be undefined
  41378. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  41379. }
  41380. result.type = 'pes';
  41381. result.data = packet.subarray(offset);
  41382. this.trigger('data', result);
  41383. };
  41384. };
  41385. TransportParseStream.prototype = new Stream$4();
  41386. TransportParseStream.STREAM_TYPES = {
  41387. h264: 0x1b,
  41388. adts: 0x0f
  41389. };
  41390. /**
  41391. * Reconsistutes program elementary stream (PES) packets from parsed
  41392. * transport stream packets. That is, if you pipe an
  41393. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  41394. * events will be events which capture the bytes for individual PES
  41395. * packets plus relevant metadata that has been extracted from the
  41396. * container.
  41397. */
  41398. ElementaryStream = function () {
  41399. var self = this,
  41400. segmentHadPmt = false,
  41401. // PES packet fragments
  41402. video = {
  41403. data: [],
  41404. size: 0
  41405. },
  41406. audio = {
  41407. data: [],
  41408. size: 0
  41409. },
  41410. timedMetadata = {
  41411. data: [],
  41412. size: 0
  41413. },
  41414. programMapTable,
  41415. parsePes = function (payload, pes) {
  41416. var ptsDtsFlags;
  41417. const startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  41418. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  41419. // that are frame data that is continuing from the previous fragment. This
  41420. // is to check that the pes data is the start of a new pes payload
  41421. if (startPrefix !== 1) {
  41422. return;
  41423. } // get the packet length, this will be 0 for video
  41424. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  41425. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  41426. // and a DTS value. Determine what combination of values is
  41427. // available to work with.
  41428. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  41429. // performs all bitwise operations on 32-bit integers but javascript
  41430. // supports a much greater range (52-bits) of integer using standard
  41431. // mathematical operations.
  41432. // We construct a 31-bit value using bitwise operators over the 31
  41433. // most significant bits and then multiply by 4 (equal to a left-shift
  41434. // of 2) before we add the final 2 least significant bits of the
  41435. // timestamp (equal to an OR.)
  41436. if (ptsDtsFlags & 0xC0) {
  41437. // the PTS and DTS are not written out directly. For information
  41438. // on how they are encoded, see
  41439. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  41440. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  41441. pes.pts *= 4; // Left shift by 2
  41442. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  41443. pes.dts = pes.pts;
  41444. if (ptsDtsFlags & 0x40) {
  41445. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  41446. pes.dts *= 4; // Left shift by 2
  41447. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  41448. }
  41449. } // the data section starts immediately after the PES header.
  41450. // pes_header_data_length specifies the number of header bytes
  41451. // that follow the last byte of the field.
  41452. pes.data = payload.subarray(9 + payload[8]);
  41453. },
  41454. /**
  41455. * Pass completely parsed PES packets to the next stream in the pipeline
  41456. **/
  41457. flushStream = function (stream, type, forceFlush) {
  41458. var packetData = new Uint8Array(stream.size),
  41459. event = {
  41460. type: type
  41461. },
  41462. i = 0,
  41463. offset = 0,
  41464. packetFlushable = false,
  41465. fragment; // do nothing if there is not enough buffered data for a complete
  41466. // PES header
  41467. if (!stream.data.length || stream.size < 9) {
  41468. return;
  41469. }
  41470. event.trackId = stream.data[0].pid; // reassemble the packet
  41471. for (i = 0; i < stream.data.length; i++) {
  41472. fragment = stream.data[i];
  41473. packetData.set(fragment.data, offset);
  41474. offset += fragment.data.byteLength;
  41475. } // parse assembled packet's PES header
  41476. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  41477. // check that there is enough stream data to fill the packet
  41478. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  41479. if (forceFlush || packetFlushable) {
  41480. stream.size = 0;
  41481. stream.data.length = 0;
  41482. } // only emit packets that are complete. this is to avoid assembling
  41483. // incomplete PES packets due to poor segmentation
  41484. if (packetFlushable) {
  41485. self.trigger('data', event);
  41486. }
  41487. };
  41488. ElementaryStream.prototype.init.call(this);
  41489. /**
  41490. * Identifies M2TS packet types and parses PES packets using metadata
  41491. * parsed from the PMT
  41492. **/
  41493. this.push = function (data) {
  41494. ({
  41495. pat: function () {// we have to wait for the PMT to arrive as well before we
  41496. // have any meaningful metadata
  41497. },
  41498. pes: function () {
  41499. var stream, streamType;
  41500. switch (data.streamType) {
  41501. case StreamTypes$2.H264_STREAM_TYPE:
  41502. stream = video;
  41503. streamType = 'video';
  41504. break;
  41505. case StreamTypes$2.ADTS_STREAM_TYPE:
  41506. stream = audio;
  41507. streamType = 'audio';
  41508. break;
  41509. case StreamTypes$2.METADATA_STREAM_TYPE:
  41510. stream = timedMetadata;
  41511. streamType = 'timed-metadata';
  41512. break;
  41513. default:
  41514. // ignore unknown stream types
  41515. return;
  41516. } // if a new packet is starting, we can flush the completed
  41517. // packet
  41518. if (data.payloadUnitStartIndicator) {
  41519. flushStream(stream, streamType, true);
  41520. } // buffer this fragment until we are sure we've received the
  41521. // complete payload
  41522. stream.data.push(data);
  41523. stream.size += data.data.byteLength;
  41524. },
  41525. pmt: function () {
  41526. var event = {
  41527. type: 'metadata',
  41528. tracks: []
  41529. };
  41530. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  41531. if (programMapTable.video !== null) {
  41532. event.tracks.push({
  41533. timelineStartInfo: {
  41534. baseMediaDecodeTime: 0
  41535. },
  41536. id: +programMapTable.video,
  41537. codec: 'avc',
  41538. type: 'video'
  41539. });
  41540. }
  41541. if (programMapTable.audio !== null) {
  41542. event.tracks.push({
  41543. timelineStartInfo: {
  41544. baseMediaDecodeTime: 0
  41545. },
  41546. id: +programMapTable.audio,
  41547. codec: 'adts',
  41548. type: 'audio'
  41549. });
  41550. }
  41551. segmentHadPmt = true;
  41552. self.trigger('data', event);
  41553. }
  41554. })[data.type]();
  41555. };
  41556. this.reset = function () {
  41557. video.size = 0;
  41558. video.data.length = 0;
  41559. audio.size = 0;
  41560. audio.data.length = 0;
  41561. this.trigger('reset');
  41562. };
  41563. /**
  41564. * Flush any remaining input. Video PES packets may be of variable
  41565. * length. Normally, the start of a new video packet can trigger the
  41566. * finalization of the previous packet. That is not possible if no
  41567. * more video is forthcoming, however. In that case, some other
  41568. * mechanism (like the end of the file) has to be employed. When it is
  41569. * clear that no additional data is forthcoming, calling this method
  41570. * will flush the buffered packets.
  41571. */
  41572. this.flushStreams_ = function () {
  41573. // !!THIS ORDER IS IMPORTANT!!
  41574. // video first then audio
  41575. flushStream(video, 'video');
  41576. flushStream(audio, 'audio');
  41577. flushStream(timedMetadata, 'timed-metadata');
  41578. };
  41579. this.flush = function () {
  41580. // if on flush we haven't had a pmt emitted
  41581. // and we have a pmt to emit. emit the pmt
  41582. // so that we trigger a trackinfo downstream.
  41583. if (!segmentHadPmt && programMapTable) {
  41584. var pmt = {
  41585. type: 'metadata',
  41586. tracks: []
  41587. }; // translate audio and video streams to tracks
  41588. if (programMapTable.video !== null) {
  41589. pmt.tracks.push({
  41590. timelineStartInfo: {
  41591. baseMediaDecodeTime: 0
  41592. },
  41593. id: +programMapTable.video,
  41594. codec: 'avc',
  41595. type: 'video'
  41596. });
  41597. }
  41598. if (programMapTable.audio !== null) {
  41599. pmt.tracks.push({
  41600. timelineStartInfo: {
  41601. baseMediaDecodeTime: 0
  41602. },
  41603. id: +programMapTable.audio,
  41604. codec: 'adts',
  41605. type: 'audio'
  41606. });
  41607. }
  41608. self.trigger('data', pmt);
  41609. }
  41610. segmentHadPmt = false;
  41611. this.flushStreams_();
  41612. this.trigger('done');
  41613. };
  41614. };
  41615. ElementaryStream.prototype = new Stream$4();
  41616. var m2ts$1 = {
  41617. PAT_PID: 0x0000,
  41618. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  41619. TransportPacketStream: TransportPacketStream,
  41620. TransportParseStream: TransportParseStream,
  41621. ElementaryStream: ElementaryStream,
  41622. TimestampRolloverStream: TimestampRolloverStream,
  41623. CaptionStream: CaptionStream$1.CaptionStream,
  41624. Cea608Stream: CaptionStream$1.Cea608Stream,
  41625. Cea708Stream: CaptionStream$1.Cea708Stream,
  41626. MetadataStream: metadataStream
  41627. };
  41628. for (var type in StreamTypes$2) {
  41629. if (StreamTypes$2.hasOwnProperty(type)) {
  41630. m2ts$1[type] = StreamTypes$2[type];
  41631. }
  41632. }
  41633. var m2ts_1 = m2ts$1;
  41634. /**
  41635. * mux.js
  41636. *
  41637. * Copyright (c) Brightcove
  41638. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  41639. */
  41640. var Stream$3 = stream;
  41641. var ONE_SECOND_IN_TS$2 = clock$2.ONE_SECOND_IN_TS;
  41642. var AdtsStream$1;
  41643. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  41644. /*
  41645. * Accepts a ElementaryStream and emits data events with parsed
  41646. * AAC Audio Frames of the individual packets. Input audio in ADTS
  41647. * format is unpacked and re-emitted as AAC frames.
  41648. *
  41649. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  41650. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  41651. */
  41652. AdtsStream$1 = function (handlePartialSegments) {
  41653. var buffer,
  41654. frameNum = 0;
  41655. AdtsStream$1.prototype.init.call(this);
  41656. this.skipWarn_ = function (start, end) {
  41657. this.trigger('log', {
  41658. level: 'warn',
  41659. message: `adts skiping bytes ${start} to ${end} in frame ${frameNum} outside syncword`
  41660. });
  41661. };
  41662. this.push = function (packet) {
  41663. var i = 0,
  41664. frameLength,
  41665. protectionSkipBytes,
  41666. oldBuffer,
  41667. sampleCount,
  41668. adtsFrameDuration;
  41669. if (!handlePartialSegments) {
  41670. frameNum = 0;
  41671. }
  41672. if (packet.type !== 'audio') {
  41673. // ignore non-audio data
  41674. return;
  41675. } // Prepend any data in the buffer to the input data so that we can parse
  41676. // aac frames the cross a PES packet boundary
  41677. if (buffer && buffer.length) {
  41678. oldBuffer = buffer;
  41679. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  41680. buffer.set(oldBuffer);
  41681. buffer.set(packet.data, oldBuffer.byteLength);
  41682. } else {
  41683. buffer = packet.data;
  41684. } // unpack any ADTS frames which have been fully received
  41685. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  41686. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  41687. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  41688. while (i + 7 < buffer.length) {
  41689. // Look for the start of an ADTS header..
  41690. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  41691. if (typeof skip !== 'number') {
  41692. skip = i;
  41693. } // If a valid header was not found, jump one forward and attempt to
  41694. // find a valid ADTS header starting at the next byte
  41695. i++;
  41696. continue;
  41697. }
  41698. if (typeof skip === 'number') {
  41699. this.skipWarn_(skip, i);
  41700. skip = null;
  41701. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  41702. // end of the ADTS header
  41703. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  41704. // end of the sync sequence
  41705. // NOTE: frame length includes the size of the header
  41706. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  41707. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  41708. 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,
  41709. // then we have to wait for more data
  41710. if (buffer.byteLength - i < frameLength) {
  41711. break;
  41712. } // Otherwise, deliver the complete AAC frame
  41713. this.trigger('data', {
  41714. pts: packet.pts + frameNum * adtsFrameDuration,
  41715. dts: packet.dts + frameNum * adtsFrameDuration,
  41716. sampleCount: sampleCount,
  41717. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  41718. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  41719. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  41720. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  41721. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  41722. samplesize: 16,
  41723. // data is the frame without it's header
  41724. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  41725. });
  41726. frameNum++;
  41727. i += frameLength;
  41728. }
  41729. if (typeof skip === 'number') {
  41730. this.skipWarn_(skip, i);
  41731. skip = null;
  41732. } // remove processed bytes from the buffer.
  41733. buffer = buffer.subarray(i);
  41734. };
  41735. this.flush = function () {
  41736. frameNum = 0;
  41737. this.trigger('done');
  41738. };
  41739. this.reset = function () {
  41740. buffer = void 0;
  41741. this.trigger('reset');
  41742. };
  41743. this.endTimeline = function () {
  41744. buffer = void 0;
  41745. this.trigger('endedtimeline');
  41746. };
  41747. };
  41748. AdtsStream$1.prototype = new Stream$3();
  41749. var adts = AdtsStream$1;
  41750. /**
  41751. * mux.js
  41752. *
  41753. * Copyright (c) Brightcove
  41754. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  41755. */
  41756. var ExpGolomb$1;
  41757. /**
  41758. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  41759. * scheme used by h264.
  41760. */
  41761. ExpGolomb$1 = function (workingData) {
  41762. var
  41763. // the number of bytes left to examine in workingData
  41764. workingBytesAvailable = workingData.byteLength,
  41765. // the current word being examined
  41766. workingWord = 0,
  41767. // :uint
  41768. // the number of bits left to examine in the current word
  41769. workingBitsAvailable = 0; // :uint;
  41770. // ():uint
  41771. this.length = function () {
  41772. return 8 * workingBytesAvailable;
  41773. }; // ():uint
  41774. this.bitsAvailable = function () {
  41775. return 8 * workingBytesAvailable + workingBitsAvailable;
  41776. }; // ():void
  41777. this.loadWord = function () {
  41778. var position = workingData.byteLength - workingBytesAvailable,
  41779. workingBytes = new Uint8Array(4),
  41780. availableBytes = Math.min(4, workingBytesAvailable);
  41781. if (availableBytes === 0) {
  41782. throw new Error('no bytes available');
  41783. }
  41784. workingBytes.set(workingData.subarray(position, position + availableBytes));
  41785. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  41786. workingBitsAvailable = availableBytes * 8;
  41787. workingBytesAvailable -= availableBytes;
  41788. }; // (count:int):void
  41789. this.skipBits = function (count) {
  41790. var skipBytes; // :int
  41791. if (workingBitsAvailable > count) {
  41792. workingWord <<= count;
  41793. workingBitsAvailable -= count;
  41794. } else {
  41795. count -= workingBitsAvailable;
  41796. skipBytes = Math.floor(count / 8);
  41797. count -= skipBytes * 8;
  41798. workingBytesAvailable -= skipBytes;
  41799. this.loadWord();
  41800. workingWord <<= count;
  41801. workingBitsAvailable -= count;
  41802. }
  41803. }; // (size:int):uint
  41804. this.readBits = function (size) {
  41805. var bits = Math.min(workingBitsAvailable, size),
  41806. // :uint
  41807. valu = workingWord >>> 32 - bits; // :uint
  41808. // if size > 31, handle error
  41809. workingBitsAvailable -= bits;
  41810. if (workingBitsAvailable > 0) {
  41811. workingWord <<= bits;
  41812. } else if (workingBytesAvailable > 0) {
  41813. this.loadWord();
  41814. }
  41815. bits = size - bits;
  41816. if (bits > 0) {
  41817. return valu << bits | this.readBits(bits);
  41818. }
  41819. return valu;
  41820. }; // ():uint
  41821. this.skipLeadingZeros = function () {
  41822. var leadingZeroCount; // :uint
  41823. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  41824. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  41825. // the first bit of working word is 1
  41826. workingWord <<= leadingZeroCount;
  41827. workingBitsAvailable -= leadingZeroCount;
  41828. return leadingZeroCount;
  41829. }
  41830. } // we exhausted workingWord and still have not found a 1
  41831. this.loadWord();
  41832. return leadingZeroCount + this.skipLeadingZeros();
  41833. }; // ():void
  41834. this.skipUnsignedExpGolomb = function () {
  41835. this.skipBits(1 + this.skipLeadingZeros());
  41836. }; // ():void
  41837. this.skipExpGolomb = function () {
  41838. this.skipBits(1 + this.skipLeadingZeros());
  41839. }; // ():uint
  41840. this.readUnsignedExpGolomb = function () {
  41841. var clz = this.skipLeadingZeros(); // :uint
  41842. return this.readBits(clz + 1) - 1;
  41843. }; // ():int
  41844. this.readExpGolomb = function () {
  41845. var valu = this.readUnsignedExpGolomb(); // :int
  41846. if (0x01 & valu) {
  41847. // the number is odd if the low order bit is set
  41848. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  41849. }
  41850. return -1 * (valu >>> 1); // divide by two then make it negative
  41851. }; // Some convenience functions
  41852. // :Boolean
  41853. this.readBoolean = function () {
  41854. return this.readBits(1) === 1;
  41855. }; // ():int
  41856. this.readUnsignedByte = function () {
  41857. return this.readBits(8);
  41858. };
  41859. this.loadWord();
  41860. };
  41861. var expGolomb = ExpGolomb$1;
  41862. /**
  41863. * mux.js
  41864. *
  41865. * Copyright (c) Brightcove
  41866. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  41867. */
  41868. var Stream$2 = stream;
  41869. var ExpGolomb = expGolomb;
  41870. var H264Stream$1, NalByteStream;
  41871. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  41872. /**
  41873. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  41874. */
  41875. NalByteStream = function () {
  41876. var syncPoint = 0,
  41877. i,
  41878. buffer;
  41879. NalByteStream.prototype.init.call(this);
  41880. /*
  41881. * Scans a byte stream and triggers a data event with the NAL units found.
  41882. * @param {Object} data Event received from H264Stream
  41883. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  41884. *
  41885. * @see H264Stream.push
  41886. */
  41887. this.push = function (data) {
  41888. var swapBuffer;
  41889. if (!buffer) {
  41890. buffer = data.data;
  41891. } else {
  41892. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  41893. swapBuffer.set(buffer);
  41894. swapBuffer.set(data.data, buffer.byteLength);
  41895. buffer = swapBuffer;
  41896. }
  41897. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  41898. // scan for NAL unit boundaries
  41899. // a match looks like this:
  41900. // 0 0 1 .. NAL .. 0 0 1
  41901. // ^ sync point ^ i
  41902. // or this:
  41903. // 0 0 1 .. NAL .. 0 0 0
  41904. // ^ sync point ^ i
  41905. // advance the sync point to a NAL start, if necessary
  41906. for (; syncPoint < len - 3; syncPoint++) {
  41907. if (buffer[syncPoint + 2] === 1) {
  41908. // the sync point is properly aligned
  41909. i = syncPoint + 5;
  41910. break;
  41911. }
  41912. }
  41913. while (i < len) {
  41914. // look at the current byte to determine if we've hit the end of
  41915. // a NAL unit boundary
  41916. switch (buffer[i]) {
  41917. case 0:
  41918. // skip past non-sync sequences
  41919. if (buffer[i - 1] !== 0) {
  41920. i += 2;
  41921. break;
  41922. } else if (buffer[i - 2] !== 0) {
  41923. i++;
  41924. break;
  41925. } // deliver the NAL unit if it isn't empty
  41926. if (syncPoint + 3 !== i - 2) {
  41927. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  41928. } // drop trailing zeroes
  41929. do {
  41930. i++;
  41931. } while (buffer[i] !== 1 && i < len);
  41932. syncPoint = i - 2;
  41933. i += 3;
  41934. break;
  41935. case 1:
  41936. // skip past non-sync sequences
  41937. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  41938. i += 3;
  41939. break;
  41940. } // deliver the NAL unit
  41941. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  41942. syncPoint = i - 2;
  41943. i += 3;
  41944. break;
  41945. default:
  41946. // the current byte isn't a one or zero, so it cannot be part
  41947. // of a sync sequence
  41948. i += 3;
  41949. break;
  41950. }
  41951. } // filter out the NAL units that were delivered
  41952. buffer = buffer.subarray(syncPoint);
  41953. i -= syncPoint;
  41954. syncPoint = 0;
  41955. };
  41956. this.reset = function () {
  41957. buffer = null;
  41958. syncPoint = 0;
  41959. this.trigger('reset');
  41960. };
  41961. this.flush = function () {
  41962. // deliver the last buffered NAL unit
  41963. if (buffer && buffer.byteLength > 3) {
  41964. this.trigger('data', buffer.subarray(syncPoint + 3));
  41965. } // reset the stream state
  41966. buffer = null;
  41967. syncPoint = 0;
  41968. this.trigger('done');
  41969. };
  41970. this.endTimeline = function () {
  41971. this.flush();
  41972. this.trigger('endedtimeline');
  41973. };
  41974. };
  41975. NalByteStream.prototype = new Stream$2(); // values of profile_idc that indicate additional fields are included in the SPS
  41976. // see Recommendation ITU-T H.264 (4/2013),
  41977. // 7.3.2.1.1 Sequence parameter set data syntax
  41978. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  41979. 100: true,
  41980. 110: true,
  41981. 122: true,
  41982. 244: true,
  41983. 44: true,
  41984. 83: true,
  41985. 86: true,
  41986. 118: true,
  41987. 128: true,
  41988. // TODO: the three profiles below don't
  41989. // appear to have sps data in the specificiation anymore?
  41990. 138: true,
  41991. 139: true,
  41992. 134: true
  41993. };
  41994. /**
  41995. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  41996. * events.
  41997. */
  41998. H264Stream$1 = function () {
  41999. var nalByteStream = new NalByteStream(),
  42000. self,
  42001. trackId,
  42002. currentPts,
  42003. currentDts,
  42004. discardEmulationPreventionBytes,
  42005. readSequenceParameterSet,
  42006. skipScalingList;
  42007. H264Stream$1.prototype.init.call(this);
  42008. self = this;
  42009. /*
  42010. * Pushes a packet from a stream onto the NalByteStream
  42011. *
  42012. * @param {Object} packet - A packet received from a stream
  42013. * @param {Uint8Array} packet.data - The raw bytes of the packet
  42014. * @param {Number} packet.dts - Decode timestamp of the packet
  42015. * @param {Number} packet.pts - Presentation timestamp of the packet
  42016. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  42017. * @param {('video'|'audio')} packet.type - The type of packet
  42018. *
  42019. */
  42020. this.push = function (packet) {
  42021. if (packet.type !== 'video') {
  42022. return;
  42023. }
  42024. trackId = packet.trackId;
  42025. currentPts = packet.pts;
  42026. currentDts = packet.dts;
  42027. nalByteStream.push(packet);
  42028. };
  42029. /*
  42030. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  42031. * for the NALUs to the next stream component.
  42032. * Also, preprocess caption and sequence parameter NALUs.
  42033. *
  42034. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  42035. * @see NalByteStream.push
  42036. */
  42037. nalByteStream.on('data', function (data) {
  42038. var event = {
  42039. trackId: trackId,
  42040. pts: currentPts,
  42041. dts: currentDts,
  42042. data: data,
  42043. nalUnitTypeCode: data[0] & 0x1f
  42044. };
  42045. switch (event.nalUnitTypeCode) {
  42046. case 0x05:
  42047. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  42048. break;
  42049. case 0x06:
  42050. event.nalUnitType = 'sei_rbsp';
  42051. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  42052. break;
  42053. case 0x07:
  42054. event.nalUnitType = 'seq_parameter_set_rbsp';
  42055. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  42056. event.config = readSequenceParameterSet(event.escapedRBSP);
  42057. break;
  42058. case 0x08:
  42059. event.nalUnitType = 'pic_parameter_set_rbsp';
  42060. break;
  42061. case 0x09:
  42062. event.nalUnitType = 'access_unit_delimiter_rbsp';
  42063. break;
  42064. } // This triggers data on the H264Stream
  42065. self.trigger('data', event);
  42066. });
  42067. nalByteStream.on('done', function () {
  42068. self.trigger('done');
  42069. });
  42070. nalByteStream.on('partialdone', function () {
  42071. self.trigger('partialdone');
  42072. });
  42073. nalByteStream.on('reset', function () {
  42074. self.trigger('reset');
  42075. });
  42076. nalByteStream.on('endedtimeline', function () {
  42077. self.trigger('endedtimeline');
  42078. });
  42079. this.flush = function () {
  42080. nalByteStream.flush();
  42081. };
  42082. this.partialFlush = function () {
  42083. nalByteStream.partialFlush();
  42084. };
  42085. this.reset = function () {
  42086. nalByteStream.reset();
  42087. };
  42088. this.endTimeline = function () {
  42089. nalByteStream.endTimeline();
  42090. };
  42091. /**
  42092. * Advance the ExpGolomb decoder past a scaling list. The scaling
  42093. * list is optionally transmitted as part of a sequence parameter
  42094. * set and is not relevant to transmuxing.
  42095. * @param count {number} the number of entries in this scaling list
  42096. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  42097. * start of a scaling list
  42098. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  42099. */
  42100. skipScalingList = function (count, expGolombDecoder) {
  42101. var lastScale = 8,
  42102. nextScale = 8,
  42103. j,
  42104. deltaScale;
  42105. for (j = 0; j < count; j++) {
  42106. if (nextScale !== 0) {
  42107. deltaScale = expGolombDecoder.readExpGolomb();
  42108. nextScale = (lastScale + deltaScale + 256) % 256;
  42109. }
  42110. lastScale = nextScale === 0 ? lastScale : nextScale;
  42111. }
  42112. };
  42113. /**
  42114. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  42115. * Sequence Payload"
  42116. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  42117. * unit
  42118. * @return {Uint8Array} the RBSP without any Emulation
  42119. * Prevention Bytes
  42120. */
  42121. discardEmulationPreventionBytes = function (data) {
  42122. var length = data.byteLength,
  42123. emulationPreventionBytesPositions = [],
  42124. i = 1,
  42125. newLength,
  42126. newData; // Find all `Emulation Prevention Bytes`
  42127. while (i < length - 2) {
  42128. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  42129. emulationPreventionBytesPositions.push(i + 2);
  42130. i += 2;
  42131. } else {
  42132. i++;
  42133. }
  42134. } // If no Emulation Prevention Bytes were found just return the original
  42135. // array
  42136. if (emulationPreventionBytesPositions.length === 0) {
  42137. return data;
  42138. } // Create a new array to hold the NAL unit data
  42139. newLength = length - emulationPreventionBytesPositions.length;
  42140. newData = new Uint8Array(newLength);
  42141. var sourceIndex = 0;
  42142. for (i = 0; i < newLength; sourceIndex++, i++) {
  42143. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  42144. // Skip this byte
  42145. sourceIndex++; // Remove this position index
  42146. emulationPreventionBytesPositions.shift();
  42147. }
  42148. newData[i] = data[sourceIndex];
  42149. }
  42150. return newData;
  42151. };
  42152. /**
  42153. * Read a sequence parameter set and return some interesting video
  42154. * properties. A sequence parameter set is the H264 metadata that
  42155. * describes the properties of upcoming video frames.
  42156. * @param data {Uint8Array} the bytes of a sequence parameter set
  42157. * @return {object} an object with configuration parsed from the
  42158. * sequence parameter set, including the dimensions of the
  42159. * associated video frames.
  42160. */
  42161. readSequenceParameterSet = function (data) {
  42162. var frameCropLeftOffset = 0,
  42163. frameCropRightOffset = 0,
  42164. frameCropTopOffset = 0,
  42165. frameCropBottomOffset = 0,
  42166. expGolombDecoder,
  42167. profileIdc,
  42168. levelIdc,
  42169. profileCompatibility,
  42170. chromaFormatIdc,
  42171. picOrderCntType,
  42172. numRefFramesInPicOrderCntCycle,
  42173. picWidthInMbsMinus1,
  42174. picHeightInMapUnitsMinus1,
  42175. frameMbsOnlyFlag,
  42176. scalingListCount,
  42177. sarRatio = [1, 1],
  42178. aspectRatioIdc,
  42179. i;
  42180. expGolombDecoder = new ExpGolomb(data);
  42181. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  42182. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  42183. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  42184. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  42185. // some profiles have more optional data we don't need
  42186. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  42187. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  42188. if (chromaFormatIdc === 3) {
  42189. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  42190. }
  42191. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  42192. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  42193. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  42194. if (expGolombDecoder.readBoolean()) {
  42195. // seq_scaling_matrix_present_flag
  42196. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  42197. for (i = 0; i < scalingListCount; i++) {
  42198. if (expGolombDecoder.readBoolean()) {
  42199. // seq_scaling_list_present_flag[ i ]
  42200. if (i < 6) {
  42201. skipScalingList(16, expGolombDecoder);
  42202. } else {
  42203. skipScalingList(64, expGolombDecoder);
  42204. }
  42205. }
  42206. }
  42207. }
  42208. }
  42209. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  42210. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  42211. if (picOrderCntType === 0) {
  42212. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  42213. } else if (picOrderCntType === 1) {
  42214. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  42215. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  42216. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  42217. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  42218. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  42219. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  42220. }
  42221. }
  42222. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  42223. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  42224. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  42225. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  42226. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  42227. if (frameMbsOnlyFlag === 0) {
  42228. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  42229. }
  42230. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  42231. if (expGolombDecoder.readBoolean()) {
  42232. // frame_cropping_flag
  42233. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  42234. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  42235. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  42236. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  42237. }
  42238. if (expGolombDecoder.readBoolean()) {
  42239. // vui_parameters_present_flag
  42240. if (expGolombDecoder.readBoolean()) {
  42241. // aspect_ratio_info_present_flag
  42242. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  42243. switch (aspectRatioIdc) {
  42244. case 1:
  42245. sarRatio = [1, 1];
  42246. break;
  42247. case 2:
  42248. sarRatio = [12, 11];
  42249. break;
  42250. case 3:
  42251. sarRatio = [10, 11];
  42252. break;
  42253. case 4:
  42254. sarRatio = [16, 11];
  42255. break;
  42256. case 5:
  42257. sarRatio = [40, 33];
  42258. break;
  42259. case 6:
  42260. sarRatio = [24, 11];
  42261. break;
  42262. case 7:
  42263. sarRatio = [20, 11];
  42264. break;
  42265. case 8:
  42266. sarRatio = [32, 11];
  42267. break;
  42268. case 9:
  42269. sarRatio = [80, 33];
  42270. break;
  42271. case 10:
  42272. sarRatio = [18, 11];
  42273. break;
  42274. case 11:
  42275. sarRatio = [15, 11];
  42276. break;
  42277. case 12:
  42278. sarRatio = [64, 33];
  42279. break;
  42280. case 13:
  42281. sarRatio = [160, 99];
  42282. break;
  42283. case 14:
  42284. sarRatio = [4, 3];
  42285. break;
  42286. case 15:
  42287. sarRatio = [3, 2];
  42288. break;
  42289. case 16:
  42290. sarRatio = [2, 1];
  42291. break;
  42292. case 255:
  42293. {
  42294. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  42295. break;
  42296. }
  42297. }
  42298. if (sarRatio) {
  42299. sarRatio[0] / sarRatio[1];
  42300. }
  42301. }
  42302. }
  42303. return {
  42304. profileIdc: profileIdc,
  42305. levelIdc: levelIdc,
  42306. profileCompatibility: profileCompatibility,
  42307. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  42308. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  42309. // sar is sample aspect ratio
  42310. sarRatio: sarRatio
  42311. };
  42312. };
  42313. };
  42314. H264Stream$1.prototype = new Stream$2();
  42315. var h264 = {
  42316. H264Stream: H264Stream$1,
  42317. NalByteStream: NalByteStream
  42318. };
  42319. /**
  42320. * mux.js
  42321. *
  42322. * Copyright (c) Brightcove
  42323. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  42324. *
  42325. * Utilities to detect basic properties and metadata about Aac data.
  42326. */
  42327. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  42328. var parseId3TagSize = function (header, byteIndex) {
  42329. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  42330. flags = header[byteIndex + 5],
  42331. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  42332. returnSize = returnSize >= 0 ? returnSize : 0;
  42333. if (footerPresent) {
  42334. return returnSize + 20;
  42335. }
  42336. return returnSize + 10;
  42337. };
  42338. var getId3Offset = function (data, offset) {
  42339. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  42340. return offset;
  42341. }
  42342. offset += parseId3TagSize(data, offset);
  42343. return getId3Offset(data, offset);
  42344. }; // TODO: use vhs-utils
  42345. var isLikelyAacData$1 = function (data) {
  42346. var offset = getId3Offset(data, 0);
  42347. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 &&
  42348. // verify that the 2 layer bits are 0, aka this
  42349. // is not mp3 data but aac data.
  42350. (data[offset + 1] & 0x16) === 0x10;
  42351. };
  42352. var parseSyncSafeInteger = function (data) {
  42353. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  42354. }; // return a percent-encoded representation of the specified byte range
  42355. // @see http://en.wikipedia.org/wiki/Percent-encoding
  42356. var percentEncode = function (bytes, start, end) {
  42357. var i,
  42358. result = '';
  42359. for (i = start; i < end; i++) {
  42360. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  42361. }
  42362. return result;
  42363. }; // return the string representation of the specified byte range,
  42364. // interpreted as ISO-8859-1.
  42365. var parseIso88591 = function (bytes, start, end) {
  42366. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  42367. };
  42368. var parseAdtsSize = function (header, byteIndex) {
  42369. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  42370. middle = header[byteIndex + 4] << 3,
  42371. highTwo = header[byteIndex + 3] & 0x3 << 11;
  42372. return highTwo | middle | lowThree;
  42373. };
  42374. var parseType$4 = function (header, byteIndex) {
  42375. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  42376. return 'timed-metadata';
  42377. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  42378. return 'audio';
  42379. }
  42380. return null;
  42381. };
  42382. var parseSampleRate = function (packet) {
  42383. var i = 0;
  42384. while (i + 5 < packet.length) {
  42385. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  42386. // If a valid header was not found, jump one forward and attempt to
  42387. // find a valid ADTS header starting at the next byte
  42388. i++;
  42389. continue;
  42390. }
  42391. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  42392. }
  42393. return null;
  42394. };
  42395. var parseAacTimestamp = function (packet) {
  42396. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  42397. frameStart = 10;
  42398. if (packet[5] & 0x40) {
  42399. // advance the frame start past the extended header
  42400. frameStart += 4; // header size field
  42401. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  42402. } // parse one or more ID3 frames
  42403. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  42404. do {
  42405. // determine the number of bytes in this frame
  42406. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  42407. if (frameSize < 1) {
  42408. return null;
  42409. }
  42410. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  42411. if (frameHeader === 'PRIV') {
  42412. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  42413. for (var i = 0; i < frame.byteLength; i++) {
  42414. if (frame[i] === 0) {
  42415. var owner = parseIso88591(frame, 0, i);
  42416. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  42417. var d = frame.subarray(i + 1);
  42418. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  42419. size *= 4;
  42420. size += d[7] & 0x03;
  42421. return size;
  42422. }
  42423. break;
  42424. }
  42425. }
  42426. }
  42427. frameStart += 10; // advance past the frame header
  42428. frameStart += frameSize; // advance past the frame body
  42429. } while (frameStart < packet.byteLength);
  42430. return null;
  42431. };
  42432. var utils = {
  42433. isLikelyAacData: isLikelyAacData$1,
  42434. parseId3TagSize: parseId3TagSize,
  42435. parseAdtsSize: parseAdtsSize,
  42436. parseType: parseType$4,
  42437. parseSampleRate: parseSampleRate,
  42438. parseAacTimestamp: parseAacTimestamp
  42439. };
  42440. /**
  42441. * mux.js
  42442. *
  42443. * Copyright (c) Brightcove
  42444. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  42445. *
  42446. * A stream-based aac to mp4 converter. This utility can be used to
  42447. * deliver mp4s to a SourceBuffer on platforms that support native
  42448. * Media Source Extensions.
  42449. */
  42450. var Stream$1 = stream;
  42451. var aacUtils = utils; // Constants
  42452. var AacStream$1;
  42453. /**
  42454. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  42455. */
  42456. AacStream$1 = function () {
  42457. var everything = new Uint8Array(),
  42458. timeStamp = 0;
  42459. AacStream$1.prototype.init.call(this);
  42460. this.setTimestamp = function (timestamp) {
  42461. timeStamp = timestamp;
  42462. };
  42463. this.push = function (bytes) {
  42464. var frameSize = 0,
  42465. byteIndex = 0,
  42466. bytesLeft,
  42467. chunk,
  42468. packet,
  42469. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  42470. // bytes that were pushed in
  42471. if (everything.length) {
  42472. tempLength = everything.length;
  42473. everything = new Uint8Array(bytes.byteLength + tempLength);
  42474. everything.set(everything.subarray(0, tempLength));
  42475. everything.set(bytes, tempLength);
  42476. } else {
  42477. everything = bytes;
  42478. }
  42479. while (everything.length - byteIndex >= 3) {
  42480. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  42481. // Exit early because we don't have enough to parse
  42482. // the ID3 tag header
  42483. if (everything.length - byteIndex < 10) {
  42484. break;
  42485. } // check framesize
  42486. frameSize = aacUtils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  42487. // to emit a full packet
  42488. // Add to byteIndex to support multiple ID3 tags in sequence
  42489. if (byteIndex + frameSize > everything.length) {
  42490. break;
  42491. }
  42492. chunk = {
  42493. type: 'timed-metadata',
  42494. data: everything.subarray(byteIndex, byteIndex + frameSize)
  42495. };
  42496. this.trigger('data', chunk);
  42497. byteIndex += frameSize;
  42498. continue;
  42499. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  42500. // Exit early because we don't have enough to parse
  42501. // the ADTS frame header
  42502. if (everything.length - byteIndex < 7) {
  42503. break;
  42504. }
  42505. frameSize = aacUtils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  42506. // to emit a full packet
  42507. if (byteIndex + frameSize > everything.length) {
  42508. break;
  42509. }
  42510. packet = {
  42511. type: 'audio',
  42512. data: everything.subarray(byteIndex, byteIndex + frameSize),
  42513. pts: timeStamp,
  42514. dts: timeStamp
  42515. };
  42516. this.trigger('data', packet);
  42517. byteIndex += frameSize;
  42518. continue;
  42519. }
  42520. byteIndex++;
  42521. }
  42522. bytesLeft = everything.length - byteIndex;
  42523. if (bytesLeft > 0) {
  42524. everything = everything.subarray(byteIndex);
  42525. } else {
  42526. everything = new Uint8Array();
  42527. }
  42528. };
  42529. this.reset = function () {
  42530. everything = new Uint8Array();
  42531. this.trigger('reset');
  42532. };
  42533. this.endTimeline = function () {
  42534. everything = new Uint8Array();
  42535. this.trigger('endedtimeline');
  42536. };
  42537. };
  42538. AacStream$1.prototype = new Stream$1();
  42539. var aac = AacStream$1;
  42540. var AUDIO_PROPERTIES$1 = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  42541. var audioProperties = AUDIO_PROPERTIES$1;
  42542. var VIDEO_PROPERTIES$1 = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  42543. var videoProperties = VIDEO_PROPERTIES$1;
  42544. /**
  42545. * mux.js
  42546. *
  42547. * Copyright (c) Brightcove
  42548. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  42549. *
  42550. * A stream-based mp2t to mp4 converter. This utility can be used to
  42551. * deliver mp4s to a SourceBuffer on platforms that support native
  42552. * Media Source Extensions.
  42553. */
  42554. var Stream = stream;
  42555. var mp4 = mp4Generator;
  42556. var frameUtils = frameUtils$1;
  42557. var audioFrameUtils = audioFrameUtils$1;
  42558. var trackDecodeInfo = trackDecodeInfo$1;
  42559. var m2ts = m2ts_1;
  42560. var clock = clock$2;
  42561. var AdtsStream = adts;
  42562. var H264Stream = h264.H264Stream;
  42563. var AacStream = aac;
  42564. var isLikelyAacData = utils.isLikelyAacData;
  42565. var ONE_SECOND_IN_TS$1 = clock$2.ONE_SECOND_IN_TS;
  42566. var AUDIO_PROPERTIES = audioProperties;
  42567. var VIDEO_PROPERTIES = videoProperties; // object types
  42568. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  42569. var retriggerForStream = function (key, event) {
  42570. event.stream = key;
  42571. this.trigger('log', event);
  42572. };
  42573. var addPipelineLogRetriggers = function (transmuxer, pipeline) {
  42574. var keys = Object.keys(pipeline);
  42575. for (var i = 0; i < keys.length; i++) {
  42576. var key = keys[i]; // skip non-stream keys and headOfPipeline
  42577. // which is just a duplicate
  42578. if (key === 'headOfPipeline' || !pipeline[key].on) {
  42579. continue;
  42580. }
  42581. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  42582. }
  42583. };
  42584. /**
  42585. * Compare two arrays (even typed) for same-ness
  42586. */
  42587. var arrayEquals = function (a, b) {
  42588. var i;
  42589. if (a.length !== b.length) {
  42590. return false;
  42591. } // compare the value of each element in the array
  42592. for (i = 0; i < a.length; i++) {
  42593. if (a[i] !== b[i]) {
  42594. return false;
  42595. }
  42596. }
  42597. return true;
  42598. };
  42599. var generateSegmentTimingInfo = function (baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  42600. var ptsOffsetFromDts = startPts - startDts,
  42601. decodeDuration = endDts - startDts,
  42602. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  42603. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  42604. // In order to provide relevant values for the player times, base timing info on the
  42605. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  42606. return {
  42607. start: {
  42608. dts: baseMediaDecodeTime,
  42609. pts: baseMediaDecodeTime + ptsOffsetFromDts
  42610. },
  42611. end: {
  42612. dts: baseMediaDecodeTime + decodeDuration,
  42613. pts: baseMediaDecodeTime + presentationDuration
  42614. },
  42615. prependedContentDuration: prependedContentDuration,
  42616. baseMediaDecodeTime: baseMediaDecodeTime
  42617. };
  42618. };
  42619. /**
  42620. * Constructs a single-track, ISO BMFF media segment from AAC data
  42621. * events. The output of this stream can be fed to a SourceBuffer
  42622. * configured with a suitable initialization segment.
  42623. * @param track {object} track metadata configuration
  42624. * @param options {object} transmuxer options object
  42625. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  42626. * in the source; false to adjust the first segment to start at 0.
  42627. */
  42628. AudioSegmentStream = function (track, options) {
  42629. var adtsFrames = [],
  42630. sequenceNumber,
  42631. earliestAllowedDts = 0,
  42632. audioAppendStartTs = 0,
  42633. videoBaseMediaDecodeTime = Infinity;
  42634. options = options || {};
  42635. sequenceNumber = options.firstSequenceNumber || 0;
  42636. AudioSegmentStream.prototype.init.call(this);
  42637. this.push = function (data) {
  42638. trackDecodeInfo.collectDtsInfo(track, data);
  42639. if (track) {
  42640. AUDIO_PROPERTIES.forEach(function (prop) {
  42641. track[prop] = data[prop];
  42642. });
  42643. } // buffer audio data until end() is called
  42644. adtsFrames.push(data);
  42645. };
  42646. this.setEarliestDts = function (earliestDts) {
  42647. earliestAllowedDts = earliestDts;
  42648. };
  42649. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  42650. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  42651. };
  42652. this.setAudioAppendStart = function (timestamp) {
  42653. audioAppendStartTs = timestamp;
  42654. };
  42655. this.flush = function () {
  42656. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  42657. if (adtsFrames.length === 0) {
  42658. this.trigger('done', 'AudioSegmentStream');
  42659. return;
  42660. }
  42661. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  42662. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  42663. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  42664. // samples (that is, adts frames) in the audio data
  42665. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  42666. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  42667. adtsFrames = [];
  42668. moof = mp4.moof(sequenceNumber, [track]);
  42669. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  42670. sequenceNumber++;
  42671. boxes.set(moof);
  42672. boxes.set(mdat, moof.byteLength);
  42673. trackDecodeInfo.clearDtsInfo(track);
  42674. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  42675. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  42676. // valid use-case where an init segment/data should be triggered without associated
  42677. // frames. Leaving for now, but should be looked into.
  42678. if (frames.length) {
  42679. segmentDuration = frames.length * frameDuration;
  42680. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(
  42681. // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  42682. // frame info is in video clock cycles. Convert to match expectation of
  42683. // listeners (that all timestamps will be based on video clock cycles).
  42684. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate),
  42685. // frame times are already in video clock, as is segment duration
  42686. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  42687. this.trigger('timingInfo', {
  42688. start: frames[0].pts,
  42689. end: frames[0].pts + segmentDuration
  42690. });
  42691. }
  42692. this.trigger('data', {
  42693. track: track,
  42694. boxes: boxes
  42695. });
  42696. this.trigger('done', 'AudioSegmentStream');
  42697. };
  42698. this.reset = function () {
  42699. trackDecodeInfo.clearDtsInfo(track);
  42700. adtsFrames = [];
  42701. this.trigger('reset');
  42702. };
  42703. };
  42704. AudioSegmentStream.prototype = new Stream();
  42705. /**
  42706. * Constructs a single-track, ISO BMFF media segment from H264 data
  42707. * events. The output of this stream can be fed to a SourceBuffer
  42708. * configured with a suitable initialization segment.
  42709. * @param track {object} track metadata configuration
  42710. * @param options {object} transmuxer options object
  42711. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  42712. * gopsToAlignWith list when attempting to align gop pts
  42713. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  42714. * in the source; false to adjust the first segment to start at 0.
  42715. */
  42716. VideoSegmentStream = function (track, options) {
  42717. var sequenceNumber,
  42718. nalUnits = [],
  42719. gopsToAlignWith = [],
  42720. config,
  42721. pps;
  42722. options = options || {};
  42723. sequenceNumber = options.firstSequenceNumber || 0;
  42724. VideoSegmentStream.prototype.init.call(this);
  42725. delete track.minPTS;
  42726. this.gopCache_ = [];
  42727. /**
  42728. * Constructs a ISO BMFF segment given H264 nalUnits
  42729. * @param {Object} nalUnit A data event representing a nalUnit
  42730. * @param {String} nalUnit.nalUnitType
  42731. * @param {Object} nalUnit.config Properties for a mp4 track
  42732. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  42733. * @see lib/codecs/h264.js
  42734. **/
  42735. this.push = function (nalUnit) {
  42736. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  42737. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  42738. config = nalUnit.config;
  42739. track.sps = [nalUnit.data];
  42740. VIDEO_PROPERTIES.forEach(function (prop) {
  42741. track[prop] = config[prop];
  42742. }, this);
  42743. }
  42744. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  42745. pps = nalUnit.data;
  42746. track.pps = [nalUnit.data];
  42747. } // buffer video until flush() is called
  42748. nalUnits.push(nalUnit);
  42749. };
  42750. /**
  42751. * Pass constructed ISO BMFF track and boxes on to the
  42752. * next stream in the pipeline
  42753. **/
  42754. this.flush = function () {
  42755. var frames,
  42756. gopForFusion,
  42757. gops,
  42758. moof,
  42759. mdat,
  42760. boxes,
  42761. prependedContentDuration = 0,
  42762. firstGop,
  42763. lastGop; // Throw away nalUnits at the start of the byte stream until
  42764. // we find the first AUD
  42765. while (nalUnits.length) {
  42766. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  42767. break;
  42768. }
  42769. nalUnits.shift();
  42770. } // Return early if no video data has been observed
  42771. if (nalUnits.length === 0) {
  42772. this.resetStream_();
  42773. this.trigger('done', 'VideoSegmentStream');
  42774. return;
  42775. } // Organize the raw nal-units into arrays that represent
  42776. // higher-level constructs such as frames and gops
  42777. // (group-of-pictures)
  42778. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  42779. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  42780. // a problem since MSE (on Chrome) requires a leading keyframe.
  42781. //
  42782. // We have two approaches to repairing this situation:
  42783. // 1) GOP-FUSION:
  42784. // This is where we keep track of the GOPS (group-of-pictures)
  42785. // from previous fragments and attempt to find one that we can
  42786. // prepend to the current fragment in order to create a valid
  42787. // fragment.
  42788. // 2) KEYFRAME-PULLING:
  42789. // Here we search for the first keyframe in the fragment and
  42790. // throw away all the frames between the start of the fragment
  42791. // and that keyframe. We then extend the duration and pull the
  42792. // PTS of the keyframe forward so that it covers the time range
  42793. // of the frames that were disposed of.
  42794. //
  42795. // #1 is far prefereable over #2 which can cause "stuttering" but
  42796. // requires more things to be just right.
  42797. if (!gops[0][0].keyFrame) {
  42798. // Search for a gop for fusion from our gopCache
  42799. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  42800. if (gopForFusion) {
  42801. // in order to provide more accurate timing information about the segment, save
  42802. // the number of seconds prepended to the original segment due to GOP fusion
  42803. prependedContentDuration = gopForFusion.duration;
  42804. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  42805. // new gop at the beginning
  42806. gops.byteLength += gopForFusion.byteLength;
  42807. gops.nalCount += gopForFusion.nalCount;
  42808. gops.pts = gopForFusion.pts;
  42809. gops.dts = gopForFusion.dts;
  42810. gops.duration += gopForFusion.duration;
  42811. } else {
  42812. // If we didn't find a candidate gop fall back to keyframe-pulling
  42813. gops = frameUtils.extendFirstKeyFrame(gops);
  42814. }
  42815. } // Trim gops to align with gopsToAlignWith
  42816. if (gopsToAlignWith.length) {
  42817. var alignedGops;
  42818. if (options.alignGopsAtEnd) {
  42819. alignedGops = this.alignGopsAtEnd_(gops);
  42820. } else {
  42821. alignedGops = this.alignGopsAtStart_(gops);
  42822. }
  42823. if (!alignedGops) {
  42824. // save all the nals in the last GOP into the gop cache
  42825. this.gopCache_.unshift({
  42826. gop: gops.pop(),
  42827. pps: track.pps,
  42828. sps: track.sps
  42829. }); // Keep a maximum of 6 GOPs in the cache
  42830. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  42831. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  42832. this.resetStream_();
  42833. this.trigger('done', 'VideoSegmentStream');
  42834. return;
  42835. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  42836. // when recalculated before sending off to CoalesceStream
  42837. trackDecodeInfo.clearDtsInfo(track);
  42838. gops = alignedGops;
  42839. }
  42840. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  42841. // samples (that is, frames) in the video data
  42842. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  42843. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  42844. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  42845. this.trigger('processedGopsInfo', gops.map(function (gop) {
  42846. return {
  42847. pts: gop.pts,
  42848. dts: gop.dts,
  42849. byteLength: gop.byteLength
  42850. };
  42851. }));
  42852. firstGop = gops[0];
  42853. lastGop = gops[gops.length - 1];
  42854. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  42855. this.trigger('timingInfo', {
  42856. start: gops[0].pts,
  42857. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  42858. }); // save all the nals in the last GOP into the gop cache
  42859. this.gopCache_.unshift({
  42860. gop: gops.pop(),
  42861. pps: track.pps,
  42862. sps: track.sps
  42863. }); // Keep a maximum of 6 GOPs in the cache
  42864. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  42865. nalUnits = [];
  42866. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  42867. this.trigger('timelineStartInfo', track.timelineStartInfo);
  42868. moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  42869. // throwing away hundreds of media segment fragments
  42870. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  42871. sequenceNumber++;
  42872. boxes.set(moof);
  42873. boxes.set(mdat, moof.byteLength);
  42874. this.trigger('data', {
  42875. track: track,
  42876. boxes: boxes
  42877. });
  42878. this.resetStream_(); // Continue with the flush process now
  42879. this.trigger('done', 'VideoSegmentStream');
  42880. };
  42881. this.reset = function () {
  42882. this.resetStream_();
  42883. nalUnits = [];
  42884. this.gopCache_.length = 0;
  42885. gopsToAlignWith.length = 0;
  42886. this.trigger('reset');
  42887. };
  42888. this.resetStream_ = function () {
  42889. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  42890. // for instance, when we are rendition switching
  42891. config = undefined;
  42892. pps = undefined;
  42893. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  42894. // return it or return null if no good candidate was found
  42895. this.getGopForFusion_ = function (nalUnit) {
  42896. var halfSecond = 45000,
  42897. // Half-a-second in a 90khz clock
  42898. allowableOverlap = 10000,
  42899. // About 3 frames @ 30fps
  42900. nearestDistance = Infinity,
  42901. dtsDistance,
  42902. nearestGopObj,
  42903. currentGop,
  42904. currentGopObj,
  42905. i; // Search for the GOP nearest to the beginning of this nal unit
  42906. for (i = 0; i < this.gopCache_.length; i++) {
  42907. currentGopObj = this.gopCache_[i];
  42908. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  42909. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  42910. continue;
  42911. } // Reject Gops that would require a negative baseMediaDecodeTime
  42912. if (currentGop.dts < track.timelineStartInfo.dts) {
  42913. continue;
  42914. } // The distance between the end of the gop and the start of the nalUnit
  42915. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  42916. // a half-second of the nal unit
  42917. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  42918. // Always use the closest GOP we found if there is more than
  42919. // one candidate
  42920. if (!nearestGopObj || nearestDistance > dtsDistance) {
  42921. nearestGopObj = currentGopObj;
  42922. nearestDistance = dtsDistance;
  42923. }
  42924. }
  42925. }
  42926. if (nearestGopObj) {
  42927. return nearestGopObj.gop;
  42928. }
  42929. return null;
  42930. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  42931. // of gopsToAlignWith starting from the START of the list
  42932. this.alignGopsAtStart_ = function (gops) {
  42933. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  42934. byteLength = gops.byteLength;
  42935. nalCount = gops.nalCount;
  42936. duration = gops.duration;
  42937. alignIndex = gopIndex = 0;
  42938. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  42939. align = gopsToAlignWith[alignIndex];
  42940. gop = gops[gopIndex];
  42941. if (align.pts === gop.pts) {
  42942. break;
  42943. }
  42944. if (gop.pts > align.pts) {
  42945. // this current gop starts after the current gop we want to align on, so increment
  42946. // align index
  42947. alignIndex++;
  42948. continue;
  42949. } // current gop starts before the current gop we want to align on. so increment gop
  42950. // index
  42951. gopIndex++;
  42952. byteLength -= gop.byteLength;
  42953. nalCount -= gop.nalCount;
  42954. duration -= gop.duration;
  42955. }
  42956. if (gopIndex === 0) {
  42957. // no gops to trim
  42958. return gops;
  42959. }
  42960. if (gopIndex === gops.length) {
  42961. // all gops trimmed, skip appending all gops
  42962. return null;
  42963. }
  42964. alignedGops = gops.slice(gopIndex);
  42965. alignedGops.byteLength = byteLength;
  42966. alignedGops.duration = duration;
  42967. alignedGops.nalCount = nalCount;
  42968. alignedGops.pts = alignedGops[0].pts;
  42969. alignedGops.dts = alignedGops[0].dts;
  42970. return alignedGops;
  42971. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  42972. // of gopsToAlignWith starting from the END of the list
  42973. this.alignGopsAtEnd_ = function (gops) {
  42974. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  42975. alignIndex = gopsToAlignWith.length - 1;
  42976. gopIndex = gops.length - 1;
  42977. alignEndIndex = null;
  42978. matchFound = false;
  42979. while (alignIndex >= 0 && gopIndex >= 0) {
  42980. align = gopsToAlignWith[alignIndex];
  42981. gop = gops[gopIndex];
  42982. if (align.pts === gop.pts) {
  42983. matchFound = true;
  42984. break;
  42985. }
  42986. if (align.pts > gop.pts) {
  42987. alignIndex--;
  42988. continue;
  42989. }
  42990. if (alignIndex === gopsToAlignWith.length - 1) {
  42991. // gop.pts is greater than the last alignment candidate. If no match is found
  42992. // by the end of this loop, we still want to append gops that come after this
  42993. // point
  42994. alignEndIndex = gopIndex;
  42995. }
  42996. gopIndex--;
  42997. }
  42998. if (!matchFound && alignEndIndex === null) {
  42999. return null;
  43000. }
  43001. var trimIndex;
  43002. if (matchFound) {
  43003. trimIndex = gopIndex;
  43004. } else {
  43005. trimIndex = alignEndIndex;
  43006. }
  43007. if (trimIndex === 0) {
  43008. return gops;
  43009. }
  43010. var alignedGops = gops.slice(trimIndex);
  43011. var metadata = alignedGops.reduce(function (total, gop) {
  43012. total.byteLength += gop.byteLength;
  43013. total.duration += gop.duration;
  43014. total.nalCount += gop.nalCount;
  43015. return total;
  43016. }, {
  43017. byteLength: 0,
  43018. duration: 0,
  43019. nalCount: 0
  43020. });
  43021. alignedGops.byteLength = metadata.byteLength;
  43022. alignedGops.duration = metadata.duration;
  43023. alignedGops.nalCount = metadata.nalCount;
  43024. alignedGops.pts = alignedGops[0].pts;
  43025. alignedGops.dts = alignedGops[0].dts;
  43026. return alignedGops;
  43027. };
  43028. this.alignGopsWith = function (newGopsToAlignWith) {
  43029. gopsToAlignWith = newGopsToAlignWith;
  43030. };
  43031. };
  43032. VideoSegmentStream.prototype = new Stream();
  43033. /**
  43034. * A Stream that can combine multiple streams (ie. audio & video)
  43035. * into a single output segment for MSE. Also supports audio-only
  43036. * and video-only streams.
  43037. * @param options {object} transmuxer options object
  43038. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  43039. * in the source; false to adjust the first segment to start at media timeline start.
  43040. */
  43041. CoalesceStream = function (options, metadataStream) {
  43042. // Number of Tracks per output segment
  43043. // If greater than 1, we combine multiple
  43044. // tracks into a single segment
  43045. this.numberOfTracks = 0;
  43046. this.metadataStream = metadataStream;
  43047. options = options || {};
  43048. if (typeof options.remux !== 'undefined') {
  43049. this.remuxTracks = !!options.remux;
  43050. } else {
  43051. this.remuxTracks = true;
  43052. }
  43053. if (typeof options.keepOriginalTimestamps === 'boolean') {
  43054. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  43055. } else {
  43056. this.keepOriginalTimestamps = false;
  43057. }
  43058. this.pendingTracks = [];
  43059. this.videoTrack = null;
  43060. this.pendingBoxes = [];
  43061. this.pendingCaptions = [];
  43062. this.pendingMetadata = [];
  43063. this.pendingBytes = 0;
  43064. this.emittedTracks = 0;
  43065. CoalesceStream.prototype.init.call(this); // Take output from multiple
  43066. this.push = function (output) {
  43067. // buffer incoming captions until the associated video segment
  43068. // finishes
  43069. if (output.text) {
  43070. return this.pendingCaptions.push(output);
  43071. } // buffer incoming id3 tags until the final flush
  43072. if (output.frames) {
  43073. return this.pendingMetadata.push(output);
  43074. } // Add this track to the list of pending tracks and store
  43075. // important information required for the construction of
  43076. // the final segment
  43077. this.pendingTracks.push(output.track);
  43078. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  43079. // We unshift audio and push video because
  43080. // as of Chrome 75 when switching from
  43081. // one init segment to another if the video
  43082. // mdat does not appear after the audio mdat
  43083. // only audio will play for the duration of our transmux.
  43084. if (output.track.type === 'video') {
  43085. this.videoTrack = output.track;
  43086. this.pendingBoxes.push(output.boxes);
  43087. }
  43088. if (output.track.type === 'audio') {
  43089. this.audioTrack = output.track;
  43090. this.pendingBoxes.unshift(output.boxes);
  43091. }
  43092. };
  43093. };
  43094. CoalesceStream.prototype = new Stream();
  43095. CoalesceStream.prototype.flush = function (flushSource) {
  43096. var offset = 0,
  43097. event = {
  43098. captions: [],
  43099. captionStreams: {},
  43100. metadata: [],
  43101. info: {}
  43102. },
  43103. caption,
  43104. id3,
  43105. initSegment,
  43106. timelineStartPts = 0,
  43107. i;
  43108. if (this.pendingTracks.length < this.numberOfTracks) {
  43109. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  43110. // Return because we haven't received a flush from a data-generating
  43111. // portion of the segment (meaning that we have only recieved meta-data
  43112. // or captions.)
  43113. return;
  43114. } else if (this.remuxTracks) {
  43115. // Return until we have enough tracks from the pipeline to remux (if we
  43116. // are remuxing audio and video into a single MP4)
  43117. return;
  43118. } else if (this.pendingTracks.length === 0) {
  43119. // In the case where we receive a flush without any data having been
  43120. // received we consider it an emitted track for the purposes of coalescing
  43121. // `done` events.
  43122. // We do this for the case where there is an audio and video track in the
  43123. // segment but no audio data. (seen in several playlists with alternate
  43124. // audio tracks and no audio present in the main TS segments.)
  43125. this.emittedTracks++;
  43126. if (this.emittedTracks >= this.numberOfTracks) {
  43127. this.trigger('done');
  43128. this.emittedTracks = 0;
  43129. }
  43130. return;
  43131. }
  43132. }
  43133. if (this.videoTrack) {
  43134. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  43135. VIDEO_PROPERTIES.forEach(function (prop) {
  43136. event.info[prop] = this.videoTrack[prop];
  43137. }, this);
  43138. } else if (this.audioTrack) {
  43139. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  43140. AUDIO_PROPERTIES.forEach(function (prop) {
  43141. event.info[prop] = this.audioTrack[prop];
  43142. }, this);
  43143. }
  43144. if (this.videoTrack || this.audioTrack) {
  43145. if (this.pendingTracks.length === 1) {
  43146. event.type = this.pendingTracks[0].type;
  43147. } else {
  43148. event.type = 'combined';
  43149. }
  43150. this.emittedTracks += this.pendingTracks.length;
  43151. initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  43152. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  43153. // and track definitions
  43154. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  43155. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  43156. for (i = 0; i < this.pendingBoxes.length; i++) {
  43157. event.data.set(this.pendingBoxes[i], offset);
  43158. offset += this.pendingBoxes[i].byteLength;
  43159. } // Translate caption PTS times into second offsets to match the
  43160. // video timeline for the segment, and add track info
  43161. for (i = 0; i < this.pendingCaptions.length; i++) {
  43162. caption = this.pendingCaptions[i];
  43163. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  43164. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  43165. event.captionStreams[caption.stream] = true;
  43166. event.captions.push(caption);
  43167. } // Translate ID3 frame PTS times into second offsets to match the
  43168. // video timeline for the segment
  43169. for (i = 0; i < this.pendingMetadata.length; i++) {
  43170. id3 = this.pendingMetadata[i];
  43171. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  43172. event.metadata.push(id3);
  43173. } // We add this to every single emitted segment even though we only need
  43174. // it for the first
  43175. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  43176. this.pendingTracks.length = 0;
  43177. this.videoTrack = null;
  43178. this.pendingBoxes.length = 0;
  43179. this.pendingCaptions.length = 0;
  43180. this.pendingBytes = 0;
  43181. this.pendingMetadata.length = 0; // Emit the built segment
  43182. // We include captions and ID3 tags for backwards compatibility,
  43183. // ideally we should send only video and audio in the data event
  43184. this.trigger('data', event); // Emit each caption to the outside world
  43185. // Ideally, this would happen immediately on parsing captions,
  43186. // but we need to ensure that video data is sent back first
  43187. // so that caption timing can be adjusted to match video timing
  43188. for (i = 0; i < event.captions.length; i++) {
  43189. caption = event.captions[i];
  43190. this.trigger('caption', caption);
  43191. } // Emit each id3 tag to the outside world
  43192. // Ideally, this would happen immediately on parsing the tag,
  43193. // but we need to ensure that video data is sent back first
  43194. // so that ID3 frame timing can be adjusted to match video timing
  43195. for (i = 0; i < event.metadata.length; i++) {
  43196. id3 = event.metadata[i];
  43197. this.trigger('id3Frame', id3);
  43198. }
  43199. } // Only emit `done` if all tracks have been flushed and emitted
  43200. if (this.emittedTracks >= this.numberOfTracks) {
  43201. this.trigger('done');
  43202. this.emittedTracks = 0;
  43203. }
  43204. };
  43205. CoalesceStream.prototype.setRemux = function (val) {
  43206. this.remuxTracks = val;
  43207. };
  43208. /**
  43209. * A Stream that expects MP2T binary data as input and produces
  43210. * corresponding media segments, suitable for use with Media Source
  43211. * Extension (MSE) implementations that support the ISO BMFF byte
  43212. * stream format, like Chrome.
  43213. */
  43214. Transmuxer = function (options) {
  43215. var self = this,
  43216. hasFlushed = true,
  43217. videoTrack,
  43218. audioTrack;
  43219. Transmuxer.prototype.init.call(this);
  43220. options = options || {};
  43221. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  43222. this.transmuxPipeline_ = {};
  43223. this.setupAacPipeline = function () {
  43224. var pipeline = {};
  43225. this.transmuxPipeline_ = pipeline;
  43226. pipeline.type = 'aac';
  43227. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  43228. pipeline.aacStream = new AacStream();
  43229. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  43230. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  43231. pipeline.adtsStream = new AdtsStream();
  43232. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  43233. pipeline.headOfPipeline = pipeline.aacStream;
  43234. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  43235. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  43236. pipeline.metadataStream.on('timestamp', function (frame) {
  43237. pipeline.aacStream.setTimestamp(frame.timeStamp);
  43238. });
  43239. pipeline.aacStream.on('data', function (data) {
  43240. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  43241. return;
  43242. }
  43243. audioTrack = audioTrack || {
  43244. timelineStartInfo: {
  43245. baseMediaDecodeTime: self.baseMediaDecodeTime
  43246. },
  43247. codec: 'adts',
  43248. type: 'audio'
  43249. }; // hook up the audio segment stream to the first track with aac data
  43250. pipeline.coalesceStream.numberOfTracks++;
  43251. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  43252. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  43253. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  43254. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  43255. self.trigger('trackinfo', {
  43256. hasAudio: !!audioTrack,
  43257. hasVideo: !!videoTrack
  43258. });
  43259. }); // Re-emit any data coming from the coalesce stream to the outside world
  43260. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  43261. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  43262. addPipelineLogRetriggers(this, pipeline);
  43263. };
  43264. this.setupTsPipeline = function () {
  43265. var pipeline = {};
  43266. this.transmuxPipeline_ = pipeline;
  43267. pipeline.type = 'ts';
  43268. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  43269. pipeline.packetStream = new m2ts.TransportPacketStream();
  43270. pipeline.parseStream = new m2ts.TransportParseStream();
  43271. pipeline.elementaryStream = new m2ts.ElementaryStream();
  43272. pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
  43273. pipeline.adtsStream = new AdtsStream();
  43274. pipeline.h264Stream = new H264Stream();
  43275. pipeline.captionStream = new m2ts.CaptionStream(options);
  43276. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  43277. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  43278. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  43279. // demux the streams
  43280. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  43281. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  43282. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  43283. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  43284. pipeline.elementaryStream.on('data', function (data) {
  43285. var i;
  43286. if (data.type === 'metadata') {
  43287. i = data.tracks.length; // scan the tracks listed in the metadata
  43288. while (i--) {
  43289. if (!videoTrack && data.tracks[i].type === 'video') {
  43290. videoTrack = data.tracks[i];
  43291. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  43292. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  43293. audioTrack = data.tracks[i];
  43294. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  43295. }
  43296. } // hook up the video segment stream to the first track with h264 data
  43297. if (videoTrack && !pipeline.videoSegmentStream) {
  43298. pipeline.coalesceStream.numberOfTracks++;
  43299. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  43300. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  43301. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  43302. // When video emits timelineStartInfo data after a flush, we forward that
  43303. // info to the AudioSegmentStream, if it exists, because video timeline
  43304. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  43305. // because this is a particularly subtle form of timestamp alteration.
  43306. if (audioTrack && !options.keepOriginalTimestamps) {
  43307. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  43308. // very earliest DTS we have seen in video because Chrome will
  43309. // interpret any video track with a baseMediaDecodeTime that is
  43310. // non-zero as a gap.
  43311. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  43312. }
  43313. });
  43314. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  43315. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  43316. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  43317. if (audioTrack) {
  43318. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  43319. }
  43320. });
  43321. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  43322. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  43323. }
  43324. if (audioTrack && !pipeline.audioSegmentStream) {
  43325. // hook up the audio segment stream to the first track with aac data
  43326. pipeline.coalesceStream.numberOfTracks++;
  43327. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  43328. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  43329. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  43330. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  43331. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  43332. } // emit pmt info
  43333. self.trigger('trackinfo', {
  43334. hasAudio: !!audioTrack,
  43335. hasVideo: !!videoTrack
  43336. });
  43337. }
  43338. }); // Re-emit any data coming from the coalesce stream to the outside world
  43339. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  43340. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  43341. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  43342. self.trigger('id3Frame', id3Frame);
  43343. });
  43344. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  43345. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  43346. addPipelineLogRetriggers(this, pipeline);
  43347. }; // hook up the segment streams once track metadata is delivered
  43348. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  43349. var pipeline = this.transmuxPipeline_;
  43350. if (!options.keepOriginalTimestamps) {
  43351. this.baseMediaDecodeTime = baseMediaDecodeTime;
  43352. }
  43353. if (audioTrack) {
  43354. audioTrack.timelineStartInfo.dts = undefined;
  43355. audioTrack.timelineStartInfo.pts = undefined;
  43356. trackDecodeInfo.clearDtsInfo(audioTrack);
  43357. if (pipeline.audioTimestampRolloverStream) {
  43358. pipeline.audioTimestampRolloverStream.discontinuity();
  43359. }
  43360. }
  43361. if (videoTrack) {
  43362. if (pipeline.videoSegmentStream) {
  43363. pipeline.videoSegmentStream.gopCache_ = [];
  43364. }
  43365. videoTrack.timelineStartInfo.dts = undefined;
  43366. videoTrack.timelineStartInfo.pts = undefined;
  43367. trackDecodeInfo.clearDtsInfo(videoTrack);
  43368. pipeline.captionStream.reset();
  43369. }
  43370. if (pipeline.timestampRolloverStream) {
  43371. pipeline.timestampRolloverStream.discontinuity();
  43372. }
  43373. };
  43374. this.setAudioAppendStart = function (timestamp) {
  43375. if (audioTrack) {
  43376. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  43377. }
  43378. };
  43379. this.setRemux = function (val) {
  43380. var pipeline = this.transmuxPipeline_;
  43381. options.remux = val;
  43382. if (pipeline && pipeline.coalesceStream) {
  43383. pipeline.coalesceStream.setRemux(val);
  43384. }
  43385. };
  43386. this.alignGopsWith = function (gopsToAlignWith) {
  43387. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  43388. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  43389. }
  43390. };
  43391. this.getLogTrigger_ = function (key) {
  43392. var self = this;
  43393. return function (event) {
  43394. event.stream = key;
  43395. self.trigger('log', event);
  43396. };
  43397. }; // feed incoming data to the front of the parsing pipeline
  43398. this.push = function (data) {
  43399. if (hasFlushed) {
  43400. var isAac = isLikelyAacData(data);
  43401. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  43402. this.setupAacPipeline();
  43403. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  43404. this.setupTsPipeline();
  43405. }
  43406. hasFlushed = false;
  43407. }
  43408. this.transmuxPipeline_.headOfPipeline.push(data);
  43409. }; // flush any buffered data
  43410. this.flush = function () {
  43411. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  43412. this.transmuxPipeline_.headOfPipeline.flush();
  43413. };
  43414. this.endTimeline = function () {
  43415. this.transmuxPipeline_.headOfPipeline.endTimeline();
  43416. };
  43417. this.reset = function () {
  43418. if (this.transmuxPipeline_.headOfPipeline) {
  43419. this.transmuxPipeline_.headOfPipeline.reset();
  43420. }
  43421. }; // Caption data has to be reset when seeking outside buffered range
  43422. this.resetCaptions = function () {
  43423. if (this.transmuxPipeline_.captionStream) {
  43424. this.transmuxPipeline_.captionStream.reset();
  43425. }
  43426. };
  43427. };
  43428. Transmuxer.prototype = new Stream();
  43429. var transmuxer = {
  43430. Transmuxer: Transmuxer,
  43431. VideoSegmentStream: VideoSegmentStream,
  43432. AudioSegmentStream: AudioSegmentStream,
  43433. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  43434. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  43435. // exported for testing
  43436. generateSegmentTimingInfo: generateSegmentTimingInfo
  43437. };
  43438. /**
  43439. * mux.js
  43440. *
  43441. * Copyright (c) Brightcove
  43442. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  43443. */
  43444. var toUnsigned$3 = function (value) {
  43445. return value >>> 0;
  43446. };
  43447. var toHexString$1 = function (value) {
  43448. return ('00' + value.toString(16)).slice(-2);
  43449. };
  43450. var bin = {
  43451. toUnsigned: toUnsigned$3,
  43452. toHexString: toHexString$1
  43453. };
  43454. var parseType$3 = function (buffer) {
  43455. var result = '';
  43456. result += String.fromCharCode(buffer[0]);
  43457. result += String.fromCharCode(buffer[1]);
  43458. result += String.fromCharCode(buffer[2]);
  43459. result += String.fromCharCode(buffer[3]);
  43460. return result;
  43461. };
  43462. var parseType_1 = parseType$3;
  43463. var toUnsigned$2 = bin.toUnsigned;
  43464. var parseType$2 = parseType_1;
  43465. var findBox$2 = function (data, path) {
  43466. var results = [],
  43467. i,
  43468. size,
  43469. type,
  43470. end,
  43471. subresults;
  43472. if (!path.length) {
  43473. // short-circuit the search for empty paths
  43474. return null;
  43475. }
  43476. for (i = 0; i < data.byteLength;) {
  43477. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  43478. type = parseType$2(data.subarray(i + 4, i + 8));
  43479. end = size > 1 ? i + size : data.byteLength;
  43480. if (type === path[0]) {
  43481. if (path.length === 1) {
  43482. // this is the end of the path and we've found the box we were
  43483. // looking for
  43484. results.push(data.subarray(i + 8, end));
  43485. } else {
  43486. // recursively search for the next box along the path
  43487. subresults = findBox$2(data.subarray(i + 8, end), path.slice(1));
  43488. if (subresults.length) {
  43489. results = results.concat(subresults);
  43490. }
  43491. }
  43492. }
  43493. i = end;
  43494. } // we've finished searching all of data
  43495. return results;
  43496. };
  43497. var findBox_1 = findBox$2;
  43498. var toUnsigned$1 = bin.toUnsigned;
  43499. var getUint64$2 = numbers.getUint64;
  43500. var tfdt = function (data) {
  43501. var result = {
  43502. version: data[0],
  43503. flags: new Uint8Array(data.subarray(1, 4))
  43504. };
  43505. if (result.version === 1) {
  43506. result.baseMediaDecodeTime = getUint64$2(data.subarray(4));
  43507. } else {
  43508. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  43509. }
  43510. return result;
  43511. };
  43512. var parseTfdt$2 = tfdt;
  43513. var parseSampleFlags$1 = function (flags) {
  43514. return {
  43515. isLeading: (flags[0] & 0x0c) >>> 2,
  43516. dependsOn: flags[0] & 0x03,
  43517. isDependedOn: (flags[1] & 0xc0) >>> 6,
  43518. hasRedundancy: (flags[1] & 0x30) >>> 4,
  43519. paddingValue: (flags[1] & 0x0e) >>> 1,
  43520. isNonSyncSample: flags[1] & 0x01,
  43521. degradationPriority: flags[2] << 8 | flags[3]
  43522. };
  43523. };
  43524. var parseSampleFlags_1 = parseSampleFlags$1;
  43525. var parseSampleFlags = parseSampleFlags_1;
  43526. var trun = function (data) {
  43527. var result = {
  43528. version: data[0],
  43529. flags: new Uint8Array(data.subarray(1, 4)),
  43530. samples: []
  43531. },
  43532. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  43533. // Flag interpretation
  43534. dataOffsetPresent = result.flags[2] & 0x01,
  43535. // compare with 2nd byte of 0x1
  43536. firstSampleFlagsPresent = result.flags[2] & 0x04,
  43537. // compare with 2nd byte of 0x4
  43538. sampleDurationPresent = result.flags[1] & 0x01,
  43539. // compare with 2nd byte of 0x100
  43540. sampleSizePresent = result.flags[1] & 0x02,
  43541. // compare with 2nd byte of 0x200
  43542. sampleFlagsPresent = result.flags[1] & 0x04,
  43543. // compare with 2nd byte of 0x400
  43544. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  43545. // compare with 2nd byte of 0x800
  43546. sampleCount = view.getUint32(4),
  43547. offset = 8,
  43548. sample;
  43549. if (dataOffsetPresent) {
  43550. // 32 bit signed integer
  43551. result.dataOffset = view.getInt32(offset);
  43552. offset += 4;
  43553. } // Overrides the flags for the first sample only. The order of
  43554. // optional values will be: duration, size, compositionTimeOffset
  43555. if (firstSampleFlagsPresent && sampleCount) {
  43556. sample = {
  43557. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  43558. };
  43559. offset += 4;
  43560. if (sampleDurationPresent) {
  43561. sample.duration = view.getUint32(offset);
  43562. offset += 4;
  43563. }
  43564. if (sampleSizePresent) {
  43565. sample.size = view.getUint32(offset);
  43566. offset += 4;
  43567. }
  43568. if (sampleCompositionTimeOffsetPresent) {
  43569. if (result.version === 1) {
  43570. sample.compositionTimeOffset = view.getInt32(offset);
  43571. } else {
  43572. sample.compositionTimeOffset = view.getUint32(offset);
  43573. }
  43574. offset += 4;
  43575. }
  43576. result.samples.push(sample);
  43577. sampleCount--;
  43578. }
  43579. while (sampleCount--) {
  43580. sample = {};
  43581. if (sampleDurationPresent) {
  43582. sample.duration = view.getUint32(offset);
  43583. offset += 4;
  43584. }
  43585. if (sampleSizePresent) {
  43586. sample.size = view.getUint32(offset);
  43587. offset += 4;
  43588. }
  43589. if (sampleFlagsPresent) {
  43590. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  43591. offset += 4;
  43592. }
  43593. if (sampleCompositionTimeOffsetPresent) {
  43594. if (result.version === 1) {
  43595. sample.compositionTimeOffset = view.getInt32(offset);
  43596. } else {
  43597. sample.compositionTimeOffset = view.getUint32(offset);
  43598. }
  43599. offset += 4;
  43600. }
  43601. result.samples.push(sample);
  43602. }
  43603. return result;
  43604. };
  43605. var parseTrun$2 = trun;
  43606. var tfhd = function (data) {
  43607. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  43608. result = {
  43609. version: data[0],
  43610. flags: new Uint8Array(data.subarray(1, 4)),
  43611. trackId: view.getUint32(4)
  43612. },
  43613. baseDataOffsetPresent = result.flags[2] & 0x01,
  43614. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  43615. defaultSampleDurationPresent = result.flags[2] & 0x08,
  43616. defaultSampleSizePresent = result.flags[2] & 0x10,
  43617. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  43618. durationIsEmpty = result.flags[0] & 0x010000,
  43619. defaultBaseIsMoof = result.flags[0] & 0x020000,
  43620. i;
  43621. i = 8;
  43622. if (baseDataOffsetPresent) {
  43623. i += 4; // truncate top 4 bytes
  43624. // FIXME: should we read the full 64 bits?
  43625. result.baseDataOffset = view.getUint32(12);
  43626. i += 4;
  43627. }
  43628. if (sampleDescriptionIndexPresent) {
  43629. result.sampleDescriptionIndex = view.getUint32(i);
  43630. i += 4;
  43631. }
  43632. if (defaultSampleDurationPresent) {
  43633. result.defaultSampleDuration = view.getUint32(i);
  43634. i += 4;
  43635. }
  43636. if (defaultSampleSizePresent) {
  43637. result.defaultSampleSize = view.getUint32(i);
  43638. i += 4;
  43639. }
  43640. if (defaultSampleFlagsPresent) {
  43641. result.defaultSampleFlags = view.getUint32(i);
  43642. }
  43643. if (durationIsEmpty) {
  43644. result.durationIsEmpty = true;
  43645. }
  43646. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  43647. result.baseDataOffsetIsMoof = true;
  43648. }
  43649. return result;
  43650. };
  43651. var parseTfhd$2 = tfhd;
  43652. var win;
  43653. if (typeof window !== "undefined") {
  43654. win = window;
  43655. } else if (typeof commonjsGlobal !== "undefined") {
  43656. win = commonjsGlobal;
  43657. } else if (typeof self !== "undefined") {
  43658. win = self;
  43659. } else {
  43660. win = {};
  43661. }
  43662. var window_1 = win;
  43663. /**
  43664. * mux.js
  43665. *
  43666. * Copyright (c) Brightcove
  43667. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  43668. *
  43669. * Reads in-band CEA-708 captions out of FMP4 segments.
  43670. * @see https://en.wikipedia.org/wiki/CEA-708
  43671. */
  43672. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  43673. var CaptionStream = captionStream.CaptionStream;
  43674. var findBox$1 = findBox_1;
  43675. var parseTfdt$1 = parseTfdt$2;
  43676. var parseTrun$1 = parseTrun$2;
  43677. var parseTfhd$1 = parseTfhd$2;
  43678. var window$2 = window_1;
  43679. /**
  43680. * Maps an offset in the mdat to a sample based on the the size of the samples.
  43681. * Assumes that `parseSamples` has been called first.
  43682. *
  43683. * @param {Number} offset - The offset into the mdat
  43684. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  43685. * @return {?Object} The matching sample, or null if no match was found.
  43686. *
  43687. * @see ISO-BMFF-12/2015, Section 8.8.8
  43688. **/
  43689. var mapToSample = function (offset, samples) {
  43690. var approximateOffset = offset;
  43691. for (var i = 0; i < samples.length; i++) {
  43692. var sample = samples[i];
  43693. if (approximateOffset < sample.size) {
  43694. return sample;
  43695. }
  43696. approximateOffset -= sample.size;
  43697. }
  43698. return null;
  43699. };
  43700. /**
  43701. * Finds SEI nal units contained in a Media Data Box.
  43702. * Assumes that `parseSamples` has been called first.
  43703. *
  43704. * @param {Uint8Array} avcStream - The bytes of the mdat
  43705. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  43706. * @param {Number} trackId - The trackId of this video track
  43707. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  43708. * The contents of the seiNal should match what is expected by
  43709. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  43710. *
  43711. * @see ISO-BMFF-12/2015, Section 8.1.1
  43712. * @see Rec. ITU-T H.264, 7.3.2.3.1
  43713. **/
  43714. var findSeiNals = function (avcStream, samples, trackId) {
  43715. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  43716. result = {
  43717. logs: [],
  43718. seiNals: []
  43719. },
  43720. seiNal,
  43721. i,
  43722. length,
  43723. lastMatchedSample;
  43724. for (i = 0; i + 4 < avcStream.length; i += length) {
  43725. length = avcView.getUint32(i);
  43726. i += 4; // Bail if this doesn't appear to be an H264 stream
  43727. if (length <= 0) {
  43728. continue;
  43729. }
  43730. switch (avcStream[i] & 0x1F) {
  43731. case 0x06:
  43732. var data = avcStream.subarray(i + 1, i + 1 + length);
  43733. var matchingSample = mapToSample(i, samples);
  43734. seiNal = {
  43735. nalUnitType: 'sei_rbsp',
  43736. size: length,
  43737. data: data,
  43738. escapedRBSP: discardEmulationPreventionBytes(data),
  43739. trackId: trackId
  43740. };
  43741. if (matchingSample) {
  43742. seiNal.pts = matchingSample.pts;
  43743. seiNal.dts = matchingSample.dts;
  43744. lastMatchedSample = matchingSample;
  43745. } else if (lastMatchedSample) {
  43746. // If a matching sample cannot be found, use the last
  43747. // sample's values as they should be as close as possible
  43748. seiNal.pts = lastMatchedSample.pts;
  43749. seiNal.dts = lastMatchedSample.dts;
  43750. } else {
  43751. result.logs.push({
  43752. level: 'warn',
  43753. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  43754. });
  43755. break;
  43756. }
  43757. result.seiNals.push(seiNal);
  43758. break;
  43759. }
  43760. }
  43761. return result;
  43762. };
  43763. /**
  43764. * Parses sample information out of Track Run Boxes and calculates
  43765. * the absolute presentation and decode timestamps of each sample.
  43766. *
  43767. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  43768. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  43769. @see ISO-BMFF-12/2015, Section 8.8.12
  43770. * @param {Object} tfhd - The parsed Track Fragment Header
  43771. * @see inspect.parseTfhd
  43772. * @return {Object[]} the parsed samples
  43773. *
  43774. * @see ISO-BMFF-12/2015, Section 8.8.8
  43775. **/
  43776. var parseSamples = function (truns, baseMediaDecodeTime, tfhd) {
  43777. var currentDts = baseMediaDecodeTime;
  43778. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  43779. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  43780. var trackId = tfhd.trackId;
  43781. var allSamples = [];
  43782. truns.forEach(function (trun) {
  43783. // Note: We currently do not parse the sample table as well
  43784. // as the trun. It's possible some sources will require this.
  43785. // moov > trak > mdia > minf > stbl
  43786. var trackRun = parseTrun$1(trun);
  43787. var samples = trackRun.samples;
  43788. samples.forEach(function (sample) {
  43789. if (sample.duration === undefined) {
  43790. sample.duration = defaultSampleDuration;
  43791. }
  43792. if (sample.size === undefined) {
  43793. sample.size = defaultSampleSize;
  43794. }
  43795. sample.trackId = trackId;
  43796. sample.dts = currentDts;
  43797. if (sample.compositionTimeOffset === undefined) {
  43798. sample.compositionTimeOffset = 0;
  43799. }
  43800. if (typeof currentDts === 'bigint') {
  43801. sample.pts = currentDts + window$2.BigInt(sample.compositionTimeOffset);
  43802. currentDts += window$2.BigInt(sample.duration);
  43803. } else {
  43804. sample.pts = currentDts + sample.compositionTimeOffset;
  43805. currentDts += sample.duration;
  43806. }
  43807. });
  43808. allSamples = allSamples.concat(samples);
  43809. });
  43810. return allSamples;
  43811. };
  43812. /**
  43813. * Parses out caption nals from an FMP4 segment's video tracks.
  43814. *
  43815. * @param {Uint8Array} segment - The bytes of a single segment
  43816. * @param {Number} videoTrackId - The trackId of a video track in the segment
  43817. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  43818. * a list of seiNals found in that track
  43819. **/
  43820. var parseCaptionNals = function (segment, videoTrackId) {
  43821. // To get the samples
  43822. var trafs = findBox$1(segment, ['moof', 'traf']); // To get SEI NAL units
  43823. var mdats = findBox$1(segment, ['mdat']);
  43824. var captionNals = {};
  43825. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  43826. mdats.forEach(function (mdat, index) {
  43827. var matchingTraf = trafs[index];
  43828. mdatTrafPairs.push({
  43829. mdat: mdat,
  43830. traf: matchingTraf
  43831. });
  43832. });
  43833. mdatTrafPairs.forEach(function (pair) {
  43834. var mdat = pair.mdat;
  43835. var traf = pair.traf;
  43836. var tfhd = findBox$1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  43837. var headerInfo = parseTfhd$1(tfhd[0]);
  43838. var trackId = headerInfo.trackId;
  43839. var tfdt = findBox$1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  43840. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt$1(tfdt[0]).baseMediaDecodeTime : 0;
  43841. var truns = findBox$1(traf, ['trun']);
  43842. var samples;
  43843. var result; // Only parse video data for the chosen video track
  43844. if (videoTrackId === trackId && truns.length > 0) {
  43845. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  43846. result = findSeiNals(mdat, samples, trackId);
  43847. if (!captionNals[trackId]) {
  43848. captionNals[trackId] = {
  43849. seiNals: [],
  43850. logs: []
  43851. };
  43852. }
  43853. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  43854. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  43855. }
  43856. });
  43857. return captionNals;
  43858. };
  43859. /**
  43860. * Parses out inband captions from an MP4 container and returns
  43861. * caption objects that can be used by WebVTT and the TextTrack API.
  43862. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  43863. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  43864. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  43865. *
  43866. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  43867. * @param {Number} trackId - The id of the video track to parse
  43868. * @param {Number} timescale - The timescale for the video track from the init segment
  43869. *
  43870. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  43871. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  43872. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  43873. * @return {String} parsedCaptions[].text - The visible content of the caption
  43874. **/
  43875. var parseEmbeddedCaptions = function (segment, trackId, timescale) {
  43876. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  43877. if (trackId === null) {
  43878. return null;
  43879. }
  43880. captionNals = parseCaptionNals(segment, trackId);
  43881. var trackNals = captionNals[trackId] || {};
  43882. return {
  43883. seiNals: trackNals.seiNals,
  43884. logs: trackNals.logs,
  43885. timescale: timescale
  43886. };
  43887. };
  43888. /**
  43889. * Converts SEI NALUs into captions that can be used by video.js
  43890. **/
  43891. var CaptionParser = function () {
  43892. var isInitialized = false;
  43893. var captionStream; // Stores segments seen before trackId and timescale are set
  43894. var segmentCache; // Stores video track ID of the track being parsed
  43895. var trackId; // Stores the timescale of the track being parsed
  43896. var timescale; // Stores captions parsed so far
  43897. var parsedCaptions; // Stores whether we are receiving partial data or not
  43898. var parsingPartial;
  43899. /**
  43900. * A method to indicate whether a CaptionParser has been initalized
  43901. * @returns {Boolean}
  43902. **/
  43903. this.isInitialized = function () {
  43904. return isInitialized;
  43905. };
  43906. /**
  43907. * Initializes the underlying CaptionStream, SEI NAL parsing
  43908. * and management, and caption collection
  43909. **/
  43910. this.init = function (options) {
  43911. captionStream = new CaptionStream();
  43912. isInitialized = true;
  43913. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  43914. captionStream.on('data', function (event) {
  43915. // Convert to seconds in the source's timescale
  43916. event.startTime = event.startPts / timescale;
  43917. event.endTime = event.endPts / timescale;
  43918. parsedCaptions.captions.push(event);
  43919. parsedCaptions.captionStreams[event.stream] = true;
  43920. });
  43921. captionStream.on('log', function (log) {
  43922. parsedCaptions.logs.push(log);
  43923. });
  43924. };
  43925. /**
  43926. * Determines if a new video track will be selected
  43927. * or if the timescale changed
  43928. * @return {Boolean}
  43929. **/
  43930. this.isNewInit = function (videoTrackIds, timescales) {
  43931. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  43932. return false;
  43933. }
  43934. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  43935. };
  43936. /**
  43937. * Parses out SEI captions and interacts with underlying
  43938. * CaptionStream to return dispatched captions
  43939. *
  43940. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  43941. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  43942. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  43943. * @see parseEmbeddedCaptions
  43944. * @see m2ts/caption-stream.js
  43945. **/
  43946. this.parse = function (segment, videoTrackIds, timescales) {
  43947. var parsedData;
  43948. if (!this.isInitialized()) {
  43949. return null; // This is not likely to be a video segment
  43950. } else if (!videoTrackIds || !timescales) {
  43951. return null;
  43952. } else if (this.isNewInit(videoTrackIds, timescales)) {
  43953. // Use the first video track only as there is no
  43954. // mechanism to switch to other video tracks
  43955. trackId = videoTrackIds[0];
  43956. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  43957. // data until we have one.
  43958. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  43959. } else if (trackId === null || !timescale) {
  43960. segmentCache.push(segment);
  43961. return null;
  43962. } // Now that a timescale and trackId is set, parse cached segments
  43963. while (segmentCache.length > 0) {
  43964. var cachedSegment = segmentCache.shift();
  43965. this.parse(cachedSegment, videoTrackIds, timescales);
  43966. }
  43967. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  43968. if (parsedData && parsedData.logs) {
  43969. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  43970. }
  43971. if (parsedData === null || !parsedData.seiNals) {
  43972. if (parsedCaptions.logs.length) {
  43973. return {
  43974. logs: parsedCaptions.logs,
  43975. captions: [],
  43976. captionStreams: []
  43977. };
  43978. }
  43979. return null;
  43980. }
  43981. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  43982. this.flushStream();
  43983. return parsedCaptions;
  43984. };
  43985. /**
  43986. * Pushes SEI NALUs onto CaptionStream
  43987. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  43988. * Assumes that `parseCaptionNals` has been called first
  43989. * @see m2ts/caption-stream.js
  43990. **/
  43991. this.pushNals = function (nals) {
  43992. if (!this.isInitialized() || !nals || nals.length === 0) {
  43993. return null;
  43994. }
  43995. nals.forEach(function (nal) {
  43996. captionStream.push(nal);
  43997. });
  43998. };
  43999. /**
  44000. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  44001. * @see m2ts/caption-stream.js
  44002. **/
  44003. this.flushStream = function () {
  44004. if (!this.isInitialized()) {
  44005. return null;
  44006. }
  44007. if (!parsingPartial) {
  44008. captionStream.flush();
  44009. } else {
  44010. captionStream.partialFlush();
  44011. }
  44012. };
  44013. /**
  44014. * Reset caption buckets for new data
  44015. **/
  44016. this.clearParsedCaptions = function () {
  44017. parsedCaptions.captions = [];
  44018. parsedCaptions.captionStreams = {};
  44019. parsedCaptions.logs = [];
  44020. };
  44021. /**
  44022. * Resets underlying CaptionStream
  44023. * @see m2ts/caption-stream.js
  44024. **/
  44025. this.resetCaptionStream = function () {
  44026. if (!this.isInitialized()) {
  44027. return null;
  44028. }
  44029. captionStream.reset();
  44030. };
  44031. /**
  44032. * Convenience method to clear all captions flushed from the
  44033. * CaptionStream and still being parsed
  44034. * @see m2ts/caption-stream.js
  44035. **/
  44036. this.clearAllCaptions = function () {
  44037. this.clearParsedCaptions();
  44038. this.resetCaptionStream();
  44039. };
  44040. /**
  44041. * Reset caption parser
  44042. **/
  44043. this.reset = function () {
  44044. segmentCache = [];
  44045. trackId = null;
  44046. timescale = null;
  44047. if (!parsedCaptions) {
  44048. parsedCaptions = {
  44049. captions: [],
  44050. // CC1, CC2, CC3, CC4
  44051. captionStreams: {},
  44052. logs: []
  44053. };
  44054. } else {
  44055. this.clearParsedCaptions();
  44056. }
  44057. this.resetCaptionStream();
  44058. };
  44059. this.reset();
  44060. };
  44061. var captionParser = CaptionParser;
  44062. /**
  44063. * Returns the first string in the data array ending with a null char '\0'
  44064. * @param {UInt8} data
  44065. * @returns the string with the null char
  44066. */
  44067. var uint8ToCString$1 = function (data) {
  44068. var index = 0;
  44069. var curChar = String.fromCharCode(data[index]);
  44070. var retString = '';
  44071. while (curChar !== '\0') {
  44072. retString += curChar;
  44073. index++;
  44074. curChar = String.fromCharCode(data[index]);
  44075. } // Add nullChar
  44076. retString += curChar;
  44077. return retString;
  44078. };
  44079. var string = {
  44080. uint8ToCString: uint8ToCString$1
  44081. };
  44082. var uint8ToCString = string.uint8ToCString;
  44083. var getUint64$1 = numbers.getUint64;
  44084. /**
  44085. * Based on: ISO/IEC 23009 Section: 5.10.3.3
  44086. * References:
  44087. * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format
  44088. * https://aomediacodec.github.io/id3-emsg/
  44089. *
  44090. * Takes emsg box data as a uint8 array and returns a emsg box object
  44091. * @param {UInt8Array} boxData data from emsg box
  44092. * @returns A parsed emsg box object
  44093. */
  44094. var parseEmsgBox = function (boxData) {
  44095. // version + flags
  44096. var offset = 4;
  44097. var version = boxData[0];
  44098. var scheme_id_uri, value, timescale, presentation_time, presentation_time_delta, event_duration, id, message_data;
  44099. if (version === 0) {
  44100. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  44101. offset += scheme_id_uri.length;
  44102. value = uint8ToCString(boxData.subarray(offset));
  44103. offset += value.length;
  44104. var dv = new DataView(boxData.buffer);
  44105. timescale = dv.getUint32(offset);
  44106. offset += 4;
  44107. presentation_time_delta = dv.getUint32(offset);
  44108. offset += 4;
  44109. event_duration = dv.getUint32(offset);
  44110. offset += 4;
  44111. id = dv.getUint32(offset);
  44112. offset += 4;
  44113. } else if (version === 1) {
  44114. var dv = new DataView(boxData.buffer);
  44115. timescale = dv.getUint32(offset);
  44116. offset += 4;
  44117. presentation_time = getUint64$1(boxData.subarray(offset));
  44118. offset += 8;
  44119. event_duration = dv.getUint32(offset);
  44120. offset += 4;
  44121. id = dv.getUint32(offset);
  44122. offset += 4;
  44123. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  44124. offset += scheme_id_uri.length;
  44125. value = uint8ToCString(boxData.subarray(offset));
  44126. offset += value.length;
  44127. }
  44128. message_data = new Uint8Array(boxData.subarray(offset, boxData.byteLength));
  44129. var emsgBox = {
  44130. scheme_id_uri,
  44131. value,
  44132. // if timescale is undefined or 0 set to 1
  44133. timescale: timescale ? timescale : 1,
  44134. presentation_time,
  44135. presentation_time_delta,
  44136. event_duration,
  44137. id,
  44138. message_data
  44139. };
  44140. return isValidEmsgBox(version, emsgBox) ? emsgBox : undefined;
  44141. };
  44142. /**
  44143. * Scales a presentation time or time delta with an offset with a provided timescale
  44144. * @param {number} presentationTime
  44145. * @param {number} timescale
  44146. * @param {number} timeDelta
  44147. * @param {number} offset
  44148. * @returns the scaled time as a number
  44149. */
  44150. var scaleTime = function (presentationTime, timescale, timeDelta, offset) {
  44151. return presentationTime || presentationTime === 0 ? presentationTime / timescale : offset + timeDelta / timescale;
  44152. };
  44153. /**
  44154. * Checks the emsg box data for validity based on the version
  44155. * @param {number} version of the emsg box to validate
  44156. * @param {Object} emsg the emsg data to validate
  44157. * @returns if the box is valid as a boolean
  44158. */
  44159. var isValidEmsgBox = function (version, emsg) {
  44160. var hasScheme = emsg.scheme_id_uri !== '\0';
  44161. var isValidV0Box = version === 0 && isDefined(emsg.presentation_time_delta) && hasScheme;
  44162. var isValidV1Box = version === 1 && isDefined(emsg.presentation_time) && hasScheme; // Only valid versions of emsg are 0 and 1
  44163. return !(version > 1) && isValidV0Box || isValidV1Box;
  44164. }; // Utility function to check if an object is defined
  44165. var isDefined = function (data) {
  44166. return data !== undefined || data !== null;
  44167. };
  44168. var emsg$1 = {
  44169. parseEmsgBox: parseEmsgBox,
  44170. scaleTime: scaleTime
  44171. };
  44172. /**
  44173. * mux.js
  44174. *
  44175. * Copyright (c) Brightcove
  44176. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  44177. *
  44178. * Utilities to detect basic properties and metadata about MP4s.
  44179. */
  44180. var toUnsigned = bin.toUnsigned;
  44181. var toHexString = bin.toHexString;
  44182. var findBox = findBox_1;
  44183. var parseType$1 = parseType_1;
  44184. var emsg = emsg$1;
  44185. var parseTfhd = parseTfhd$2;
  44186. var parseTrun = parseTrun$2;
  44187. var parseTfdt = parseTfdt$2;
  44188. var getUint64 = numbers.getUint64;
  44189. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader, getEmsgID3;
  44190. var window$1 = window_1;
  44191. var parseId3Frames = parseId3.parseId3Frames;
  44192. /**
  44193. * Parses an MP4 initialization segment and extracts the timescale
  44194. * values for any declared tracks. Timescale values indicate the
  44195. * number of clock ticks per second to assume for time-based values
  44196. * elsewhere in the MP4.
  44197. *
  44198. * To determine the start time of an MP4, you need two pieces of
  44199. * information: the timescale unit and the earliest base media decode
  44200. * time. Multiple timescales can be specified within an MP4 but the
  44201. * base media decode time is always expressed in the timescale from
  44202. * the media header box for the track:
  44203. * ```
  44204. * moov > trak > mdia > mdhd.timescale
  44205. * ```
  44206. * @param init {Uint8Array} the bytes of the init segment
  44207. * @return {object} a hash of track ids to timescale values or null if
  44208. * the init segment is malformed.
  44209. */
  44210. timescale = function (init) {
  44211. var result = {},
  44212. traks = findBox(init, ['moov', 'trak']); // mdhd timescale
  44213. return traks.reduce(function (result, trak) {
  44214. var tkhd, version, index, id, mdhd;
  44215. tkhd = findBox(trak, ['tkhd'])[0];
  44216. if (!tkhd) {
  44217. return null;
  44218. }
  44219. version = tkhd[0];
  44220. index = version === 0 ? 12 : 20;
  44221. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  44222. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  44223. if (!mdhd) {
  44224. return null;
  44225. }
  44226. version = mdhd[0];
  44227. index = version === 0 ? 12 : 20;
  44228. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  44229. return result;
  44230. }, result);
  44231. };
  44232. /**
  44233. * Determine the base media decode start time, in seconds, for an MP4
  44234. * fragment. If multiple fragments are specified, the earliest time is
  44235. * returned.
  44236. *
  44237. * The base media decode time can be parsed from track fragment
  44238. * metadata:
  44239. * ```
  44240. * moof > traf > tfdt.baseMediaDecodeTime
  44241. * ```
  44242. * It requires the timescale value from the mdhd to interpret.
  44243. *
  44244. * @param timescale {object} a hash of track ids to timescale values.
  44245. * @return {number} the earliest base media decode start time for the
  44246. * fragment, in seconds
  44247. */
  44248. startTime = function (timescale, fragment) {
  44249. var trafs; // we need info from two childrend of each track fragment box
  44250. trafs = findBox(fragment, ['moof', 'traf']); // determine the start times for each track
  44251. var lowestTime = trafs.reduce(function (acc, traf) {
  44252. var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
  44253. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  44254. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  44255. var tfdt = findBox(traf, ['tfdt'])[0];
  44256. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  44257. var baseTime; // version 1 is 64 bit
  44258. if (tfdt[0] === 1) {
  44259. baseTime = getUint64(tfdt.subarray(4, 12));
  44260. } else {
  44261. baseTime = dv.getUint32(4);
  44262. } // convert base time to seconds if it is a valid number.
  44263. let seconds;
  44264. if (typeof baseTime === 'bigint') {
  44265. seconds = baseTime / window$1.BigInt(scale);
  44266. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  44267. seconds = baseTime / scale;
  44268. }
  44269. if (seconds < Number.MAX_SAFE_INTEGER) {
  44270. seconds = Number(seconds);
  44271. }
  44272. if (seconds < acc) {
  44273. acc = seconds;
  44274. }
  44275. return acc;
  44276. }, Infinity);
  44277. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  44278. };
  44279. /**
  44280. * Determine the composition start, in seconds, for an MP4
  44281. * fragment.
  44282. *
  44283. * The composition start time of a fragment can be calculated using the base
  44284. * media decode time, composition time offset, and timescale, as follows:
  44285. *
  44286. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  44287. *
  44288. * All of the aforementioned information is contained within a media fragment's
  44289. * `traf` box, except for timescale info, which comes from the initialization
  44290. * segment, so a track id (also contained within a `traf`) is also necessary to
  44291. * associate it with a timescale
  44292. *
  44293. *
  44294. * @param timescales {object} - a hash of track ids to timescale values.
  44295. * @param fragment {Unit8Array} - the bytes of a media segment
  44296. * @return {number} the composition start time for the fragment, in seconds
  44297. **/
  44298. compositionStartTime = function (timescales, fragment) {
  44299. var trafBoxes = findBox(fragment, ['moof', 'traf']);
  44300. var baseMediaDecodeTime = 0;
  44301. var compositionTimeOffset = 0;
  44302. var trackId;
  44303. if (trafBoxes && trafBoxes.length) {
  44304. // The spec states that track run samples contained within a `traf` box are contiguous, but
  44305. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  44306. // We will assume that they are, so we only need the first to calculate start time.
  44307. var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
  44308. var trun = findBox(trafBoxes[0], ['trun'])[0];
  44309. var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];
  44310. if (tfhd) {
  44311. var parsedTfhd = parseTfhd(tfhd);
  44312. trackId = parsedTfhd.trackId;
  44313. }
  44314. if (tfdt) {
  44315. var parsedTfdt = parseTfdt(tfdt);
  44316. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  44317. }
  44318. if (trun) {
  44319. var parsedTrun = parseTrun(trun);
  44320. if (parsedTrun.samples && parsedTrun.samples.length) {
  44321. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  44322. }
  44323. }
  44324. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  44325. // specified.
  44326. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  44327. if (typeof baseMediaDecodeTime === 'bigint') {
  44328. compositionTimeOffset = window$1.BigInt(compositionTimeOffset);
  44329. timescale = window$1.BigInt(timescale);
  44330. }
  44331. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  44332. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  44333. result = Number(result);
  44334. }
  44335. return result;
  44336. };
  44337. /**
  44338. * Find the trackIds of the video tracks in this source.
  44339. * Found by parsing the Handler Reference and Track Header Boxes:
  44340. * moov > trak > mdia > hdlr
  44341. * moov > trak > tkhd
  44342. *
  44343. * @param {Uint8Array} init - The bytes of the init segment for this source
  44344. * @return {Number[]} A list of trackIds
  44345. *
  44346. * @see ISO-BMFF-12/2015, Section 8.4.3
  44347. **/
  44348. getVideoTrackIds = function (init) {
  44349. var traks = findBox(init, ['moov', 'trak']);
  44350. var videoTrackIds = [];
  44351. traks.forEach(function (trak) {
  44352. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  44353. var tkhds = findBox(trak, ['tkhd']);
  44354. hdlrs.forEach(function (hdlr, index) {
  44355. var handlerType = parseType$1(hdlr.subarray(8, 12));
  44356. var tkhd = tkhds[index];
  44357. var view;
  44358. var version;
  44359. var trackId;
  44360. if (handlerType === 'vide') {
  44361. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  44362. version = view.getUint8(0);
  44363. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  44364. videoTrackIds.push(trackId);
  44365. }
  44366. });
  44367. });
  44368. return videoTrackIds;
  44369. };
  44370. getTimescaleFromMediaHeader = function (mdhd) {
  44371. // mdhd is a FullBox, meaning it will have its own version as the first byte
  44372. var version = mdhd[0];
  44373. var index = version === 0 ? 12 : 20;
  44374. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  44375. };
  44376. /**
  44377. * Get all the video, audio, and hint tracks from a non fragmented
  44378. * mp4 segment
  44379. */
  44380. getTracks = function (init) {
  44381. var traks = findBox(init, ['moov', 'trak']);
  44382. var tracks = [];
  44383. traks.forEach(function (trak) {
  44384. var track = {};
  44385. var tkhd = findBox(trak, ['tkhd'])[0];
  44386. var view, tkhdVersion; // id
  44387. if (tkhd) {
  44388. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  44389. tkhdVersion = view.getUint8(0);
  44390. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  44391. }
  44392. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0]; // type
  44393. if (hdlr) {
  44394. var type = parseType$1(hdlr.subarray(8, 12));
  44395. if (type === 'vide') {
  44396. track.type = 'video';
  44397. } else if (type === 'soun') {
  44398. track.type = 'audio';
  44399. } else {
  44400. track.type = type;
  44401. }
  44402. } // codec
  44403. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  44404. if (stsd) {
  44405. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  44406. track.codec = parseType$1(sampleDescriptions.subarray(4, 8));
  44407. var codecBox = findBox(sampleDescriptions, [track.codec])[0];
  44408. var codecConfig, codecConfigType;
  44409. if (codecBox) {
  44410. // https://tools.ietf.org/html/rfc6381#section-3.3
  44411. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  44412. // we don't need anything but the "config" parameter of the
  44413. // avc1 codecBox
  44414. codecConfig = codecBox.subarray(78);
  44415. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  44416. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  44417. track.codec += '.'; // left padded with zeroes for single digit hex
  44418. // profile idc
  44419. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  44420. track.codec += toHexString(codecConfig[10]); // level idc
  44421. track.codec += toHexString(codecConfig[11]);
  44422. } else {
  44423. // TODO: show a warning that we couldn't parse the codec
  44424. // and are using the default
  44425. track.codec = 'avc1.4d400d';
  44426. }
  44427. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  44428. // we do not need anything but the streamDescriptor of the mp4a codecBox
  44429. codecConfig = codecBox.subarray(28);
  44430. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  44431. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  44432. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  44433. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  44434. } else {
  44435. // TODO: show a warning that we couldn't parse the codec
  44436. // and are using the default
  44437. track.codec = 'mp4a.40.2';
  44438. }
  44439. } else {
  44440. // flac, opus, etc
  44441. track.codec = track.codec.toLowerCase();
  44442. }
  44443. }
  44444. }
  44445. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  44446. if (mdhd) {
  44447. track.timescale = getTimescaleFromMediaHeader(mdhd);
  44448. }
  44449. tracks.push(track);
  44450. });
  44451. return tracks;
  44452. };
  44453. /**
  44454. * Returns an array of emsg ID3 data from the provided segmentData.
  44455. * An offset can also be provided as the Latest Arrival Time to calculate
  44456. * the Event Start Time of v0 EMSG boxes.
  44457. * See: https://dashif-documents.azurewebsites.net/Events/master/event.html#Inband-event-timing
  44458. *
  44459. * @param {Uint8Array} segmentData the segment byte array.
  44460. * @param {number} offset the segment start time or Latest Arrival Time,
  44461. * @return {Object[]} an array of ID3 parsed from EMSG boxes
  44462. */
  44463. getEmsgID3 = function (segmentData, offset = 0) {
  44464. var emsgBoxes = findBox(segmentData, ['emsg']);
  44465. return emsgBoxes.map(data => {
  44466. var parsedBox = emsg.parseEmsgBox(new Uint8Array(data));
  44467. var parsedId3Frames = parseId3Frames(parsedBox.message_data);
  44468. return {
  44469. cueTime: emsg.scaleTime(parsedBox.presentation_time, parsedBox.timescale, parsedBox.presentation_time_delta, offset),
  44470. duration: emsg.scaleTime(parsedBox.event_duration, parsedBox.timescale),
  44471. frames: parsedId3Frames
  44472. };
  44473. });
  44474. };
  44475. var probe$2 = {
  44476. // export mp4 inspector's findBox and parseType for backwards compatibility
  44477. findBox: findBox,
  44478. parseType: parseType$1,
  44479. timescale: timescale,
  44480. startTime: startTime,
  44481. compositionStartTime: compositionStartTime,
  44482. videoTrackIds: getVideoTrackIds,
  44483. tracks: getTracks,
  44484. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader,
  44485. getEmsgID3: getEmsgID3
  44486. };
  44487. /**
  44488. * mux.js
  44489. *
  44490. * Copyright (c) Brightcove
  44491. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  44492. *
  44493. * Utilities to detect basic properties and metadata about TS Segments.
  44494. */
  44495. var StreamTypes$1 = streamTypes;
  44496. var parsePid = function (packet) {
  44497. var pid = packet[1] & 0x1f;
  44498. pid <<= 8;
  44499. pid |= packet[2];
  44500. return pid;
  44501. };
  44502. var parsePayloadUnitStartIndicator = function (packet) {
  44503. return !!(packet[1] & 0x40);
  44504. };
  44505. var parseAdaptionField = function (packet) {
  44506. var offset = 0; // if an adaption field is present, its length is specified by the
  44507. // fifth byte of the TS packet header. The adaptation field is
  44508. // used to add stuffing to PES packets that don't fill a complete
  44509. // TS packet, and to specify some forms of timing and control data
  44510. // that we do not currently use.
  44511. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  44512. offset += packet[4] + 1;
  44513. }
  44514. return offset;
  44515. };
  44516. var parseType = function (packet, pmtPid) {
  44517. var pid = parsePid(packet);
  44518. if (pid === 0) {
  44519. return 'pat';
  44520. } else if (pid === pmtPid) {
  44521. return 'pmt';
  44522. } else if (pmtPid) {
  44523. return 'pes';
  44524. }
  44525. return null;
  44526. };
  44527. var parsePat = function (packet) {
  44528. var pusi = parsePayloadUnitStartIndicator(packet);
  44529. var offset = 4 + parseAdaptionField(packet);
  44530. if (pusi) {
  44531. offset += packet[offset] + 1;
  44532. }
  44533. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  44534. };
  44535. var parsePmt = function (packet) {
  44536. var programMapTable = {};
  44537. var pusi = parsePayloadUnitStartIndicator(packet);
  44538. var payloadOffset = 4 + parseAdaptionField(packet);
  44539. if (pusi) {
  44540. payloadOffset += packet[payloadOffset] + 1;
  44541. } // PMTs can be sent ahead of the time when they should actually
  44542. // take effect. We don't believe this should ever be the case
  44543. // for HLS but we'll ignore "forward" PMT declarations if we see
  44544. // them. Future PMT declarations have the current_next_indicator
  44545. // set to zero.
  44546. if (!(packet[payloadOffset + 5] & 0x01)) {
  44547. return;
  44548. }
  44549. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  44550. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  44551. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  44552. // long the program info descriptors are
  44553. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  44554. var offset = 12 + programInfoLength;
  44555. while (offset < tableEnd) {
  44556. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  44557. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  44558. // skip past the elementary stream descriptors, if present
  44559. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  44560. }
  44561. return programMapTable;
  44562. };
  44563. var parsePesType = function (packet, programMapTable) {
  44564. var pid = parsePid(packet);
  44565. var type = programMapTable[pid];
  44566. switch (type) {
  44567. case StreamTypes$1.H264_STREAM_TYPE:
  44568. return 'video';
  44569. case StreamTypes$1.ADTS_STREAM_TYPE:
  44570. return 'audio';
  44571. case StreamTypes$1.METADATA_STREAM_TYPE:
  44572. return 'timed-metadata';
  44573. default:
  44574. return null;
  44575. }
  44576. };
  44577. var parsePesTime = function (packet) {
  44578. var pusi = parsePayloadUnitStartIndicator(packet);
  44579. if (!pusi) {
  44580. return null;
  44581. }
  44582. var offset = 4 + parseAdaptionField(packet);
  44583. if (offset >= packet.byteLength) {
  44584. // From the H 222.0 MPEG-TS spec
  44585. // "For transport stream packets carrying PES packets, stuffing is needed when there
  44586. // is insufficient PES packet data to completely fill the transport stream packet
  44587. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  44588. // the sum of the lengths of the data elements in it, so that the payload bytes
  44589. // remaining after the adaptation field exactly accommodates the available PES packet
  44590. // data."
  44591. //
  44592. // If the offset is >= the length of the packet, then the packet contains no data
  44593. // and instead is just adaption field stuffing bytes
  44594. return null;
  44595. }
  44596. var pes = null;
  44597. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  44598. // and a DTS value. Determine what combination of values is
  44599. // available to work with.
  44600. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  44601. // performs all bitwise operations on 32-bit integers but javascript
  44602. // supports a much greater range (52-bits) of integer using standard
  44603. // mathematical operations.
  44604. // We construct a 31-bit value using bitwise operators over the 31
  44605. // most significant bits and then multiply by 4 (equal to a left-shift
  44606. // of 2) before we add the final 2 least significant bits of the
  44607. // timestamp (equal to an OR.)
  44608. if (ptsDtsFlags & 0xC0) {
  44609. pes = {}; // the PTS and DTS are not written out directly. For information
  44610. // on how they are encoded, see
  44611. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  44612. 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;
  44613. pes.pts *= 4; // Left shift by 2
  44614. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  44615. pes.dts = pes.pts;
  44616. if (ptsDtsFlags & 0x40) {
  44617. 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;
  44618. pes.dts *= 4; // Left shift by 2
  44619. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  44620. }
  44621. }
  44622. return pes;
  44623. };
  44624. var parseNalUnitType = function (type) {
  44625. switch (type) {
  44626. case 0x05:
  44627. return 'slice_layer_without_partitioning_rbsp_idr';
  44628. case 0x06:
  44629. return 'sei_rbsp';
  44630. case 0x07:
  44631. return 'seq_parameter_set_rbsp';
  44632. case 0x08:
  44633. return 'pic_parameter_set_rbsp';
  44634. case 0x09:
  44635. return 'access_unit_delimiter_rbsp';
  44636. default:
  44637. return null;
  44638. }
  44639. };
  44640. var videoPacketContainsKeyFrame = function (packet) {
  44641. var offset = 4 + parseAdaptionField(packet);
  44642. var frameBuffer = packet.subarray(offset);
  44643. var frameI = 0;
  44644. var frameSyncPoint = 0;
  44645. var foundKeyFrame = false;
  44646. var nalType; // advance the sync point to a NAL start, if necessary
  44647. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  44648. if (frameBuffer[frameSyncPoint + 2] === 1) {
  44649. // the sync point is properly aligned
  44650. frameI = frameSyncPoint + 5;
  44651. break;
  44652. }
  44653. }
  44654. while (frameI < frameBuffer.byteLength) {
  44655. // look at the current byte to determine if we've hit the end of
  44656. // a NAL unit boundary
  44657. switch (frameBuffer[frameI]) {
  44658. case 0:
  44659. // skip past non-sync sequences
  44660. if (frameBuffer[frameI - 1] !== 0) {
  44661. frameI += 2;
  44662. break;
  44663. } else if (frameBuffer[frameI - 2] !== 0) {
  44664. frameI++;
  44665. break;
  44666. }
  44667. if (frameSyncPoint + 3 !== frameI - 2) {
  44668. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  44669. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  44670. foundKeyFrame = true;
  44671. }
  44672. } // drop trailing zeroes
  44673. do {
  44674. frameI++;
  44675. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  44676. frameSyncPoint = frameI - 2;
  44677. frameI += 3;
  44678. break;
  44679. case 1:
  44680. // skip past non-sync sequences
  44681. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  44682. frameI += 3;
  44683. break;
  44684. }
  44685. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  44686. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  44687. foundKeyFrame = true;
  44688. }
  44689. frameSyncPoint = frameI - 2;
  44690. frameI += 3;
  44691. break;
  44692. default:
  44693. // the current byte isn't a one or zero, so it cannot be part
  44694. // of a sync sequence
  44695. frameI += 3;
  44696. break;
  44697. }
  44698. }
  44699. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  44700. frameI -= frameSyncPoint;
  44701. frameSyncPoint = 0; // parse the final nal
  44702. if (frameBuffer && frameBuffer.byteLength > 3) {
  44703. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  44704. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  44705. foundKeyFrame = true;
  44706. }
  44707. }
  44708. return foundKeyFrame;
  44709. };
  44710. var probe$1 = {
  44711. parseType: parseType,
  44712. parsePat: parsePat,
  44713. parsePmt: parsePmt,
  44714. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  44715. parsePesType: parsePesType,
  44716. parsePesTime: parsePesTime,
  44717. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  44718. };
  44719. /**
  44720. * mux.js
  44721. *
  44722. * Copyright (c) Brightcove
  44723. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  44724. *
  44725. * Parse mpeg2 transport stream packets to extract basic timing information
  44726. */
  44727. var StreamTypes = streamTypes;
  44728. var handleRollover = timestampRolloverStream.handleRollover;
  44729. var probe = {};
  44730. probe.ts = probe$1;
  44731. probe.aac = utils;
  44732. var ONE_SECOND_IN_TS = clock$2.ONE_SECOND_IN_TS;
  44733. var MP2T_PACKET_LENGTH = 188,
  44734. // bytes
  44735. SYNC_BYTE = 0x47;
  44736. /**
  44737. * walks through segment data looking for pat and pmt packets to parse out
  44738. * program map table information
  44739. */
  44740. var parsePsi_ = function (bytes, pmt) {
  44741. var startIndex = 0,
  44742. endIndex = MP2T_PACKET_LENGTH,
  44743. packet,
  44744. type;
  44745. while (endIndex < bytes.byteLength) {
  44746. // Look for a pair of start and end sync bytes in the data..
  44747. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  44748. // We found a packet
  44749. packet = bytes.subarray(startIndex, endIndex);
  44750. type = probe.ts.parseType(packet, pmt.pid);
  44751. switch (type) {
  44752. case 'pat':
  44753. pmt.pid = probe.ts.parsePat(packet);
  44754. break;
  44755. case 'pmt':
  44756. var table = probe.ts.parsePmt(packet);
  44757. pmt.table = pmt.table || {};
  44758. Object.keys(table).forEach(function (key) {
  44759. pmt.table[key] = table[key];
  44760. });
  44761. break;
  44762. }
  44763. startIndex += MP2T_PACKET_LENGTH;
  44764. endIndex += MP2T_PACKET_LENGTH;
  44765. continue;
  44766. } // If we get here, we have somehow become de-synchronized and we need to step
  44767. // forward one byte at a time until we find a pair of sync bytes that denote
  44768. // a packet
  44769. startIndex++;
  44770. endIndex++;
  44771. }
  44772. };
  44773. /**
  44774. * walks through the segment data from the start and end to get timing information
  44775. * for the first and last audio pes packets
  44776. */
  44777. var parseAudioPes_ = function (bytes, pmt, result) {
  44778. var startIndex = 0,
  44779. endIndex = MP2T_PACKET_LENGTH,
  44780. packet,
  44781. type,
  44782. pesType,
  44783. pusi,
  44784. parsed;
  44785. var endLoop = false; // Start walking from start of segment to get first audio packet
  44786. while (endIndex <= bytes.byteLength) {
  44787. // Look for a pair of start and end sync bytes in the data..
  44788. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  44789. // We found a packet
  44790. packet = bytes.subarray(startIndex, endIndex);
  44791. type = probe.ts.parseType(packet, pmt.pid);
  44792. switch (type) {
  44793. case 'pes':
  44794. pesType = probe.ts.parsePesType(packet, pmt.table);
  44795. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  44796. if (pesType === 'audio' && pusi) {
  44797. parsed = probe.ts.parsePesTime(packet);
  44798. if (parsed) {
  44799. parsed.type = 'audio';
  44800. result.audio.push(parsed);
  44801. endLoop = true;
  44802. }
  44803. }
  44804. break;
  44805. }
  44806. if (endLoop) {
  44807. break;
  44808. }
  44809. startIndex += MP2T_PACKET_LENGTH;
  44810. endIndex += MP2T_PACKET_LENGTH;
  44811. continue;
  44812. } // If we get here, we have somehow become de-synchronized and we need to step
  44813. // forward one byte at a time until we find a pair of sync bytes that denote
  44814. // a packet
  44815. startIndex++;
  44816. endIndex++;
  44817. } // Start walking from end of segment to get last audio packet
  44818. endIndex = bytes.byteLength;
  44819. startIndex = endIndex - MP2T_PACKET_LENGTH;
  44820. endLoop = false;
  44821. while (startIndex >= 0) {
  44822. // Look for a pair of start and end sync bytes in the data..
  44823. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  44824. // We found a packet
  44825. packet = bytes.subarray(startIndex, endIndex);
  44826. type = probe.ts.parseType(packet, pmt.pid);
  44827. switch (type) {
  44828. case 'pes':
  44829. pesType = probe.ts.parsePesType(packet, pmt.table);
  44830. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  44831. if (pesType === 'audio' && pusi) {
  44832. parsed = probe.ts.parsePesTime(packet);
  44833. if (parsed) {
  44834. parsed.type = 'audio';
  44835. result.audio.push(parsed);
  44836. endLoop = true;
  44837. }
  44838. }
  44839. break;
  44840. }
  44841. if (endLoop) {
  44842. break;
  44843. }
  44844. startIndex -= MP2T_PACKET_LENGTH;
  44845. endIndex -= MP2T_PACKET_LENGTH;
  44846. continue;
  44847. } // If we get here, we have somehow become de-synchronized and we need to step
  44848. // forward one byte at a time until we find a pair of sync bytes that denote
  44849. // a packet
  44850. startIndex--;
  44851. endIndex--;
  44852. }
  44853. };
  44854. /**
  44855. * walks through the segment data from the start and end to get timing information
  44856. * for the first and last video pes packets as well as timing information for the first
  44857. * key frame.
  44858. */
  44859. var parseVideoPes_ = function (bytes, pmt, result) {
  44860. var startIndex = 0,
  44861. endIndex = MP2T_PACKET_LENGTH,
  44862. packet,
  44863. type,
  44864. pesType,
  44865. pusi,
  44866. parsed,
  44867. frame,
  44868. i,
  44869. pes;
  44870. var endLoop = false;
  44871. var currentFrame = {
  44872. data: [],
  44873. size: 0
  44874. }; // Start walking from start of segment to get first video packet
  44875. while (endIndex < bytes.byteLength) {
  44876. // Look for a pair of start and end sync bytes in the data..
  44877. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  44878. // We found a packet
  44879. packet = bytes.subarray(startIndex, endIndex);
  44880. type = probe.ts.parseType(packet, pmt.pid);
  44881. switch (type) {
  44882. case 'pes':
  44883. pesType = probe.ts.parsePesType(packet, pmt.table);
  44884. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  44885. if (pesType === 'video') {
  44886. if (pusi && !endLoop) {
  44887. parsed = probe.ts.parsePesTime(packet);
  44888. if (parsed) {
  44889. parsed.type = 'video';
  44890. result.video.push(parsed);
  44891. endLoop = true;
  44892. }
  44893. }
  44894. if (!result.firstKeyFrame) {
  44895. if (pusi) {
  44896. if (currentFrame.size !== 0) {
  44897. frame = new Uint8Array(currentFrame.size);
  44898. i = 0;
  44899. while (currentFrame.data.length) {
  44900. pes = currentFrame.data.shift();
  44901. frame.set(pes, i);
  44902. i += pes.byteLength;
  44903. }
  44904. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  44905. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  44906. // the keyframe seems to work fine with HLS playback
  44907. // and definitely preferable to a crash with TypeError...
  44908. if (firstKeyFrame) {
  44909. result.firstKeyFrame = firstKeyFrame;
  44910. result.firstKeyFrame.type = 'video';
  44911. } else {
  44912. // eslint-disable-next-line
  44913. 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.');
  44914. }
  44915. }
  44916. currentFrame.size = 0;
  44917. }
  44918. }
  44919. currentFrame.data.push(packet);
  44920. currentFrame.size += packet.byteLength;
  44921. }
  44922. }
  44923. break;
  44924. }
  44925. if (endLoop && result.firstKeyFrame) {
  44926. break;
  44927. }
  44928. startIndex += MP2T_PACKET_LENGTH;
  44929. endIndex += MP2T_PACKET_LENGTH;
  44930. continue;
  44931. } // If we get here, we have somehow become de-synchronized and we need to step
  44932. // forward one byte at a time until we find a pair of sync bytes that denote
  44933. // a packet
  44934. startIndex++;
  44935. endIndex++;
  44936. } // Start walking from end of segment to get last video packet
  44937. endIndex = bytes.byteLength;
  44938. startIndex = endIndex - MP2T_PACKET_LENGTH;
  44939. endLoop = false;
  44940. while (startIndex >= 0) {
  44941. // Look for a pair of start and end sync bytes in the data..
  44942. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  44943. // We found a packet
  44944. packet = bytes.subarray(startIndex, endIndex);
  44945. type = probe.ts.parseType(packet, pmt.pid);
  44946. switch (type) {
  44947. case 'pes':
  44948. pesType = probe.ts.parsePesType(packet, pmt.table);
  44949. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  44950. if (pesType === 'video' && pusi) {
  44951. parsed = probe.ts.parsePesTime(packet);
  44952. if (parsed) {
  44953. parsed.type = 'video';
  44954. result.video.push(parsed);
  44955. endLoop = true;
  44956. }
  44957. }
  44958. break;
  44959. }
  44960. if (endLoop) {
  44961. break;
  44962. }
  44963. startIndex -= MP2T_PACKET_LENGTH;
  44964. endIndex -= MP2T_PACKET_LENGTH;
  44965. continue;
  44966. } // If we get here, we have somehow become de-synchronized and we need to step
  44967. // forward one byte at a time until we find a pair of sync bytes that denote
  44968. // a packet
  44969. startIndex--;
  44970. endIndex--;
  44971. }
  44972. };
  44973. /**
  44974. * Adjusts the timestamp information for the segment to account for
  44975. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  44976. */
  44977. var adjustTimestamp_ = function (segmentInfo, baseTimestamp) {
  44978. if (segmentInfo.audio && segmentInfo.audio.length) {
  44979. var audioBaseTimestamp = baseTimestamp;
  44980. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  44981. audioBaseTimestamp = segmentInfo.audio[0].dts;
  44982. }
  44983. segmentInfo.audio.forEach(function (info) {
  44984. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  44985. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  44986. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  44987. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  44988. });
  44989. }
  44990. if (segmentInfo.video && segmentInfo.video.length) {
  44991. var videoBaseTimestamp = baseTimestamp;
  44992. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  44993. videoBaseTimestamp = segmentInfo.video[0].dts;
  44994. }
  44995. segmentInfo.video.forEach(function (info) {
  44996. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  44997. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  44998. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  44999. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  45000. });
  45001. if (segmentInfo.firstKeyFrame) {
  45002. var frame = segmentInfo.firstKeyFrame;
  45003. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  45004. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  45005. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  45006. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  45007. }
  45008. }
  45009. };
  45010. /**
  45011. * inspects the aac data stream for start and end time information
  45012. */
  45013. var inspectAac_ = function (bytes) {
  45014. var endLoop = false,
  45015. audioCount = 0,
  45016. sampleRate = null,
  45017. timestamp = null,
  45018. frameSize = 0,
  45019. byteIndex = 0,
  45020. packet;
  45021. while (bytes.length - byteIndex >= 3) {
  45022. var type = probe.aac.parseType(bytes, byteIndex);
  45023. switch (type) {
  45024. case 'timed-metadata':
  45025. // Exit early because we don't have enough to parse
  45026. // the ID3 tag header
  45027. if (bytes.length - byteIndex < 10) {
  45028. endLoop = true;
  45029. break;
  45030. }
  45031. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  45032. // to emit a full packet
  45033. if (frameSize > bytes.length) {
  45034. endLoop = true;
  45035. break;
  45036. }
  45037. if (timestamp === null) {
  45038. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  45039. timestamp = probe.aac.parseAacTimestamp(packet);
  45040. }
  45041. byteIndex += frameSize;
  45042. break;
  45043. case 'audio':
  45044. // Exit early because we don't have enough to parse
  45045. // the ADTS frame header
  45046. if (bytes.length - byteIndex < 7) {
  45047. endLoop = true;
  45048. break;
  45049. }
  45050. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  45051. // to emit a full packet
  45052. if (frameSize > bytes.length) {
  45053. endLoop = true;
  45054. break;
  45055. }
  45056. if (sampleRate === null) {
  45057. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  45058. sampleRate = probe.aac.parseSampleRate(packet);
  45059. }
  45060. audioCount++;
  45061. byteIndex += frameSize;
  45062. break;
  45063. default:
  45064. byteIndex++;
  45065. break;
  45066. }
  45067. if (endLoop) {
  45068. return null;
  45069. }
  45070. }
  45071. if (sampleRate === null || timestamp === null) {
  45072. return null;
  45073. }
  45074. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  45075. var result = {
  45076. audio: [{
  45077. type: 'audio',
  45078. dts: timestamp,
  45079. pts: timestamp
  45080. }, {
  45081. type: 'audio',
  45082. dts: timestamp + audioCount * 1024 * audioTimescale,
  45083. pts: timestamp + audioCount * 1024 * audioTimescale
  45084. }]
  45085. };
  45086. return result;
  45087. };
  45088. /**
  45089. * inspects the transport stream segment data for start and end time information
  45090. * of the audio and video tracks (when present) as well as the first key frame's
  45091. * start time.
  45092. */
  45093. var inspectTs_ = function (bytes) {
  45094. var pmt = {
  45095. pid: null,
  45096. table: null
  45097. };
  45098. var result = {};
  45099. parsePsi_(bytes, pmt);
  45100. for (var pid in pmt.table) {
  45101. if (pmt.table.hasOwnProperty(pid)) {
  45102. var type = pmt.table[pid];
  45103. switch (type) {
  45104. case StreamTypes.H264_STREAM_TYPE:
  45105. result.video = [];
  45106. parseVideoPes_(bytes, pmt, result);
  45107. if (result.video.length === 0) {
  45108. delete result.video;
  45109. }
  45110. break;
  45111. case StreamTypes.ADTS_STREAM_TYPE:
  45112. result.audio = [];
  45113. parseAudioPes_(bytes, pmt, result);
  45114. if (result.audio.length === 0) {
  45115. delete result.audio;
  45116. }
  45117. break;
  45118. }
  45119. }
  45120. }
  45121. return result;
  45122. };
  45123. /**
  45124. * Inspects segment byte data and returns an object with start and end timing information
  45125. *
  45126. * @param {Uint8Array} bytes The segment byte data
  45127. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  45128. * timestamps for rollover. This value must be in 90khz clock.
  45129. * @return {Object} Object containing start and end frame timing info of segment.
  45130. */
  45131. var inspect = function (bytes, baseTimestamp) {
  45132. var isAacData = probe.aac.isLikelyAacData(bytes);
  45133. var result;
  45134. if (isAacData) {
  45135. result = inspectAac_(bytes);
  45136. } else {
  45137. result = inspectTs_(bytes);
  45138. }
  45139. if (!result || !result.audio && !result.video) {
  45140. return null;
  45141. }
  45142. adjustTimestamp_(result, baseTimestamp);
  45143. return result;
  45144. };
  45145. var tsInspector = {
  45146. inspect: inspect,
  45147. parseAudioPes_: parseAudioPes_
  45148. };
  45149. /* global self */
  45150. /**
  45151. * Re-emits transmuxer events by converting them into messages to the
  45152. * world outside the worker.
  45153. *
  45154. * @param {Object} transmuxer the transmuxer to wire events on
  45155. * @private
  45156. */
  45157. const wireTransmuxerEvents = function (self, transmuxer) {
  45158. transmuxer.on('data', function (segment) {
  45159. // transfer ownership of the underlying ArrayBuffer
  45160. // instead of doing a copy to save memory
  45161. // ArrayBuffers are transferable but generic TypedArrays are not
  45162. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  45163. const initArray = segment.initSegment;
  45164. segment.initSegment = {
  45165. data: initArray.buffer,
  45166. byteOffset: initArray.byteOffset,
  45167. byteLength: initArray.byteLength
  45168. };
  45169. const typedArray = segment.data;
  45170. segment.data = typedArray.buffer;
  45171. self.postMessage({
  45172. action: 'data',
  45173. segment,
  45174. byteOffset: typedArray.byteOffset,
  45175. byteLength: typedArray.byteLength
  45176. }, [segment.data]);
  45177. });
  45178. transmuxer.on('done', function (data) {
  45179. self.postMessage({
  45180. action: 'done'
  45181. });
  45182. });
  45183. transmuxer.on('gopInfo', function (gopInfo) {
  45184. self.postMessage({
  45185. action: 'gopInfo',
  45186. gopInfo
  45187. });
  45188. });
  45189. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  45190. const videoSegmentTimingInfo = {
  45191. start: {
  45192. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  45193. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  45194. },
  45195. end: {
  45196. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  45197. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  45198. },
  45199. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  45200. };
  45201. if (timingInfo.prependedContentDuration) {
  45202. videoSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  45203. }
  45204. self.postMessage({
  45205. action: 'videoSegmentTimingInfo',
  45206. videoSegmentTimingInfo
  45207. });
  45208. });
  45209. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  45210. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  45211. const audioSegmentTimingInfo = {
  45212. start: {
  45213. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  45214. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  45215. },
  45216. end: {
  45217. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  45218. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  45219. },
  45220. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  45221. };
  45222. if (timingInfo.prependedContentDuration) {
  45223. audioSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  45224. }
  45225. self.postMessage({
  45226. action: 'audioSegmentTimingInfo',
  45227. audioSegmentTimingInfo
  45228. });
  45229. });
  45230. transmuxer.on('id3Frame', function (id3Frame) {
  45231. self.postMessage({
  45232. action: 'id3Frame',
  45233. id3Frame
  45234. });
  45235. });
  45236. transmuxer.on('caption', function (caption) {
  45237. self.postMessage({
  45238. action: 'caption',
  45239. caption
  45240. });
  45241. });
  45242. transmuxer.on('trackinfo', function (trackInfo) {
  45243. self.postMessage({
  45244. action: 'trackinfo',
  45245. trackInfo
  45246. });
  45247. });
  45248. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  45249. // convert to video TS since we prioritize video time over audio
  45250. self.postMessage({
  45251. action: 'audioTimingInfo',
  45252. audioTimingInfo: {
  45253. start: clock$2.videoTsToSeconds(audioTimingInfo.start),
  45254. end: clock$2.videoTsToSeconds(audioTimingInfo.end)
  45255. }
  45256. });
  45257. });
  45258. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  45259. self.postMessage({
  45260. action: 'videoTimingInfo',
  45261. videoTimingInfo: {
  45262. start: clock$2.videoTsToSeconds(videoTimingInfo.start),
  45263. end: clock$2.videoTsToSeconds(videoTimingInfo.end)
  45264. }
  45265. });
  45266. });
  45267. transmuxer.on('log', function (log) {
  45268. self.postMessage({
  45269. action: 'log',
  45270. log
  45271. });
  45272. });
  45273. };
  45274. /**
  45275. * All incoming messages route through this hash. If no function exists
  45276. * to handle an incoming message, then we ignore the message.
  45277. *
  45278. * @class MessageHandlers
  45279. * @param {Object} options the options to initialize with
  45280. */
  45281. class MessageHandlers {
  45282. constructor(self, options) {
  45283. this.options = options || {};
  45284. this.self = self;
  45285. this.init();
  45286. }
  45287. /**
  45288. * initialize our web worker and wire all the events.
  45289. */
  45290. init() {
  45291. if (this.transmuxer) {
  45292. this.transmuxer.dispose();
  45293. }
  45294. this.transmuxer = new transmuxer.Transmuxer(this.options);
  45295. wireTransmuxerEvents(this.self, this.transmuxer);
  45296. }
  45297. pushMp4Captions(data) {
  45298. if (!this.captionParser) {
  45299. this.captionParser = new captionParser();
  45300. this.captionParser.init();
  45301. }
  45302. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  45303. const parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  45304. this.self.postMessage({
  45305. action: 'mp4Captions',
  45306. captions: parsed && parsed.captions || [],
  45307. logs: parsed && parsed.logs || [],
  45308. data: segment.buffer
  45309. }, [segment.buffer]);
  45310. }
  45311. probeMp4StartTime({
  45312. timescales,
  45313. data
  45314. }) {
  45315. const startTime = probe$2.startTime(timescales, data);
  45316. this.self.postMessage({
  45317. action: 'probeMp4StartTime',
  45318. startTime,
  45319. data
  45320. }, [data.buffer]);
  45321. }
  45322. probeMp4Tracks({
  45323. data
  45324. }) {
  45325. const tracks = probe$2.tracks(data);
  45326. this.self.postMessage({
  45327. action: 'probeMp4Tracks',
  45328. tracks,
  45329. data
  45330. }, [data.buffer]);
  45331. }
  45332. /**
  45333. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  45334. * internal "media time," as well as whether it contains video and/or audio.
  45335. *
  45336. * @private
  45337. * @param {Uint8Array} bytes - segment bytes
  45338. * @param {number} baseStartTime
  45339. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  45340. * This value should be in seconds, as it's converted to a 90khz clock within the
  45341. * function body.
  45342. * @return {Object} The start time of the current segment in "media time" as well as
  45343. * whether it contains video and/or audio
  45344. */
  45345. probeTs({
  45346. data,
  45347. baseStartTime
  45348. }) {
  45349. const tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock$2.ONE_SECOND_IN_TS : void 0;
  45350. const timeInfo = tsInspector.inspect(data, tsStartTime);
  45351. let result = null;
  45352. if (timeInfo) {
  45353. result = {
  45354. // each type's time info comes back as an array of 2 times, start and end
  45355. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  45356. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  45357. };
  45358. if (result.hasVideo) {
  45359. result.videoStart = timeInfo.video[0].ptsTime;
  45360. }
  45361. if (result.hasAudio) {
  45362. result.audioStart = timeInfo.audio[0].ptsTime;
  45363. }
  45364. }
  45365. this.self.postMessage({
  45366. action: 'probeTs',
  45367. result,
  45368. data
  45369. }, [data.buffer]);
  45370. }
  45371. clearAllMp4Captions() {
  45372. if (this.captionParser) {
  45373. this.captionParser.clearAllCaptions();
  45374. }
  45375. }
  45376. clearParsedMp4Captions() {
  45377. if (this.captionParser) {
  45378. this.captionParser.clearParsedCaptions();
  45379. }
  45380. }
  45381. /**
  45382. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  45383. * processing.
  45384. *
  45385. * @param {ArrayBuffer} data data to push into the muxer
  45386. */
  45387. push(data) {
  45388. // Cast array buffer to correct type for transmuxer
  45389. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  45390. this.transmuxer.push(segment);
  45391. }
  45392. /**
  45393. * Recreate the transmuxer so that the next segment added via `push`
  45394. * start with a fresh transmuxer.
  45395. */
  45396. reset() {
  45397. this.transmuxer.reset();
  45398. }
  45399. /**
  45400. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  45401. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  45402. * set relative to the first based on the PTS values.
  45403. *
  45404. * @param {Object} data used to set the timestamp offset in the muxer
  45405. */
  45406. setTimestampOffset(data) {
  45407. const timestampOffset = data.timestampOffset || 0;
  45408. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock$2.secondsToVideoTs(timestampOffset)));
  45409. }
  45410. setAudioAppendStart(data) {
  45411. this.transmuxer.setAudioAppendStart(Math.ceil(clock$2.secondsToVideoTs(data.appendStart)));
  45412. }
  45413. setRemux(data) {
  45414. this.transmuxer.setRemux(data.remux);
  45415. }
  45416. /**
  45417. * Forces the pipeline to finish processing the last segment and emit it's
  45418. * results.
  45419. *
  45420. * @param {Object} data event data, not really used
  45421. */
  45422. flush(data) {
  45423. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  45424. self.postMessage({
  45425. action: 'done',
  45426. type: 'transmuxed'
  45427. });
  45428. }
  45429. endTimeline() {
  45430. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  45431. // timelines
  45432. self.postMessage({
  45433. action: 'endedtimeline',
  45434. type: 'transmuxed'
  45435. });
  45436. }
  45437. alignGopsWith(data) {
  45438. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  45439. }
  45440. }
  45441. /**
  45442. * Our web worker interface so that things can talk to mux.js
  45443. * that will be running in a web worker. the scope is passed to this by
  45444. * webworkify.
  45445. *
  45446. * @param {Object} self the scope for the web worker
  45447. */
  45448. self.onmessage = function (event) {
  45449. if (event.data.action === 'init' && event.data.options) {
  45450. this.messageHandlers = new MessageHandlers(self, event.data.options);
  45451. return;
  45452. }
  45453. if (!this.messageHandlers) {
  45454. this.messageHandlers = new MessageHandlers(self);
  45455. }
  45456. if (event.data && event.data.action && event.data.action !== 'init') {
  45457. if (this.messageHandlers[event.data.action]) {
  45458. this.messageHandlers[event.data.action](event.data);
  45459. }
  45460. }
  45461. };
  45462. }));
  45463. var TransmuxWorker = factory(workerCode$1);
  45464. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  45465. const handleData_ = (event, transmuxedData, callback) => {
  45466. const {
  45467. type,
  45468. initSegment,
  45469. captions,
  45470. captionStreams,
  45471. metadata,
  45472. videoFrameDtsTime,
  45473. videoFramePtsTime
  45474. } = event.data.segment;
  45475. transmuxedData.buffer.push({
  45476. captions,
  45477. captionStreams,
  45478. metadata
  45479. });
  45480. const boxes = event.data.segment.boxes || {
  45481. data: event.data.segment.data
  45482. };
  45483. const result = {
  45484. type,
  45485. // cast ArrayBuffer to TypedArray
  45486. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  45487. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  45488. };
  45489. if (typeof videoFrameDtsTime !== 'undefined') {
  45490. result.videoFrameDtsTime = videoFrameDtsTime;
  45491. }
  45492. if (typeof videoFramePtsTime !== 'undefined') {
  45493. result.videoFramePtsTime = videoFramePtsTime;
  45494. }
  45495. callback(result);
  45496. };
  45497. const handleDone_ = ({
  45498. transmuxedData,
  45499. callback
  45500. }) => {
  45501. // Previously we only returned data on data events,
  45502. // not on done events. Clear out the buffer to keep that consistent.
  45503. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  45504. // have received
  45505. callback(transmuxedData);
  45506. };
  45507. const handleGopInfo_ = (event, transmuxedData) => {
  45508. transmuxedData.gopInfo = event.data.gopInfo;
  45509. };
  45510. const processTransmux = options => {
  45511. const {
  45512. transmuxer,
  45513. bytes,
  45514. audioAppendStart,
  45515. gopsToAlignWith,
  45516. remux,
  45517. onData,
  45518. onTrackInfo,
  45519. onAudioTimingInfo,
  45520. onVideoTimingInfo,
  45521. onVideoSegmentTimingInfo,
  45522. onAudioSegmentTimingInfo,
  45523. onId3,
  45524. onCaptions,
  45525. onDone,
  45526. onEndedTimeline,
  45527. onTransmuxerLog,
  45528. isEndOfTimeline
  45529. } = options;
  45530. const transmuxedData = {
  45531. buffer: []
  45532. };
  45533. let waitForEndedTimelineEvent = isEndOfTimeline;
  45534. const handleMessage = event => {
  45535. if (transmuxer.currentTransmux !== options) {
  45536. // disposed
  45537. return;
  45538. }
  45539. if (event.data.action === 'data') {
  45540. handleData_(event, transmuxedData, onData);
  45541. }
  45542. if (event.data.action === 'trackinfo') {
  45543. onTrackInfo(event.data.trackInfo);
  45544. }
  45545. if (event.data.action === 'gopInfo') {
  45546. handleGopInfo_(event, transmuxedData);
  45547. }
  45548. if (event.data.action === 'audioTimingInfo') {
  45549. onAudioTimingInfo(event.data.audioTimingInfo);
  45550. }
  45551. if (event.data.action === 'videoTimingInfo') {
  45552. onVideoTimingInfo(event.data.videoTimingInfo);
  45553. }
  45554. if (event.data.action === 'videoSegmentTimingInfo') {
  45555. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  45556. }
  45557. if (event.data.action === 'audioSegmentTimingInfo') {
  45558. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  45559. }
  45560. if (event.data.action === 'id3Frame') {
  45561. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  45562. }
  45563. if (event.data.action === 'caption') {
  45564. onCaptions(event.data.caption);
  45565. }
  45566. if (event.data.action === 'endedtimeline') {
  45567. waitForEndedTimelineEvent = false;
  45568. onEndedTimeline();
  45569. }
  45570. if (event.data.action === 'log') {
  45571. onTransmuxerLog(event.data.log);
  45572. } // wait for the transmuxed event since we may have audio and video
  45573. if (event.data.type !== 'transmuxed') {
  45574. return;
  45575. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  45576. // of a timeline, that means there may still be data events before the segment
  45577. // processing can be considerred complete. In that case, the final event should be
  45578. // an "endedtimeline" event with the type "transmuxed."
  45579. if (waitForEndedTimelineEvent) {
  45580. return;
  45581. }
  45582. transmuxer.onmessage = null;
  45583. handleDone_({
  45584. transmuxedData,
  45585. callback: onDone
  45586. });
  45587. /* eslint-disable no-use-before-define */
  45588. dequeue(transmuxer);
  45589. /* eslint-enable */
  45590. };
  45591. transmuxer.onmessage = handleMessage;
  45592. if (audioAppendStart) {
  45593. transmuxer.postMessage({
  45594. action: 'setAudioAppendStart',
  45595. appendStart: audioAppendStart
  45596. });
  45597. } // allow empty arrays to be passed to clear out GOPs
  45598. if (Array.isArray(gopsToAlignWith)) {
  45599. transmuxer.postMessage({
  45600. action: 'alignGopsWith',
  45601. gopsToAlignWith
  45602. });
  45603. }
  45604. if (typeof remux !== 'undefined') {
  45605. transmuxer.postMessage({
  45606. action: 'setRemux',
  45607. remux
  45608. });
  45609. }
  45610. if (bytes.byteLength) {
  45611. const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  45612. const byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  45613. transmuxer.postMessage({
  45614. action: 'push',
  45615. // Send the typed-array of data as an ArrayBuffer so that
  45616. // it can be sent as a "Transferable" and avoid the costly
  45617. // memory copy
  45618. data: buffer,
  45619. // To recreate the original typed-array, we need information
  45620. // about what portion of the ArrayBuffer it was a view into
  45621. byteOffset,
  45622. byteLength: bytes.byteLength
  45623. }, [buffer]);
  45624. }
  45625. if (isEndOfTimeline) {
  45626. transmuxer.postMessage({
  45627. action: 'endTimeline'
  45628. });
  45629. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  45630. // the end of the segment
  45631. transmuxer.postMessage({
  45632. action: 'flush'
  45633. });
  45634. };
  45635. const dequeue = transmuxer => {
  45636. transmuxer.currentTransmux = null;
  45637. if (transmuxer.transmuxQueue.length) {
  45638. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  45639. if (typeof transmuxer.currentTransmux === 'function') {
  45640. transmuxer.currentTransmux();
  45641. } else {
  45642. processTransmux(transmuxer.currentTransmux);
  45643. }
  45644. }
  45645. };
  45646. const processAction = (transmuxer, action) => {
  45647. transmuxer.postMessage({
  45648. action
  45649. });
  45650. dequeue(transmuxer);
  45651. };
  45652. const enqueueAction = (action, transmuxer) => {
  45653. if (!transmuxer.currentTransmux) {
  45654. transmuxer.currentTransmux = action;
  45655. processAction(transmuxer, action);
  45656. return;
  45657. }
  45658. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  45659. };
  45660. const reset = transmuxer => {
  45661. enqueueAction('reset', transmuxer);
  45662. };
  45663. const endTimeline = transmuxer => {
  45664. enqueueAction('endTimeline', transmuxer);
  45665. };
  45666. const transmux = options => {
  45667. if (!options.transmuxer.currentTransmux) {
  45668. options.transmuxer.currentTransmux = options;
  45669. processTransmux(options);
  45670. return;
  45671. }
  45672. options.transmuxer.transmuxQueue.push(options);
  45673. };
  45674. const createTransmuxer = options => {
  45675. const transmuxer = new TransmuxWorker();
  45676. transmuxer.currentTransmux = null;
  45677. transmuxer.transmuxQueue = [];
  45678. const term = transmuxer.terminate;
  45679. transmuxer.terminate = () => {
  45680. transmuxer.currentTransmux = null;
  45681. transmuxer.transmuxQueue.length = 0;
  45682. return term.call(transmuxer);
  45683. };
  45684. transmuxer.postMessage({
  45685. action: 'init',
  45686. options
  45687. });
  45688. return transmuxer;
  45689. };
  45690. var segmentTransmuxer = {
  45691. reset,
  45692. endTimeline,
  45693. transmux,
  45694. createTransmuxer
  45695. };
  45696. const workerCallback = function (options) {
  45697. const transmuxer = options.transmuxer;
  45698. const endAction = options.endAction || options.action;
  45699. const callback = options.callback;
  45700. const message = _extends$1({}, options, {
  45701. endAction: null,
  45702. transmuxer: null,
  45703. callback: null
  45704. });
  45705. const listenForEndEvent = event => {
  45706. if (event.data.action !== endAction) {
  45707. return;
  45708. }
  45709. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  45710. if (event.data.data) {
  45711. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  45712. if (options.data) {
  45713. options.data = event.data.data;
  45714. }
  45715. }
  45716. callback(event.data);
  45717. };
  45718. transmuxer.addEventListener('message', listenForEndEvent);
  45719. if (options.data) {
  45720. const isArrayBuffer = options.data instanceof ArrayBuffer;
  45721. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  45722. message.byteLength = options.data.byteLength;
  45723. const transfers = [isArrayBuffer ? options.data : options.data.buffer];
  45724. transmuxer.postMessage(message, transfers);
  45725. } else {
  45726. transmuxer.postMessage(message);
  45727. }
  45728. };
  45729. const REQUEST_ERRORS = {
  45730. FAILURE: 2,
  45731. TIMEOUT: -101,
  45732. ABORTED: -102
  45733. };
  45734. /**
  45735. * Abort all requests
  45736. *
  45737. * @param {Object} activeXhrs - an object that tracks all XHR requests
  45738. */
  45739. const abortAll = activeXhrs => {
  45740. activeXhrs.forEach(xhr => {
  45741. xhr.abort();
  45742. });
  45743. };
  45744. /**
  45745. * Gather important bandwidth stats once a request has completed
  45746. *
  45747. * @param {Object} request - the XHR request from which to gather stats
  45748. */
  45749. const getRequestStats = request => {
  45750. return {
  45751. bandwidth: request.bandwidth,
  45752. bytesReceived: request.bytesReceived || 0,
  45753. roundTripTime: request.roundTripTime || 0
  45754. };
  45755. };
  45756. /**
  45757. * If possible gather bandwidth stats as a request is in
  45758. * progress
  45759. *
  45760. * @param {Event} progressEvent - an event object from an XHR's progress event
  45761. */
  45762. const getProgressStats = progressEvent => {
  45763. const request = progressEvent.target;
  45764. const roundTripTime = Date.now() - request.requestTime;
  45765. const stats = {
  45766. bandwidth: Infinity,
  45767. bytesReceived: 0,
  45768. roundTripTime: roundTripTime || 0
  45769. };
  45770. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  45771. // because we should only use bandwidth stats on progress to determine when
  45772. // abort a request early due to insufficient bandwidth
  45773. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  45774. return stats;
  45775. };
  45776. /**
  45777. * Handle all error conditions in one place and return an object
  45778. * with all the information
  45779. *
  45780. * @param {Error|null} error - if non-null signals an error occured with the XHR
  45781. * @param {Object} request - the XHR request that possibly generated the error
  45782. */
  45783. const handleErrors = (error, request) => {
  45784. if (request.timedout) {
  45785. return {
  45786. status: request.status,
  45787. message: 'HLS request timed-out at URL: ' + request.uri,
  45788. code: REQUEST_ERRORS.TIMEOUT,
  45789. xhr: request
  45790. };
  45791. }
  45792. if (request.aborted) {
  45793. return {
  45794. status: request.status,
  45795. message: 'HLS request aborted at URL: ' + request.uri,
  45796. code: REQUEST_ERRORS.ABORTED,
  45797. xhr: request
  45798. };
  45799. }
  45800. if (error) {
  45801. return {
  45802. status: request.status,
  45803. message: 'HLS request errored at URL: ' + request.uri,
  45804. code: REQUEST_ERRORS.FAILURE,
  45805. xhr: request
  45806. };
  45807. }
  45808. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  45809. return {
  45810. status: request.status,
  45811. message: 'Empty HLS response at URL: ' + request.uri,
  45812. code: REQUEST_ERRORS.FAILURE,
  45813. xhr: request
  45814. };
  45815. }
  45816. return null;
  45817. };
  45818. /**
  45819. * Handle responses for key data and convert the key data to the correct format
  45820. * for the decryption step later
  45821. *
  45822. * @param {Object} segment - a simplified copy of the segmentInfo object
  45823. * from SegmentLoader
  45824. * @param {Array} objects - objects to add the key bytes to.
  45825. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  45826. * this request
  45827. */
  45828. const handleKeyResponse = (segment, objects, finishProcessingFn) => (error, request) => {
  45829. const response = request.response;
  45830. const errorObj = handleErrors(error, request);
  45831. if (errorObj) {
  45832. return finishProcessingFn(errorObj, segment);
  45833. }
  45834. if (response.byteLength !== 16) {
  45835. return finishProcessingFn({
  45836. status: request.status,
  45837. message: 'Invalid HLS key at URL: ' + request.uri,
  45838. code: REQUEST_ERRORS.FAILURE,
  45839. xhr: request
  45840. }, segment);
  45841. }
  45842. const view = new DataView(response);
  45843. const bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  45844. for (let i = 0; i < objects.length; i++) {
  45845. objects[i].bytes = bytes;
  45846. }
  45847. return finishProcessingFn(null, segment);
  45848. };
  45849. const parseInitSegment = (segment, callback) => {
  45850. const type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  45851. // only know how to parse mp4 init segments at the moment
  45852. if (type !== 'mp4') {
  45853. const uri = segment.map.resolvedUri || segment.map.uri;
  45854. return callback({
  45855. internal: true,
  45856. message: `Found unsupported ${type || 'unknown'} container for initialization segment at URL: ${uri}`,
  45857. code: REQUEST_ERRORS.FAILURE
  45858. });
  45859. }
  45860. workerCallback({
  45861. action: 'probeMp4Tracks',
  45862. data: segment.map.bytes,
  45863. transmuxer: segment.transmuxer,
  45864. callback: ({
  45865. tracks,
  45866. data
  45867. }) => {
  45868. // transfer bytes back to us
  45869. segment.map.bytes = data;
  45870. tracks.forEach(function (track) {
  45871. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  45872. if (segment.map.tracks[track.type]) {
  45873. return;
  45874. }
  45875. segment.map.tracks[track.type] = track;
  45876. if (typeof track.id === 'number' && track.timescale) {
  45877. segment.map.timescales = segment.map.timescales || {};
  45878. segment.map.timescales[track.id] = track.timescale;
  45879. }
  45880. });
  45881. return callback(null);
  45882. }
  45883. });
  45884. };
  45885. /**
  45886. * Handle init-segment responses
  45887. *
  45888. * @param {Object} segment - a simplified copy of the segmentInfo object
  45889. * from SegmentLoader
  45890. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  45891. * this request
  45892. */
  45893. const handleInitSegmentResponse = ({
  45894. segment,
  45895. finishProcessingFn
  45896. }) => (error, request) => {
  45897. const errorObj = handleErrors(error, request);
  45898. if (errorObj) {
  45899. return finishProcessingFn(errorObj, segment);
  45900. }
  45901. const bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  45902. // until the key request is done to decrypt.
  45903. if (segment.map.key) {
  45904. segment.map.encryptedBytes = bytes;
  45905. return finishProcessingFn(null, segment);
  45906. }
  45907. segment.map.bytes = bytes;
  45908. parseInitSegment(segment, function (parseError) {
  45909. if (parseError) {
  45910. parseError.xhr = request;
  45911. parseError.status = request.status;
  45912. return finishProcessingFn(parseError, segment);
  45913. }
  45914. finishProcessingFn(null, segment);
  45915. });
  45916. };
  45917. /**
  45918. * Response handler for segment-requests being sure to set the correct
  45919. * property depending on whether the segment is encryped or not
  45920. * Also records and keeps track of stats that are used for ABR purposes
  45921. *
  45922. * @param {Object} segment - a simplified copy of the segmentInfo object
  45923. * from SegmentLoader
  45924. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  45925. * this request
  45926. */
  45927. const handleSegmentResponse = ({
  45928. segment,
  45929. finishProcessingFn,
  45930. responseType
  45931. }) => (error, request) => {
  45932. const errorObj = handleErrors(error, request);
  45933. if (errorObj) {
  45934. return finishProcessingFn(errorObj, segment);
  45935. }
  45936. const newBytes =
  45937. // although responseText "should" exist, this guard serves to prevent an error being
  45938. // thrown for two primary cases:
  45939. // 1. the mime type override stops working, or is not implemented for a specific
  45940. // browser
  45941. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  45942. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  45943. segment.stats = getRequestStats(request);
  45944. if (segment.key) {
  45945. segment.encryptedBytes = new Uint8Array(newBytes);
  45946. } else {
  45947. segment.bytes = new Uint8Array(newBytes);
  45948. }
  45949. return finishProcessingFn(null, segment);
  45950. };
  45951. const transmuxAndNotify = ({
  45952. segment,
  45953. bytes,
  45954. trackInfoFn,
  45955. timingInfoFn,
  45956. videoSegmentTimingInfoFn,
  45957. audioSegmentTimingInfoFn,
  45958. id3Fn,
  45959. captionsFn,
  45960. isEndOfTimeline,
  45961. endedTimelineFn,
  45962. dataFn,
  45963. doneFn,
  45964. onTransmuxerLog
  45965. }) => {
  45966. const fmp4Tracks = segment.map && segment.map.tracks || {};
  45967. const isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  45968. // One reason for this is that in the case of full segments, we want to trust start
  45969. // times from the probe, rather than the transmuxer.
  45970. let audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  45971. const audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  45972. let videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  45973. const videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  45974. const finish = () => transmux({
  45975. bytes,
  45976. transmuxer: segment.transmuxer,
  45977. audioAppendStart: segment.audioAppendStart,
  45978. gopsToAlignWith: segment.gopsToAlignWith,
  45979. remux: isMuxed,
  45980. onData: result => {
  45981. result.type = result.type === 'combined' ? 'video' : result.type;
  45982. dataFn(segment, result);
  45983. },
  45984. onTrackInfo: trackInfo => {
  45985. if (trackInfoFn) {
  45986. if (isMuxed) {
  45987. trackInfo.isMuxed = true;
  45988. }
  45989. trackInfoFn(segment, trackInfo);
  45990. }
  45991. },
  45992. onAudioTimingInfo: audioTimingInfo => {
  45993. // we only want the first start value we encounter
  45994. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  45995. audioStartFn(audioTimingInfo.start);
  45996. audioStartFn = null;
  45997. } // we want to continually update the end time
  45998. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  45999. audioEndFn(audioTimingInfo.end);
  46000. }
  46001. },
  46002. onVideoTimingInfo: videoTimingInfo => {
  46003. // we only want the first start value we encounter
  46004. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  46005. videoStartFn(videoTimingInfo.start);
  46006. videoStartFn = null;
  46007. } // we want to continually update the end time
  46008. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  46009. videoEndFn(videoTimingInfo.end);
  46010. }
  46011. },
  46012. onVideoSegmentTimingInfo: videoSegmentTimingInfo => {
  46013. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  46014. },
  46015. onAudioSegmentTimingInfo: audioSegmentTimingInfo => {
  46016. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  46017. },
  46018. onId3: (id3Frames, dispatchType) => {
  46019. id3Fn(segment, id3Frames, dispatchType);
  46020. },
  46021. onCaptions: captions => {
  46022. captionsFn(segment, [captions]);
  46023. },
  46024. isEndOfTimeline,
  46025. onEndedTimeline: () => {
  46026. endedTimelineFn();
  46027. },
  46028. onTransmuxerLog,
  46029. onDone: result => {
  46030. if (!doneFn) {
  46031. return;
  46032. }
  46033. result.type = result.type === 'combined' ? 'video' : result.type;
  46034. doneFn(null, segment, result);
  46035. }
  46036. }); // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  46037. // Meaning cached frame data may corrupt our notion of where this segment
  46038. // really starts. To get around this, probe for the info needed.
  46039. workerCallback({
  46040. action: 'probeTs',
  46041. transmuxer: segment.transmuxer,
  46042. data: bytes,
  46043. baseStartTime: segment.baseStartTime,
  46044. callback: data => {
  46045. segment.bytes = bytes = data.data;
  46046. const probeResult = data.result;
  46047. if (probeResult) {
  46048. trackInfoFn(segment, {
  46049. hasAudio: probeResult.hasAudio,
  46050. hasVideo: probeResult.hasVideo,
  46051. isMuxed
  46052. });
  46053. trackInfoFn = null;
  46054. if (probeResult.hasAudio && !isMuxed) {
  46055. audioStartFn(probeResult.audioStart);
  46056. }
  46057. if (probeResult.hasVideo) {
  46058. videoStartFn(probeResult.videoStart);
  46059. }
  46060. audioStartFn = null;
  46061. videoStartFn = null;
  46062. }
  46063. finish();
  46064. }
  46065. });
  46066. };
  46067. const handleSegmentBytes = ({
  46068. segment,
  46069. bytes,
  46070. trackInfoFn,
  46071. timingInfoFn,
  46072. videoSegmentTimingInfoFn,
  46073. audioSegmentTimingInfoFn,
  46074. id3Fn,
  46075. captionsFn,
  46076. isEndOfTimeline,
  46077. endedTimelineFn,
  46078. dataFn,
  46079. doneFn,
  46080. onTransmuxerLog
  46081. }) => {
  46082. let bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  46083. // We should have a handler that fetches the number of bytes required
  46084. // to check if something is fmp4. This will allow us to save bandwidth
  46085. // because we can only exclude a playlist and abort requests
  46086. // by codec after trackinfo triggers.
  46087. if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  46088. segment.isFmp4 = true;
  46089. const {
  46090. tracks
  46091. } = segment.map;
  46092. const trackInfo = {
  46093. isFmp4: true,
  46094. hasVideo: !!tracks.video,
  46095. hasAudio: !!tracks.audio
  46096. }; // if we have a audio track, with a codec that is not set to
  46097. // encrypted audio
  46098. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  46099. trackInfo.audioCodec = tracks.audio.codec;
  46100. } // if we have a video track, with a codec that is not set to
  46101. // encrypted video
  46102. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  46103. trackInfo.videoCodec = tracks.video.codec;
  46104. }
  46105. if (tracks.video && tracks.audio) {
  46106. trackInfo.isMuxed = true;
  46107. } // since we don't support appending fmp4 data on progress, we know we have the full
  46108. // segment here
  46109. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  46110. // time. The end time can be roughly calculated by the receiver using the duration.
  46111. //
  46112. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  46113. // that is the true start of the segment (where the playback engine should begin
  46114. // decoding).
  46115. const finishLoading = captions => {
  46116. // if the track still has audio at this point it is only possible
  46117. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  46118. // above.
  46119. // we make sure to use segment.bytes here as that
  46120. dataFn(segment, {
  46121. data: bytesAsUint8Array,
  46122. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  46123. });
  46124. if (captions && captions.length) {
  46125. captionsFn(segment, captions);
  46126. }
  46127. doneFn(null, segment, {});
  46128. };
  46129. workerCallback({
  46130. action: 'probeMp4StartTime',
  46131. timescales: segment.map.timescales,
  46132. data: bytesAsUint8Array,
  46133. transmuxer: segment.transmuxer,
  46134. callback: ({
  46135. data,
  46136. startTime
  46137. }) => {
  46138. // transfer bytes back to us
  46139. bytes = data.buffer;
  46140. segment.bytes = bytesAsUint8Array = data;
  46141. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  46142. timingInfoFn(segment, 'audio', 'start', startTime);
  46143. }
  46144. if (trackInfo.hasVideo) {
  46145. timingInfoFn(segment, 'video', 'start', startTime);
  46146. } // Run through the CaptionParser in case there are captions.
  46147. // Initialize CaptionParser if it hasn't been yet
  46148. if (!tracks.video || !data.byteLength || !segment.transmuxer) {
  46149. finishLoading();
  46150. return;
  46151. }
  46152. workerCallback({
  46153. action: 'pushMp4Captions',
  46154. endAction: 'mp4Captions',
  46155. transmuxer: segment.transmuxer,
  46156. data: bytesAsUint8Array,
  46157. timescales: segment.map.timescales,
  46158. trackIds: [tracks.video.id],
  46159. callback: message => {
  46160. // transfer bytes back to us
  46161. bytes = message.data.buffer;
  46162. segment.bytes = bytesAsUint8Array = message.data;
  46163. message.logs.forEach(function (log) {
  46164. onTransmuxerLog(merge(log, {
  46165. stream: 'mp4CaptionParser'
  46166. }));
  46167. });
  46168. finishLoading(message.captions);
  46169. }
  46170. });
  46171. }
  46172. });
  46173. return;
  46174. } // VTT or other segments that don't need processing
  46175. if (!segment.transmuxer) {
  46176. doneFn(null, segment, {});
  46177. return;
  46178. }
  46179. if (typeof segment.container === 'undefined') {
  46180. segment.container = detectContainerForBytes(bytesAsUint8Array);
  46181. }
  46182. if (segment.container !== 'ts' && segment.container !== 'aac') {
  46183. trackInfoFn(segment, {
  46184. hasAudio: false,
  46185. hasVideo: false
  46186. });
  46187. doneFn(null, segment, {});
  46188. return;
  46189. } // ts or aac
  46190. transmuxAndNotify({
  46191. segment,
  46192. bytes,
  46193. trackInfoFn,
  46194. timingInfoFn,
  46195. videoSegmentTimingInfoFn,
  46196. audioSegmentTimingInfoFn,
  46197. id3Fn,
  46198. captionsFn,
  46199. isEndOfTimeline,
  46200. endedTimelineFn,
  46201. dataFn,
  46202. doneFn,
  46203. onTransmuxerLog
  46204. });
  46205. };
  46206. const decrypt = function ({
  46207. id,
  46208. key,
  46209. encryptedBytes,
  46210. decryptionWorker
  46211. }, callback) {
  46212. const decryptionHandler = event => {
  46213. if (event.data.source === id) {
  46214. decryptionWorker.removeEventListener('message', decryptionHandler);
  46215. const decrypted = event.data.decrypted;
  46216. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  46217. }
  46218. };
  46219. decryptionWorker.addEventListener('message', decryptionHandler);
  46220. let keyBytes;
  46221. if (key.bytes.slice) {
  46222. keyBytes = key.bytes.slice();
  46223. } else {
  46224. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  46225. } // incrementally decrypt the bytes
  46226. decryptionWorker.postMessage(createTransferableMessage({
  46227. source: id,
  46228. encrypted: encryptedBytes,
  46229. key: keyBytes,
  46230. iv: key.iv
  46231. }), [encryptedBytes.buffer, keyBytes.buffer]);
  46232. };
  46233. /**
  46234. * Decrypt the segment via the decryption web worker
  46235. *
  46236. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  46237. * routines
  46238. * @param {Object} segment - a simplified copy of the segmentInfo object
  46239. * from SegmentLoader
  46240. * @param {Function} trackInfoFn - a callback that receives track info
  46241. * @param {Function} timingInfoFn - a callback that receives timing info
  46242. * @param {Function} videoSegmentTimingInfoFn
  46243. * a callback that receives video timing info based on media times and
  46244. * any adjustments made by the transmuxer
  46245. * @param {Function} audioSegmentTimingInfoFn
  46246. * a callback that receives audio timing info based on media times and
  46247. * any adjustments made by the transmuxer
  46248. * @param {boolean} isEndOfTimeline
  46249. * true if this segment represents the last segment in a timeline
  46250. * @param {Function} endedTimelineFn
  46251. * a callback made when a timeline is ended, will only be called if
  46252. * isEndOfTimeline is true
  46253. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  46254. * and ready to use
  46255. * @param {Function} doneFn - a callback that is executed after decryption has completed
  46256. */
  46257. const decryptSegment = ({
  46258. decryptionWorker,
  46259. segment,
  46260. trackInfoFn,
  46261. timingInfoFn,
  46262. videoSegmentTimingInfoFn,
  46263. audioSegmentTimingInfoFn,
  46264. id3Fn,
  46265. captionsFn,
  46266. isEndOfTimeline,
  46267. endedTimelineFn,
  46268. dataFn,
  46269. doneFn,
  46270. onTransmuxerLog
  46271. }) => {
  46272. decrypt({
  46273. id: segment.requestId,
  46274. key: segment.key,
  46275. encryptedBytes: segment.encryptedBytes,
  46276. decryptionWorker
  46277. }, decryptedBytes => {
  46278. segment.bytes = decryptedBytes;
  46279. handleSegmentBytes({
  46280. segment,
  46281. bytes: segment.bytes,
  46282. trackInfoFn,
  46283. timingInfoFn,
  46284. videoSegmentTimingInfoFn,
  46285. audioSegmentTimingInfoFn,
  46286. id3Fn,
  46287. captionsFn,
  46288. isEndOfTimeline,
  46289. endedTimelineFn,
  46290. dataFn,
  46291. doneFn,
  46292. onTransmuxerLog
  46293. });
  46294. });
  46295. };
  46296. /**
  46297. * This function waits for all XHRs to finish (with either success or failure)
  46298. * before continueing processing via it's callback. The function gathers errors
  46299. * from each request into a single errors array so that the error status for
  46300. * each request can be examined later.
  46301. *
  46302. * @param {Object} activeXhrs - an object that tracks all XHR requests
  46303. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  46304. * routines
  46305. * @param {Function} trackInfoFn - a callback that receives track info
  46306. * @param {Function} timingInfoFn - a callback that receives timing info
  46307. * @param {Function} videoSegmentTimingInfoFn
  46308. * a callback that receives video timing info based on media times and
  46309. * any adjustments made by the transmuxer
  46310. * @param {Function} audioSegmentTimingInfoFn
  46311. * a callback that receives audio timing info based on media times and
  46312. * any adjustments made by the transmuxer
  46313. * @param {Function} id3Fn - a callback that receives ID3 metadata
  46314. * @param {Function} captionsFn - a callback that receives captions
  46315. * @param {boolean} isEndOfTimeline
  46316. * true if this segment represents the last segment in a timeline
  46317. * @param {Function} endedTimelineFn
  46318. * a callback made when a timeline is ended, will only be called if
  46319. * isEndOfTimeline is true
  46320. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  46321. * and ready to use
  46322. * @param {Function} doneFn - a callback that is executed after all resources have been
  46323. * downloaded and any decryption completed
  46324. */
  46325. const waitForCompletion = ({
  46326. activeXhrs,
  46327. decryptionWorker,
  46328. trackInfoFn,
  46329. timingInfoFn,
  46330. videoSegmentTimingInfoFn,
  46331. audioSegmentTimingInfoFn,
  46332. id3Fn,
  46333. captionsFn,
  46334. isEndOfTimeline,
  46335. endedTimelineFn,
  46336. dataFn,
  46337. doneFn,
  46338. onTransmuxerLog
  46339. }) => {
  46340. let count = 0;
  46341. let didError = false;
  46342. return (error, segment) => {
  46343. if (didError) {
  46344. return;
  46345. }
  46346. if (error) {
  46347. didError = true; // If there are errors, we have to abort any outstanding requests
  46348. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  46349. // handle the aborted events from those requests, there are some cases where we may
  46350. // never get an aborted event. For instance, if the network connection is lost and
  46351. // there were two requests, the first may have triggered an error immediately, while
  46352. // the second request remains unsent. In that case, the aborted algorithm will not
  46353. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  46354. //
  46355. // We also can't rely on the ready state of the XHR, since the request that
  46356. // triggered the connection error may also show as a ready state of 0 (unsent).
  46357. // Therefore, we have to finish this group of requests immediately after the first
  46358. // seen error.
  46359. return doneFn(error, segment);
  46360. }
  46361. count += 1;
  46362. if (count === activeXhrs.length) {
  46363. const segmentFinish = function () {
  46364. if (segment.encryptedBytes) {
  46365. return decryptSegment({
  46366. decryptionWorker,
  46367. segment,
  46368. trackInfoFn,
  46369. timingInfoFn,
  46370. videoSegmentTimingInfoFn,
  46371. audioSegmentTimingInfoFn,
  46372. id3Fn,
  46373. captionsFn,
  46374. isEndOfTimeline,
  46375. endedTimelineFn,
  46376. dataFn,
  46377. doneFn,
  46378. onTransmuxerLog
  46379. });
  46380. } // Otherwise, everything is ready just continue
  46381. handleSegmentBytes({
  46382. segment,
  46383. bytes: segment.bytes,
  46384. trackInfoFn,
  46385. timingInfoFn,
  46386. videoSegmentTimingInfoFn,
  46387. audioSegmentTimingInfoFn,
  46388. id3Fn,
  46389. captionsFn,
  46390. isEndOfTimeline,
  46391. endedTimelineFn,
  46392. dataFn,
  46393. doneFn,
  46394. onTransmuxerLog
  46395. });
  46396. }; // Keep track of when *all* of the requests have completed
  46397. segment.endOfAllRequests = Date.now();
  46398. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  46399. return decrypt({
  46400. decryptionWorker,
  46401. // add -init to the "id" to differentiate between segment
  46402. // and init segment decryption, just in case they happen
  46403. // at the same time at some point in the future.
  46404. id: segment.requestId + '-init',
  46405. encryptedBytes: segment.map.encryptedBytes,
  46406. key: segment.map.key
  46407. }, decryptedBytes => {
  46408. segment.map.bytes = decryptedBytes;
  46409. parseInitSegment(segment, parseError => {
  46410. if (parseError) {
  46411. abortAll(activeXhrs);
  46412. return doneFn(parseError, segment);
  46413. }
  46414. segmentFinish();
  46415. });
  46416. });
  46417. }
  46418. segmentFinish();
  46419. }
  46420. };
  46421. };
  46422. /**
  46423. * Calls the abort callback if any request within the batch was aborted. Will only call
  46424. * the callback once per batch of requests, even if multiple were aborted.
  46425. *
  46426. * @param {Object} loadendState - state to check to see if the abort function was called
  46427. * @param {Function} abortFn - callback to call for abort
  46428. */
  46429. const handleLoadEnd = ({
  46430. loadendState,
  46431. abortFn
  46432. }) => event => {
  46433. const request = event.target;
  46434. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  46435. abortFn();
  46436. loadendState.calledAbortFn = true;
  46437. }
  46438. };
  46439. /**
  46440. * Simple progress event callback handler that gathers some stats before
  46441. * executing a provided callback with the `segment` object
  46442. *
  46443. * @param {Object} segment - a simplified copy of the segmentInfo object
  46444. * from SegmentLoader
  46445. * @param {Function} progressFn - a callback that is executed each time a progress event
  46446. * is received
  46447. * @param {Function} trackInfoFn - a callback that receives track info
  46448. * @param {Function} timingInfoFn - a callback that receives timing info
  46449. * @param {Function} videoSegmentTimingInfoFn
  46450. * a callback that receives video timing info based on media times and
  46451. * any adjustments made by the transmuxer
  46452. * @param {Function} audioSegmentTimingInfoFn
  46453. * a callback that receives audio timing info based on media times and
  46454. * any adjustments made by the transmuxer
  46455. * @param {boolean} isEndOfTimeline
  46456. * true if this segment represents the last segment in a timeline
  46457. * @param {Function} endedTimelineFn
  46458. * a callback made when a timeline is ended, will only be called if
  46459. * isEndOfTimeline is true
  46460. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  46461. * and ready to use
  46462. * @param {Event} event - the progress event object from XMLHttpRequest
  46463. */
  46464. const handleProgress = ({
  46465. segment,
  46466. progressFn,
  46467. trackInfoFn,
  46468. timingInfoFn,
  46469. videoSegmentTimingInfoFn,
  46470. audioSegmentTimingInfoFn,
  46471. id3Fn,
  46472. captionsFn,
  46473. isEndOfTimeline,
  46474. endedTimelineFn,
  46475. dataFn
  46476. }) => event => {
  46477. const request = event.target;
  46478. if (request.aborted) {
  46479. return;
  46480. }
  46481. segment.stats = merge(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  46482. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  46483. segment.stats.firstBytesReceivedAt = Date.now();
  46484. }
  46485. return progressFn(event, segment);
  46486. };
  46487. /**
  46488. * Load all resources and does any processing necessary for a media-segment
  46489. *
  46490. * Features:
  46491. * decrypts the media-segment if it has a key uri and an iv
  46492. * aborts *all* requests if *any* one request fails
  46493. *
  46494. * The segment object, at minimum, has the following format:
  46495. * {
  46496. * resolvedUri: String,
  46497. * [transmuxer]: Object,
  46498. * [byterange]: {
  46499. * offset: Number,
  46500. * length: Number
  46501. * },
  46502. * [key]: {
  46503. * resolvedUri: String
  46504. * [byterange]: {
  46505. * offset: Number,
  46506. * length: Number
  46507. * },
  46508. * iv: {
  46509. * bytes: Uint32Array
  46510. * }
  46511. * },
  46512. * [map]: {
  46513. * resolvedUri: String,
  46514. * [byterange]: {
  46515. * offset: Number,
  46516. * length: Number
  46517. * },
  46518. * [bytes]: Uint8Array
  46519. * }
  46520. * }
  46521. * ...where [name] denotes optional properties
  46522. *
  46523. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  46524. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  46525. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  46526. * decryption routines
  46527. * @param {Object} segment - a simplified copy of the segmentInfo object
  46528. * from SegmentLoader
  46529. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  46530. * aborted
  46531. * @param {Function} progressFn - a callback that receives progress events from the main
  46532. * segment's xhr request
  46533. * @param {Function} trackInfoFn - a callback that receives track info
  46534. * @param {Function} timingInfoFn - a callback that receives timing info
  46535. * @param {Function} videoSegmentTimingInfoFn
  46536. * a callback that receives video timing info based on media times and
  46537. * any adjustments made by the transmuxer
  46538. * @param {Function} audioSegmentTimingInfoFn
  46539. * a callback that receives audio timing info based on media times and
  46540. * any adjustments made by the transmuxer
  46541. * @param {Function} id3Fn - a callback that receives ID3 metadata
  46542. * @param {Function} captionsFn - a callback that receives captions
  46543. * @param {boolean} isEndOfTimeline
  46544. * true if this segment represents the last segment in a timeline
  46545. * @param {Function} endedTimelineFn
  46546. * a callback made when a timeline is ended, will only be called if
  46547. * isEndOfTimeline is true
  46548. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  46549. * request, transmuxed if needed
  46550. * @param {Function} doneFn - a callback that is executed only once all requests have
  46551. * succeeded or failed
  46552. * @return {Function} a function that, when invoked, immediately aborts all
  46553. * outstanding requests
  46554. */
  46555. const mediaSegmentRequest = ({
  46556. xhr,
  46557. xhrOptions,
  46558. decryptionWorker,
  46559. segment,
  46560. abortFn,
  46561. progressFn,
  46562. trackInfoFn,
  46563. timingInfoFn,
  46564. videoSegmentTimingInfoFn,
  46565. audioSegmentTimingInfoFn,
  46566. id3Fn,
  46567. captionsFn,
  46568. isEndOfTimeline,
  46569. endedTimelineFn,
  46570. dataFn,
  46571. doneFn,
  46572. onTransmuxerLog
  46573. }) => {
  46574. const activeXhrs = [];
  46575. const finishProcessingFn = waitForCompletion({
  46576. activeXhrs,
  46577. decryptionWorker,
  46578. trackInfoFn,
  46579. timingInfoFn,
  46580. videoSegmentTimingInfoFn,
  46581. audioSegmentTimingInfoFn,
  46582. id3Fn,
  46583. captionsFn,
  46584. isEndOfTimeline,
  46585. endedTimelineFn,
  46586. dataFn,
  46587. doneFn,
  46588. onTransmuxerLog
  46589. }); // optionally, request the decryption key
  46590. if (segment.key && !segment.key.bytes) {
  46591. const objects = [segment.key];
  46592. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  46593. objects.push(segment.map.key);
  46594. }
  46595. const keyRequestOptions = merge(xhrOptions, {
  46596. uri: segment.key.resolvedUri,
  46597. responseType: 'arraybuffer'
  46598. });
  46599. const keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  46600. const keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  46601. activeXhrs.push(keyXhr);
  46602. } // optionally, request the associated media init segment
  46603. if (segment.map && !segment.map.bytes) {
  46604. const differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  46605. if (differentMapKey) {
  46606. const mapKeyRequestOptions = merge(xhrOptions, {
  46607. uri: segment.map.key.resolvedUri,
  46608. responseType: 'arraybuffer'
  46609. });
  46610. const mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  46611. const mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  46612. activeXhrs.push(mapKeyXhr);
  46613. }
  46614. const initSegmentOptions = merge(xhrOptions, {
  46615. uri: segment.map.resolvedUri,
  46616. responseType: 'arraybuffer',
  46617. headers: segmentXhrHeaders(segment.map)
  46618. });
  46619. const initSegmentRequestCallback = handleInitSegmentResponse({
  46620. segment,
  46621. finishProcessingFn
  46622. });
  46623. const initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  46624. activeXhrs.push(initSegmentXhr);
  46625. }
  46626. const segmentRequestOptions = merge(xhrOptions, {
  46627. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  46628. responseType: 'arraybuffer',
  46629. headers: segmentXhrHeaders(segment)
  46630. });
  46631. const segmentRequestCallback = handleSegmentResponse({
  46632. segment,
  46633. finishProcessingFn,
  46634. responseType: segmentRequestOptions.responseType
  46635. });
  46636. const segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  46637. segmentXhr.addEventListener('progress', handleProgress({
  46638. segment,
  46639. progressFn,
  46640. trackInfoFn,
  46641. timingInfoFn,
  46642. videoSegmentTimingInfoFn,
  46643. audioSegmentTimingInfoFn,
  46644. id3Fn,
  46645. captionsFn,
  46646. isEndOfTimeline,
  46647. endedTimelineFn,
  46648. dataFn
  46649. }));
  46650. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  46651. // multiple times, provide a shared state object
  46652. const loadendState = {};
  46653. activeXhrs.forEach(activeXhr => {
  46654. activeXhr.addEventListener('loadend', handleLoadEnd({
  46655. loadendState,
  46656. abortFn
  46657. }));
  46658. });
  46659. return () => abortAll(activeXhrs);
  46660. };
  46661. /**
  46662. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  46663. * codec strings, or translating codec strings into objects that can be examined.
  46664. */
  46665. const logFn$1 = logger('CodecUtils');
  46666. /**
  46667. * Returns a set of codec strings parsed from the playlist or the default
  46668. * codec strings if no codecs were specified in the playlist
  46669. *
  46670. * @param {Playlist} media the current media playlist
  46671. * @return {Object} an object with the video and audio codecs
  46672. */
  46673. const getCodecs = function (media) {
  46674. // if the codecs were explicitly specified, use them instead of the
  46675. // defaults
  46676. const mediaAttributes = media.attributes || {};
  46677. if (mediaAttributes.CODECS) {
  46678. return parseCodecs(mediaAttributes.CODECS);
  46679. }
  46680. };
  46681. const isMaat = (main, media) => {
  46682. const mediaAttributes = media.attributes || {};
  46683. return main && main.mediaGroups && main.mediaGroups.AUDIO && mediaAttributes.AUDIO && main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  46684. };
  46685. const isMuxed = (main, media) => {
  46686. if (!isMaat(main, media)) {
  46687. return true;
  46688. }
  46689. const mediaAttributes = media.attributes || {};
  46690. const audioGroup = main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  46691. for (const groupId in audioGroup) {
  46692. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  46693. // or there are listed playlists (the case for DASH, as the manifest will have already
  46694. // provided all of the details necessary to generate the audio playlist, as opposed to
  46695. // HLS' externally requested playlists), then the content is demuxed.
  46696. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  46697. return true;
  46698. }
  46699. }
  46700. return false;
  46701. };
  46702. const unwrapCodecList = function (codecList) {
  46703. const codecs = {};
  46704. codecList.forEach(({
  46705. mediaType,
  46706. type,
  46707. details
  46708. }) => {
  46709. codecs[mediaType] = codecs[mediaType] || [];
  46710. codecs[mediaType].push(translateLegacyCodec(`${type}${details}`));
  46711. });
  46712. Object.keys(codecs).forEach(function (mediaType) {
  46713. if (codecs[mediaType].length > 1) {
  46714. 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.`);
  46715. codecs[mediaType] = null;
  46716. return;
  46717. }
  46718. codecs[mediaType] = codecs[mediaType][0];
  46719. });
  46720. return codecs;
  46721. };
  46722. const codecCount = function (codecObj) {
  46723. let count = 0;
  46724. if (codecObj.audio) {
  46725. count++;
  46726. }
  46727. if (codecObj.video) {
  46728. count++;
  46729. }
  46730. return count;
  46731. };
  46732. /**
  46733. * Calculates the codec strings for a working configuration of
  46734. * SourceBuffers to play variant streams in a main playlist. If
  46735. * there is no possible working configuration, an empty object will be
  46736. * returned.
  46737. *
  46738. * @param main {Object} the m3u8 object for the main playlist
  46739. * @param media {Object} the m3u8 object for the variant playlist
  46740. * @return {Object} the codec strings.
  46741. *
  46742. * @private
  46743. */
  46744. const codecsForPlaylist = function (main, media) {
  46745. const mediaAttributes = media.attributes || {};
  46746. const codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  46747. // Put another way, there is no way to have a video-only multiple-audio HLS!
  46748. if (isMaat(main, media) && !codecInfo.audio) {
  46749. if (!isMuxed(main, media)) {
  46750. // It is possible for codecs to be specified on the audio media group playlist but
  46751. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  46752. // video are always separate (and separately specified).
  46753. const defaultCodecs = unwrapCodecList(codecsFromDefault(main, mediaAttributes.AUDIO) || []);
  46754. if (defaultCodecs.audio) {
  46755. codecInfo.audio = defaultCodecs.audio;
  46756. }
  46757. }
  46758. }
  46759. return codecInfo;
  46760. };
  46761. const logFn = logger('PlaylistSelector');
  46762. const representationToString = function (representation) {
  46763. if (!representation || !representation.playlist) {
  46764. return;
  46765. }
  46766. const playlist = representation.playlist;
  46767. return JSON.stringify({
  46768. id: playlist.id,
  46769. bandwidth: representation.bandwidth,
  46770. width: representation.width,
  46771. height: representation.height,
  46772. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  46773. });
  46774. }; // Utilities
  46775. /**
  46776. * Returns the CSS value for the specified property on an element
  46777. * using `getComputedStyle`. Firefox has a long-standing issue where
  46778. * getComputedStyle() may return null when running in an iframe with
  46779. * `display: none`.
  46780. *
  46781. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  46782. * @param {HTMLElement} el the htmlelement to work on
  46783. * @param {string} the proprety to get the style for
  46784. */
  46785. const safeGetComputedStyle = function (el, property) {
  46786. if (!el) {
  46787. return '';
  46788. }
  46789. const result = window.getComputedStyle(el);
  46790. if (!result) {
  46791. return '';
  46792. }
  46793. return result[property];
  46794. };
  46795. /**
  46796. * Resuable stable sort function
  46797. *
  46798. * @param {Playlists} array
  46799. * @param {Function} sortFn Different comparators
  46800. * @function stableSort
  46801. */
  46802. const stableSort = function (array, sortFn) {
  46803. const newArray = array.slice();
  46804. array.sort(function (left, right) {
  46805. const cmp = sortFn(left, right);
  46806. if (cmp === 0) {
  46807. return newArray.indexOf(left) - newArray.indexOf(right);
  46808. }
  46809. return cmp;
  46810. });
  46811. };
  46812. /**
  46813. * A comparator function to sort two playlist object by bandwidth.
  46814. *
  46815. * @param {Object} left a media playlist object
  46816. * @param {Object} right a media playlist object
  46817. * @return {number} Greater than zero if the bandwidth attribute of
  46818. * left is greater than the corresponding attribute of right. Less
  46819. * than zero if the bandwidth of right is greater than left and
  46820. * exactly zero if the two are equal.
  46821. */
  46822. const comparePlaylistBandwidth = function (left, right) {
  46823. let leftBandwidth;
  46824. let rightBandwidth;
  46825. if (left.attributes.BANDWIDTH) {
  46826. leftBandwidth = left.attributes.BANDWIDTH;
  46827. }
  46828. leftBandwidth = leftBandwidth || window.Number.MAX_VALUE;
  46829. if (right.attributes.BANDWIDTH) {
  46830. rightBandwidth = right.attributes.BANDWIDTH;
  46831. }
  46832. rightBandwidth = rightBandwidth || window.Number.MAX_VALUE;
  46833. return leftBandwidth - rightBandwidth;
  46834. };
  46835. /**
  46836. * A comparator function to sort two playlist object by resolution (width).
  46837. *
  46838. * @param {Object} left a media playlist object
  46839. * @param {Object} right a media playlist object
  46840. * @return {number} Greater than zero if the resolution.width attribute of
  46841. * left is greater than the corresponding attribute of right. Less
  46842. * than zero if the resolution.width of right is greater than left and
  46843. * exactly zero if the two are equal.
  46844. */
  46845. const comparePlaylistResolution = function (left, right) {
  46846. let leftWidth;
  46847. let rightWidth;
  46848. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  46849. leftWidth = left.attributes.RESOLUTION.width;
  46850. }
  46851. leftWidth = leftWidth || window.Number.MAX_VALUE;
  46852. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  46853. rightWidth = right.attributes.RESOLUTION.width;
  46854. }
  46855. rightWidth = rightWidth || window.Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  46856. // have the same media dimensions/ resolution
  46857. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  46858. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  46859. }
  46860. return leftWidth - rightWidth;
  46861. };
  46862. /**
  46863. * Chooses the appropriate media playlist based on bandwidth and player size
  46864. *
  46865. * @param {Object} main
  46866. * Object representation of the main manifest
  46867. * @param {number} playerBandwidth
  46868. * Current calculated bandwidth of the player
  46869. * @param {number} playerWidth
  46870. * Current width of the player element (should account for the device pixel ratio)
  46871. * @param {number} playerHeight
  46872. * Current height of the player element (should account for the device pixel ratio)
  46873. * @param {boolean} limitRenditionByPlayerDimensions
  46874. * True if the player width and height should be used during the selection, false otherwise
  46875. * @param {Object} playlistController
  46876. * the current playlistController object
  46877. * @return {Playlist} the highest bitrate playlist less than the
  46878. * currently detected bandwidth, accounting for some amount of
  46879. * bandwidth variance
  46880. */
  46881. let simpleSelector = function (main, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, playlistController) {
  46882. // If we end up getting called before `main` is available, exit early
  46883. if (!main) {
  46884. return;
  46885. }
  46886. const options = {
  46887. bandwidth: playerBandwidth,
  46888. width: playerWidth,
  46889. height: playerHeight,
  46890. limitRenditionByPlayerDimensions
  46891. };
  46892. let playlists = main.playlists; // if playlist is audio only, select between currently active audio group playlists.
  46893. if (Playlist.isAudioOnly(main)) {
  46894. playlists = playlistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  46895. // at the buttom of this function for debugging.
  46896. options.audioOnly = true;
  46897. } // convert the playlists to an intermediary representation to make comparisons easier
  46898. let sortedPlaylistReps = playlists.map(playlist => {
  46899. let bandwidth;
  46900. const width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  46901. const height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  46902. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  46903. bandwidth = bandwidth || window.Number.MAX_VALUE;
  46904. return {
  46905. bandwidth,
  46906. width,
  46907. height,
  46908. playlist
  46909. };
  46910. });
  46911. stableSort(sortedPlaylistReps, (left, right) => left.bandwidth - right.bandwidth); // filter out any playlists that have been excluded due to
  46912. // incompatible configurations
  46913. sortedPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isIncompatible(rep.playlist)); // filter out any playlists that have been disabled manually through the representations
  46914. // api or excluded temporarily due to playback errors.
  46915. let enabledPlaylistReps = sortedPlaylistReps.filter(rep => Playlist.isEnabled(rep.playlist));
  46916. if (!enabledPlaylistReps.length) {
  46917. // if there are no enabled playlists, then they have all been excluded or disabled
  46918. // by the user through the representations api. In this case, ignore exclusion and
  46919. // fallback to what the user wants by using playlists the user has not disabled.
  46920. enabledPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isDisabled(rep.playlist));
  46921. } // filter out any variant that has greater effective bitrate
  46922. // than the current estimated bandwidth
  46923. const bandwidthPlaylistReps = enabledPlaylistReps.filter(rep => rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth);
  46924. let highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  46925. // and then taking the very first element
  46926. 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.
  46927. if (limitRenditionByPlayerDimensions === false) {
  46928. const chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  46929. if (chosenRep && chosenRep.playlist) {
  46930. let type = 'sortedPlaylistReps';
  46931. if (bandwidthBestRep) {
  46932. type = 'bandwidthBestRep';
  46933. }
  46934. if (enabledPlaylistReps[0]) {
  46935. type = 'enabledPlaylistReps';
  46936. }
  46937. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  46938. return chosenRep.playlist;
  46939. }
  46940. logFn('could not choose a playlist with options', options);
  46941. return null;
  46942. } // filter out playlists without resolution information
  46943. const haveResolution = bandwidthPlaylistReps.filter(rep => rep.width && rep.height); // sort variants by resolution
  46944. stableSort(haveResolution, (left, right) => left.width - right.width); // if we have the exact resolution as the player use it
  46945. const resolutionBestRepList = haveResolution.filter(rep => rep.width === playerWidth && rep.height === playerHeight);
  46946. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  46947. const resolutionBestRep = resolutionBestRepList.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  46948. let resolutionPlusOneList;
  46949. let resolutionPlusOneSmallest;
  46950. let resolutionPlusOneRep; // find the smallest variant that is larger than the player
  46951. // if there is no match of exact resolution
  46952. if (!resolutionBestRep) {
  46953. resolutionPlusOneList = haveResolution.filter(rep => rep.width > playerWidth || rep.height > playerHeight); // find all the variants have the same smallest resolution
  46954. resolutionPlusOneSmallest = resolutionPlusOneList.filter(rep => rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height); // ensure that we also pick the highest bandwidth variant that
  46955. // is just-larger-than the video player
  46956. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  46957. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  46958. }
  46959. let leastPixelDiffRep; // If this selector proves to be better than others,
  46960. // resolutionPlusOneRep and resolutionBestRep and all
  46961. // the code involving them should be removed.
  46962. if (playlistController.leastPixelDiffSelector) {
  46963. // find the variant that is closest to the player's pixel size
  46964. const leastPixelDiffList = haveResolution.map(rep => {
  46965. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  46966. return rep;
  46967. }); // get the highest bandwidth, closest resolution playlist
  46968. stableSort(leastPixelDiffList, (left, right) => {
  46969. // sort by highest bandwidth if pixelDiff is the same
  46970. if (left.pixelDiff === right.pixelDiff) {
  46971. return right.bandwidth - left.bandwidth;
  46972. }
  46973. return left.pixelDiff - right.pixelDiff;
  46974. });
  46975. leastPixelDiffRep = leastPixelDiffList[0];
  46976. } // fallback chain of variants
  46977. const chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  46978. if (chosenRep && chosenRep.playlist) {
  46979. let type = 'sortedPlaylistReps';
  46980. if (leastPixelDiffRep) {
  46981. type = 'leastPixelDiffRep';
  46982. } else if (resolutionPlusOneRep) {
  46983. type = 'resolutionPlusOneRep';
  46984. } else if (resolutionBestRep) {
  46985. type = 'resolutionBestRep';
  46986. } else if (bandwidthBestRep) {
  46987. type = 'bandwidthBestRep';
  46988. } else if (enabledPlaylistReps[0]) {
  46989. type = 'enabledPlaylistReps';
  46990. }
  46991. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  46992. return chosenRep.playlist;
  46993. }
  46994. logFn('could not choose a playlist with options', options);
  46995. return null;
  46996. };
  46997. /**
  46998. * Chooses the appropriate media playlist based on the most recent
  46999. * bandwidth estimate and the player size.
  47000. *
  47001. * Expects to be called within the context of an instance of VhsHandler
  47002. *
  47003. * @return {Playlist} the highest bitrate playlist less than the
  47004. * currently detected bandwidth, accounting for some amount of
  47005. * bandwidth variance
  47006. */
  47007. const lastBandwidthSelector = function () {
  47008. const pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  47009. 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_);
  47010. };
  47011. /**
  47012. * Chooses the appropriate media playlist based on an
  47013. * exponential-weighted moving average of the bandwidth after
  47014. * filtering for player size.
  47015. *
  47016. * Expects to be called within the context of an instance of VhsHandler
  47017. *
  47018. * @param {number} decay - a number between 0 and 1. Higher values of
  47019. * this parameter will cause previous bandwidth estimates to lose
  47020. * significance more quickly.
  47021. * @return {Function} a function which can be invoked to create a new
  47022. * playlist selector function.
  47023. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  47024. */
  47025. const movingAverageBandwidthSelector = function (decay) {
  47026. let average = -1;
  47027. let lastSystemBandwidth = -1;
  47028. if (decay < 0 || decay > 1) {
  47029. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  47030. }
  47031. return function () {
  47032. const pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  47033. if (average < 0) {
  47034. average = this.systemBandwidth;
  47035. lastSystemBandwidth = this.systemBandwidth;
  47036. } // stop the average value from decaying for every 250ms
  47037. // when the systemBandwidth is constant
  47038. // and
  47039. // stop average from setting to a very low value when the
  47040. // systemBandwidth becomes 0 in case of chunk cancellation
  47041. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  47042. average = decay * this.systemBandwidth + (1 - decay) * average;
  47043. lastSystemBandwidth = this.systemBandwidth;
  47044. }
  47045. 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_);
  47046. };
  47047. };
  47048. /**
  47049. * Chooses the appropriate media playlist based on the potential to rebuffer
  47050. *
  47051. * @param {Object} settings
  47052. * Object of information required to use this selector
  47053. * @param {Object} settings.main
  47054. * Object representation of the main manifest
  47055. * @param {number} settings.currentTime
  47056. * The current time of the player
  47057. * @param {number} settings.bandwidth
  47058. * Current measured bandwidth
  47059. * @param {number} settings.duration
  47060. * Duration of the media
  47061. * @param {number} settings.segmentDuration
  47062. * Segment duration to be used in round trip time calculations
  47063. * @param {number} settings.timeUntilRebuffer
  47064. * Time left in seconds until the player has to rebuffer
  47065. * @param {number} settings.currentTimeline
  47066. * The current timeline segments are being loaded from
  47067. * @param {SyncController} settings.syncController
  47068. * SyncController for determining if we have a sync point for a given playlist
  47069. * @return {Object|null}
  47070. * {Object} return.playlist
  47071. * The highest bandwidth playlist with the least amount of rebuffering
  47072. * {Number} return.rebufferingImpact
  47073. * The amount of time in seconds switching to this playlist will rebuffer. A
  47074. * negative value means that switching will cause zero rebuffering.
  47075. */
  47076. const minRebufferMaxBandwidthSelector = function (settings) {
  47077. const {
  47078. main,
  47079. currentTime,
  47080. bandwidth,
  47081. duration,
  47082. segmentDuration,
  47083. timeUntilRebuffer,
  47084. currentTimeline,
  47085. syncController
  47086. } = settings; // filter out any playlists that have been excluded due to
  47087. // incompatible configurations
  47088. const compatiblePlaylists = main.playlists.filter(playlist => !Playlist.isIncompatible(playlist)); // filter out any playlists that have been disabled manually through the representations
  47089. // api or excluded temporarily due to playback errors.
  47090. let enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  47091. if (!enabledPlaylists.length) {
  47092. // if there are no enabled playlists, then they have all been excluded or disabled
  47093. // by the user through the representations api. In this case, ignore exclusion and
  47094. // fallback to what the user wants by using playlists the user has not disabled.
  47095. enabledPlaylists = compatiblePlaylists.filter(playlist => !Playlist.isDisabled(playlist));
  47096. }
  47097. const bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  47098. const rebufferingEstimates = bandwidthPlaylists.map(playlist => {
  47099. const syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  47100. // sync request first. This will double the request time
  47101. const numRequests = syncPoint ? 1 : 2;
  47102. const requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  47103. const rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  47104. return {
  47105. playlist,
  47106. rebufferingImpact
  47107. };
  47108. });
  47109. const noRebufferingPlaylists = rebufferingEstimates.filter(estimate => estimate.rebufferingImpact <= 0); // Sort by bandwidth DESC
  47110. stableSort(noRebufferingPlaylists, (a, b) => comparePlaylistBandwidth(b.playlist, a.playlist));
  47111. if (noRebufferingPlaylists.length) {
  47112. return noRebufferingPlaylists[0];
  47113. }
  47114. stableSort(rebufferingEstimates, (a, b) => a.rebufferingImpact - b.rebufferingImpact);
  47115. return rebufferingEstimates[0] || null;
  47116. };
  47117. /**
  47118. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  47119. * one with video. If no renditions with video exist, return the lowest audio rendition.
  47120. *
  47121. * Expects to be called within the context of an instance of VhsHandler
  47122. *
  47123. * @return {Object|null}
  47124. * {Object} return.playlist
  47125. * The lowest bitrate playlist that contains a video codec. If no such rendition
  47126. * exists pick the lowest audio rendition.
  47127. */
  47128. const lowestBitrateCompatibleVariantSelector = function () {
  47129. // filter out any playlists that have been excluded due to
  47130. // incompatible configurations or playback errors
  47131. const playlists = this.playlists.main.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  47132. stableSort(playlists, (a, b) => comparePlaylistBandwidth(a, b)); // Parse and assume that playlists with no video codec have no video
  47133. // (this is not necessarily true, although it is generally true).
  47134. //
  47135. // If an entire manifest has no valid videos everything will get filtered
  47136. // out.
  47137. const playlistsWithVideo = playlists.filter(playlist => !!codecsForPlaylist(this.playlists.main, playlist).video);
  47138. return playlistsWithVideo[0] || null;
  47139. };
  47140. /**
  47141. * Combine all segments into a single Uint8Array
  47142. *
  47143. * @param {Object} segmentObj
  47144. * @return {Uint8Array} concatenated bytes
  47145. * @private
  47146. */
  47147. const concatSegments = segmentObj => {
  47148. let offset = 0;
  47149. let tempBuffer;
  47150. if (segmentObj.bytes) {
  47151. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  47152. segmentObj.segments.forEach(segment => {
  47153. tempBuffer.set(segment, offset);
  47154. offset += segment.byteLength;
  47155. });
  47156. }
  47157. return tempBuffer;
  47158. };
  47159. /**
  47160. * @file text-tracks.js
  47161. */
  47162. /**
  47163. * Create captions text tracks on video.js if they do not exist
  47164. *
  47165. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  47166. * @param {Object} tech the video.js tech
  47167. * @param {Object} captionStream the caption stream to create
  47168. * @private
  47169. */
  47170. const createCaptionsTrackIfNotExists = function (inbandTextTracks, tech, captionStream) {
  47171. if (!inbandTextTracks[captionStream]) {
  47172. tech.trigger({
  47173. type: 'usage',
  47174. name: 'vhs-608'
  47175. });
  47176. let instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  47177. if (/^cc708_/.test(captionStream)) {
  47178. instreamId = 'SERVICE' + captionStream.split('_')[1];
  47179. }
  47180. const track = tech.textTracks().getTrackById(instreamId);
  47181. if (track) {
  47182. // Resuse an existing track with a CC# id because this was
  47183. // very likely created by videojs-contrib-hls from information
  47184. // in the m3u8 for us to use
  47185. inbandTextTracks[captionStream] = track;
  47186. } else {
  47187. // This section gets called when we have caption services that aren't specified in the manifest.
  47188. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  47189. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  47190. let label = captionStream;
  47191. let language = captionStream;
  47192. let def = false;
  47193. const captionService = captionServices[instreamId];
  47194. if (captionService) {
  47195. label = captionService.label;
  47196. language = captionService.language;
  47197. def = captionService.default;
  47198. } // Otherwise, create a track with the default `CC#` label and
  47199. // without a language
  47200. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  47201. kind: 'captions',
  47202. id: instreamId,
  47203. // TODO: investigate why this doesn't seem to turn the caption on by default
  47204. default: def,
  47205. label,
  47206. language
  47207. }, false).track;
  47208. }
  47209. }
  47210. };
  47211. /**
  47212. * Add caption text track data to a source handler given an array of captions
  47213. *
  47214. * @param {Object}
  47215. * @param {Object} inbandTextTracks the inband text tracks
  47216. * @param {number} timestampOffset the timestamp offset of the source buffer
  47217. * @param {Array} captionArray an array of caption data
  47218. * @private
  47219. */
  47220. const addCaptionData = function ({
  47221. inbandTextTracks,
  47222. captionArray,
  47223. timestampOffset
  47224. }) {
  47225. if (!captionArray) {
  47226. return;
  47227. }
  47228. const Cue = window.WebKitDataCue || window.VTTCue;
  47229. captionArray.forEach(caption => {
  47230. const track = caption.stream;
  47231. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  47232. });
  47233. };
  47234. /**
  47235. * Define properties on a cue for backwards compatability,
  47236. * but warn the user that the way that they are using it
  47237. * is depricated and will be removed at a later date.
  47238. *
  47239. * @param {Cue} cue the cue to add the properties on
  47240. * @private
  47241. */
  47242. const deprecateOldCue = function (cue) {
  47243. Object.defineProperties(cue.frame, {
  47244. id: {
  47245. get() {
  47246. videojs.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  47247. return cue.value.key;
  47248. }
  47249. },
  47250. value: {
  47251. get() {
  47252. videojs.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  47253. return cue.value.data;
  47254. }
  47255. },
  47256. privateData: {
  47257. get() {
  47258. videojs.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  47259. return cue.value.data;
  47260. }
  47261. }
  47262. });
  47263. };
  47264. /**
  47265. * Add metadata text track data to a source handler given an array of metadata
  47266. *
  47267. * @param {Object}
  47268. * @param {Object} inbandTextTracks the inband text tracks
  47269. * @param {Array} metadataArray an array of meta data
  47270. * @param {number} timestampOffset the timestamp offset of the source buffer
  47271. * @param {number} videoDuration the duration of the video
  47272. * @private
  47273. */
  47274. const addMetadata = ({
  47275. inbandTextTracks,
  47276. metadataArray,
  47277. timestampOffset,
  47278. videoDuration
  47279. }) => {
  47280. if (!metadataArray) {
  47281. return;
  47282. }
  47283. const Cue = window.WebKitDataCue || window.VTTCue;
  47284. const metadataTrack = inbandTextTracks.metadataTrack_;
  47285. if (!metadataTrack) {
  47286. return;
  47287. }
  47288. metadataArray.forEach(metadata => {
  47289. const time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  47290. // ignore this bit of metadata.
  47291. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  47292. // which is the "Title/Songname/Content description" frame
  47293. if (typeof time !== 'number' || window.isNaN(time) || time < 0 || !(time < Infinity)) {
  47294. return;
  47295. }
  47296. metadata.frames.forEach(frame => {
  47297. const cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  47298. cue.frame = frame;
  47299. cue.value = frame;
  47300. deprecateOldCue(cue);
  47301. metadataTrack.addCue(cue);
  47302. });
  47303. });
  47304. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  47305. return;
  47306. } // Updating the metadeta cues so that
  47307. // the endTime of each cue is the startTime of the next cue
  47308. // the endTime of last cue is the duration of the video
  47309. const cues = metadataTrack.cues;
  47310. const cuesArray = []; // Create a copy of the TextTrackCueList...
  47311. // ...disregarding cues with a falsey value
  47312. for (let i = 0; i < cues.length; i++) {
  47313. if (cues[i]) {
  47314. cuesArray.push(cues[i]);
  47315. }
  47316. } // Group cues by their startTime value
  47317. const cuesGroupedByStartTime = cuesArray.reduce((obj, cue) => {
  47318. const timeSlot = obj[cue.startTime] || [];
  47319. timeSlot.push(cue);
  47320. obj[cue.startTime] = timeSlot;
  47321. return obj;
  47322. }, {}); // Sort startTimes by ascending order
  47323. const sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort((a, b) => Number(a) - Number(b)); // Map each cue group's endTime to the next group's startTime
  47324. sortedStartTimes.forEach((startTime, idx) => {
  47325. const cueGroup = cuesGroupedByStartTime[startTime];
  47326. const nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
  47327. cueGroup.forEach(cue => {
  47328. cue.endTime = nextTime;
  47329. });
  47330. });
  47331. };
  47332. /**
  47333. * Create metadata text track on video.js if it does not exist
  47334. *
  47335. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  47336. * @param {string} dispatchType the inband metadata track dispatch type
  47337. * @param {Object} tech the video.js tech
  47338. * @private
  47339. */
  47340. const createMetadataTrackIfNotExists = (inbandTextTracks, dispatchType, tech) => {
  47341. if (inbandTextTracks.metadataTrack_) {
  47342. return;
  47343. }
  47344. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  47345. kind: 'metadata',
  47346. label: 'Timed Metadata'
  47347. }, false).track;
  47348. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  47349. };
  47350. /**
  47351. * Remove cues from a track on video.js.
  47352. *
  47353. * @param {Double} start start of where we should remove the cue
  47354. * @param {Double} end end of where the we should remove the cue
  47355. * @param {Object} track the text track to remove the cues from
  47356. * @private
  47357. */
  47358. const removeCuesFromTrack = function (start, end, track) {
  47359. let i;
  47360. let cue;
  47361. if (!track) {
  47362. return;
  47363. }
  47364. if (!track.cues) {
  47365. return;
  47366. }
  47367. i = track.cues.length;
  47368. while (i--) {
  47369. cue = track.cues[i]; // Remove any cue within the provided start and end time
  47370. if (cue.startTime >= start && cue.endTime <= end) {
  47371. track.removeCue(cue);
  47372. }
  47373. }
  47374. };
  47375. /**
  47376. * Remove duplicate cues from a track on video.js (a cue is considered a
  47377. * duplicate if it has the same time interval and text as another)
  47378. *
  47379. * @param {Object} track the text track to remove the duplicate cues from
  47380. * @private
  47381. */
  47382. const removeDuplicateCuesFromTrack = function (track) {
  47383. const cues = track.cues;
  47384. if (!cues) {
  47385. return;
  47386. }
  47387. for (let i = 0; i < cues.length; i++) {
  47388. const duplicates = [];
  47389. let occurrences = 0;
  47390. for (let j = 0; j < cues.length; j++) {
  47391. if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
  47392. occurrences++;
  47393. if (occurrences > 1) {
  47394. duplicates.push(cues[j]);
  47395. }
  47396. }
  47397. }
  47398. if (duplicates.length) {
  47399. duplicates.forEach(dupe => track.removeCue(dupe));
  47400. }
  47401. }
  47402. };
  47403. /**
  47404. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  47405. * front of current time.
  47406. *
  47407. * @param {Array} buffer
  47408. * The current buffer of gop information
  47409. * @param {number} currentTime
  47410. * The current time
  47411. * @param {Double} mapping
  47412. * Offset to map display time to stream presentation time
  47413. * @return {Array}
  47414. * List of gops considered safe to append over
  47415. */
  47416. const gopsSafeToAlignWith = (buffer, currentTime, mapping) => {
  47417. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  47418. return [];
  47419. } // pts value for current time + 3 seconds to give a bit more wiggle room
  47420. const currentTimePts = Math.ceil((currentTime - mapping + 3) * clock_1);
  47421. let i;
  47422. for (i = 0; i < buffer.length; i++) {
  47423. if (buffer[i].pts > currentTimePts) {
  47424. break;
  47425. }
  47426. }
  47427. return buffer.slice(i);
  47428. };
  47429. /**
  47430. * Appends gop information (timing and byteLength) received by the transmuxer for the
  47431. * gops appended in the last call to appendBuffer
  47432. *
  47433. * @param {Array} buffer
  47434. * The current buffer of gop information
  47435. * @param {Array} gops
  47436. * List of new gop information
  47437. * @param {boolean} replace
  47438. * If true, replace the buffer with the new gop information. If false, append the
  47439. * new gop information to the buffer in the right location of time.
  47440. * @return {Array}
  47441. * Updated list of gop information
  47442. */
  47443. const updateGopBuffer = (buffer, gops, replace) => {
  47444. if (!gops.length) {
  47445. return buffer;
  47446. }
  47447. if (replace) {
  47448. // If we are in safe append mode, then completely overwrite the gop buffer
  47449. // with the most recent appeneded data. This will make sure that when appending
  47450. // future segments, we only try to align with gops that are both ahead of current
  47451. // time and in the last segment appended.
  47452. return gops.slice();
  47453. }
  47454. const start = gops[0].pts;
  47455. let i = 0;
  47456. for (i; i < buffer.length; i++) {
  47457. if (buffer[i].pts >= start) {
  47458. break;
  47459. }
  47460. }
  47461. return buffer.slice(0, i).concat(gops);
  47462. };
  47463. /**
  47464. * Removes gop information in buffer that overlaps with provided start and end
  47465. *
  47466. * @param {Array} buffer
  47467. * The current buffer of gop information
  47468. * @param {Double} start
  47469. * position to start the remove at
  47470. * @param {Double} end
  47471. * position to end the remove at
  47472. * @param {Double} mapping
  47473. * Offset to map display time to stream presentation time
  47474. */
  47475. const removeGopBuffer = (buffer, start, end, mapping) => {
  47476. const startPts = Math.ceil((start - mapping) * clock_1);
  47477. const endPts = Math.ceil((end - mapping) * clock_1);
  47478. const updatedBuffer = buffer.slice();
  47479. let i = buffer.length;
  47480. while (i--) {
  47481. if (buffer[i].pts <= endPts) {
  47482. break;
  47483. }
  47484. }
  47485. if (i === -1) {
  47486. // no removal because end of remove range is before start of buffer
  47487. return updatedBuffer;
  47488. }
  47489. let j = i + 1;
  47490. while (j--) {
  47491. if (buffer[j].pts <= startPts) {
  47492. break;
  47493. }
  47494. } // clamp remove range start to 0 index
  47495. j = Math.max(j, 0);
  47496. updatedBuffer.splice(j, i - j + 1);
  47497. return updatedBuffer;
  47498. };
  47499. const shallowEqual = function (a, b) {
  47500. // if both are undefined
  47501. // or one or the other is undefined
  47502. // they are not equal
  47503. if (!a && !b || !a && b || a && !b) {
  47504. return false;
  47505. } // they are the same object and thus, equal
  47506. if (a === b) {
  47507. return true;
  47508. } // sort keys so we can make sure they have
  47509. // all the same keys later.
  47510. const akeys = Object.keys(a).sort();
  47511. const bkeys = Object.keys(b).sort(); // different number of keys, not equal
  47512. if (akeys.length !== bkeys.length) {
  47513. return false;
  47514. }
  47515. for (let i = 0; i < akeys.length; i++) {
  47516. const key = akeys[i]; // different sorted keys, not equal
  47517. if (key !== bkeys[i]) {
  47518. return false;
  47519. } // different values, not equal
  47520. if (a[key] !== b[key]) {
  47521. return false;
  47522. }
  47523. }
  47524. return true;
  47525. };
  47526. // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  47527. const QUOTA_EXCEEDED_ERR = 22;
  47528. /**
  47529. * The segment loader has no recourse except to fetch a segment in the
  47530. * current playlist and use the internal timestamps in that segment to
  47531. * generate a syncPoint. This function returns a good candidate index
  47532. * for that process.
  47533. *
  47534. * @param {Array} segments - the segments array from a playlist.
  47535. * @return {number} An index of a segment from the playlist to load
  47536. */
  47537. const getSyncSegmentCandidate = function (currentTimeline, segments, targetTime) {
  47538. segments = segments || [];
  47539. const timelineSegments = [];
  47540. let time = 0;
  47541. for (let i = 0; i < segments.length; i++) {
  47542. const segment = segments[i];
  47543. if (currentTimeline === segment.timeline) {
  47544. timelineSegments.push(i);
  47545. time += segment.duration;
  47546. if (time > targetTime) {
  47547. return i;
  47548. }
  47549. }
  47550. }
  47551. if (timelineSegments.length === 0) {
  47552. return 0;
  47553. } // default to the last timeline segment
  47554. return timelineSegments[timelineSegments.length - 1];
  47555. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  47556. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  47557. // as a start to prevent any potential issues with removing content too close to the
  47558. // playhead.
  47559. const MIN_BACK_BUFFER = 1; // in ms
  47560. const CHECK_BUFFER_DELAY = 500;
  47561. const finite = num => typeof num === 'number' && isFinite(num); // With most content hovering around 30fps, if a segment has a duration less than a half
  47562. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  47563. // not accurately reflect the rest of the content.
  47564. const MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  47565. const illegalMediaSwitch = (loaderType, startingMedia, trackInfo) => {
  47566. // Although these checks should most likely cover non 'main' types, for now it narrows
  47567. // the scope of our checks.
  47568. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  47569. return null;
  47570. }
  47571. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  47572. return 'Neither audio nor video found in segment.';
  47573. }
  47574. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  47575. 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.';
  47576. }
  47577. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  47578. 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.';
  47579. }
  47580. return null;
  47581. };
  47582. /**
  47583. * Calculates a time value that is safe to remove from the back buffer without interrupting
  47584. * playback.
  47585. *
  47586. * @param {TimeRange} seekable
  47587. * The current seekable range
  47588. * @param {number} currentTime
  47589. * The current time of the player
  47590. * @param {number} targetDuration
  47591. * The target duration of the current playlist
  47592. * @return {number}
  47593. * Time that is safe to remove from the back buffer without interrupting playback
  47594. */
  47595. const safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {
  47596. // 30 seconds before the playhead provides a safe default for trimming.
  47597. //
  47598. // Choosing a reasonable default is particularly important for high bitrate content and
  47599. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  47600. // throw an APPEND_BUFFER_ERR.
  47601. let trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  47602. if (seekable.length) {
  47603. // Some live playlists may have a shorter window of content than the full allowed back
  47604. // buffer. For these playlists, don't save content that's no longer within the window.
  47605. trimTime = Math.max(trimTime, seekable.start(0));
  47606. } // Don't remove within target duration of the current time to avoid the possibility of
  47607. // removing the GOP currently being played, as removing it can cause playback stalls.
  47608. const maxTrimTime = currentTime - targetDuration;
  47609. return Math.min(maxTrimTime, trimTime);
  47610. };
  47611. const segmentInfoString = segmentInfo => {
  47612. const {
  47613. startOfSegment,
  47614. duration,
  47615. segment,
  47616. part,
  47617. playlist: {
  47618. mediaSequence: seq,
  47619. id,
  47620. segments = []
  47621. },
  47622. mediaIndex: index,
  47623. partIndex,
  47624. timeline
  47625. } = segmentInfo;
  47626. const segmentLen = segments.length - 1;
  47627. let selection = 'mediaIndex/partIndex increment';
  47628. if (segmentInfo.getMediaInfoForTime) {
  47629. selection = `getMediaInfoForTime (${segmentInfo.getMediaInfoForTime})`;
  47630. } else if (segmentInfo.isSyncRequest) {
  47631. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  47632. }
  47633. if (segmentInfo.independent) {
  47634. selection += ` with independent ${segmentInfo.independent}`;
  47635. }
  47636. const hasPartIndex = typeof partIndex === 'number';
  47637. const name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  47638. const zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  47639. preloadSegment: segment
  47640. }) - 1 : 0;
  47641. 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}]`;
  47642. };
  47643. const timingInfoPropertyForMedia = mediaType => `${mediaType}TimingInfo`;
  47644. /**
  47645. * Returns the timestamp offset to use for the segment.
  47646. *
  47647. * @param {number} segmentTimeline
  47648. * The timeline of the segment
  47649. * @param {number} currentTimeline
  47650. * The timeline currently being followed by the loader
  47651. * @param {number} startOfSegment
  47652. * The estimated segment start
  47653. * @param {TimeRange[]} buffered
  47654. * The loader's buffer
  47655. * @param {boolean} overrideCheck
  47656. * If true, no checks are made to see if the timestamp offset value should be set,
  47657. * but sets it directly to a value.
  47658. *
  47659. * @return {number|null}
  47660. * Either a number representing a new timestamp offset, or null if the segment is
  47661. * part of the same timeline
  47662. */
  47663. const timestampOffsetForSegment = ({
  47664. segmentTimeline,
  47665. currentTimeline,
  47666. startOfSegment,
  47667. buffered,
  47668. overrideCheck
  47669. }) => {
  47670. // Check to see if we are crossing a discontinuity to see if we need to set the
  47671. // timestamp offset on the transmuxer and source buffer.
  47672. //
  47673. // Previously, we changed the timestampOffset if the start of this segment was less than
  47674. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  47675. // behavior, especially around long running live streams.
  47676. if (!overrideCheck && segmentTimeline === currentTimeline) {
  47677. return null;
  47678. } // When changing renditions, it's possible to request a segment on an older timeline. For
  47679. // instance, given two renditions with the following:
  47680. //
  47681. // #EXTINF:10
  47682. // segment1
  47683. // #EXT-X-DISCONTINUITY
  47684. // #EXTINF:10
  47685. // segment2
  47686. // #EXTINF:10
  47687. // segment3
  47688. //
  47689. // And the current player state:
  47690. //
  47691. // current time: 8
  47692. // buffer: 0 => 20
  47693. //
  47694. // The next segment on the current rendition would be segment3, filling the buffer from
  47695. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  47696. // then the next segment to be requested will be segment1 from the new rendition in
  47697. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  47698. // content (since it would position segment1 of the new rendition starting at 20s). This
  47699. // case can be identified when the new segment's timeline is a prior value. Instead of
  47700. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  47701. // more accurate to the actual start time of the segment.
  47702. if (segmentTimeline < currentTimeline) {
  47703. return startOfSegment;
  47704. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  47705. // value uses the end of the last segment if it is available. While this value
  47706. // should often be correct, it's better to rely on the buffered end, as the new
  47707. // content post discontinuity should line up with the buffered end as if it were
  47708. // time 0 for the new content.
  47709. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  47710. };
  47711. /**
  47712. * Returns whether or not the loader should wait for a timeline change from the timeline
  47713. * change controller before processing the segment.
  47714. *
  47715. * Primary timing in VHS goes by video. This is different from most media players, as
  47716. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  47717. * will continue to use video as the primary timing source, due to the current logic and
  47718. * expectations built around it.
  47719. * Since the timing follows video, in order to maintain sync, the video loader is
  47720. * responsible for setting both audio and video source buffer timestamp offsets.
  47721. *
  47722. * Setting different values for audio and video source buffers could lead to
  47723. * desyncing. The following examples demonstrate some of the situations where this
  47724. * distinction is important. Note that all of these cases involve demuxed content. When
  47725. * content is muxed, the audio and video are packaged together, therefore syncing
  47726. * separate media playlists is not an issue.
  47727. *
  47728. * CASE 1: Audio prepares to load a new timeline before video:
  47729. *
  47730. * Timeline: 0 1
  47731. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  47732. * Audio Loader: ^
  47733. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  47734. * Video Loader ^
  47735. *
  47736. * In the above example, the audio loader is preparing to load the 6th segment, the first
  47737. * after a discontinuity, while the video loader is still loading the 5th segment, before
  47738. * the discontinuity.
  47739. *
  47740. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  47741. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  47742. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  47743. * the audio loader must provide the audioAppendStart value to trim the content in the
  47744. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  47745. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  47746. * segment until that value is provided.
  47747. *
  47748. * CASE 2: Video prepares to load a new timeline before audio:
  47749. *
  47750. * Timeline: 0 1
  47751. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  47752. * Audio Loader: ^
  47753. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  47754. * Video Loader ^
  47755. *
  47756. * In the above example, the video loader is preparing to load the 6th segment, the first
  47757. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  47758. * the discontinuity.
  47759. *
  47760. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  47761. * segment is loaded and processed, both the video and audio timestamp offsets will be
  47762. * set, since video is used as the primary timing source. This is to ensure content lines
  47763. * up appropriately, as any modifications to the video timing are reflected by audio when
  47764. * the video loader sets the audio and video timestamp offsets to the same value. However,
  47765. * setting the timestamp offset for audio before audio has had a chance to change
  47766. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  47767. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  47768. *
  47769. * CASE 3: When seeking, audio prepares to load a new timeline before video
  47770. *
  47771. * Timeline: 0 1
  47772. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  47773. * Audio Loader: ^
  47774. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  47775. * Video Loader ^
  47776. *
  47777. * In the above example, both audio and video loaders are loading segments from timeline
  47778. * 0, but imagine that the seek originated from timeline 1.
  47779. *
  47780. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  47781. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  47782. * must wait for the video loader to load its segment and update both the audio and video
  47783. * timestamp offsets before it may load and append its own segment. This is the case
  47784. * whether the seek results in a mismatched segment request (e.g., the audio loader
  47785. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  47786. * loaders choose to load the same segment index from each playlist, as the segments may
  47787. * not be aligned perfectly, even for matching segment indexes.
  47788. *
  47789. * @param {Object} timelinechangeController
  47790. * @param {number} currentTimeline
  47791. * The timeline currently being followed by the loader
  47792. * @param {number} segmentTimeline
  47793. * The timeline of the segment being loaded
  47794. * @param {('main'|'audio')} loaderType
  47795. * The loader type
  47796. * @param {boolean} audioDisabled
  47797. * Whether the audio is disabled for the loader. This should only be true when the
  47798. * loader may have muxed audio in its segment, but should not append it, e.g., for
  47799. * the main loader when an alternate audio playlist is active.
  47800. *
  47801. * @return {boolean}
  47802. * Whether the loader should wait for a timeline change from the timeline change
  47803. * controller before processing the segment
  47804. */
  47805. const shouldWaitForTimelineChange = ({
  47806. timelineChangeController,
  47807. currentTimeline,
  47808. segmentTimeline,
  47809. loaderType,
  47810. audioDisabled
  47811. }) => {
  47812. if (currentTimeline === segmentTimeline) {
  47813. return false;
  47814. }
  47815. if (loaderType === 'audio') {
  47816. const lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  47817. type: 'main'
  47818. }); // Audio loader should wait if:
  47819. //
  47820. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  47821. // * main hasn't yet changed to the timeline audio is looking to load
  47822. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  47823. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  47824. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  47825. // loader's segments (or the content is audio/video only and handled by the main
  47826. // loader).
  47827. if (loaderType === 'main' && audioDisabled) {
  47828. const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  47829. type: 'audio'
  47830. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  47831. // change to the current timeline.
  47832. //
  47833. // Since the main loader is responsible for setting the timestamp offset for both
  47834. // audio and video, the main loader must wait for audio to be about to change to its
  47835. // timeline before setting the offset, otherwise, if audio is behind in loading,
  47836. // segments from the previous timeline would be adjusted by the new timestamp offset.
  47837. //
  47838. // This requirement means that video will not cross a timeline until the audio is
  47839. // about to cross to it, so that way audio and video will always cross the timeline
  47840. // together.
  47841. //
  47842. // In addition to normal timeline changes, these rules also apply to the start of a
  47843. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  47844. // that these rules apply to the first timeline change because if they did not, it's
  47845. // possible that the main loader will cross two timelines before the audio loader has
  47846. // crossed one. Logic may be implemented to handle the startup as a special case, but
  47847. // it's easier to simply treat all timeline changes the same.
  47848. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  47849. return false;
  47850. }
  47851. return true;
  47852. }
  47853. return false;
  47854. };
  47855. const mediaDuration = timingInfos => {
  47856. let maxDuration = 0;
  47857. ['video', 'audio'].forEach(function (type) {
  47858. const typeTimingInfo = timingInfos[`${type}TimingInfo`];
  47859. if (!typeTimingInfo) {
  47860. return;
  47861. }
  47862. const {
  47863. start,
  47864. end
  47865. } = typeTimingInfo;
  47866. let duration;
  47867. if (typeof start === 'bigint' || typeof end === 'bigint') {
  47868. duration = window.BigInt(end) - window.BigInt(start);
  47869. } else if (typeof start === 'number' && typeof end === 'number') {
  47870. duration = end - start;
  47871. }
  47872. if (typeof duration !== 'undefined' && duration > maxDuration) {
  47873. maxDuration = duration;
  47874. }
  47875. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  47876. // as we only need BigInt when we are above that.
  47877. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  47878. maxDuration = Number(maxDuration);
  47879. }
  47880. return maxDuration;
  47881. };
  47882. const segmentTooLong = ({
  47883. segmentDuration,
  47884. maxDuration
  47885. }) => {
  47886. // 0 duration segments are most likely due to metadata only segments or a lack of
  47887. // information.
  47888. if (!segmentDuration) {
  47889. return false;
  47890. } // For HLS:
  47891. //
  47892. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  47893. // The EXTINF duration of each Media Segment in the Playlist
  47894. // file, when rounded to the nearest integer, MUST be less than or equal
  47895. // to the target duration; longer segments can trigger playback stalls
  47896. // or other errors.
  47897. //
  47898. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  47899. // duration. Although that reported duration is occasionally approximate (i.e., not
  47900. // exact), a strict check may report that a segment is too long more often in DASH.
  47901. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  47902. };
  47903. const getTroublesomeSegmentDurationMessage = (segmentInfo, sourceType) => {
  47904. // Right now we aren't following DASH's timing model exactly, so only perform
  47905. // this check for HLS content.
  47906. if (sourceType !== 'hls') {
  47907. return null;
  47908. }
  47909. const segmentDuration = mediaDuration({
  47910. audioTimingInfo: segmentInfo.audioTimingInfo,
  47911. videoTimingInfo: segmentInfo.videoTimingInfo
  47912. }); // Don't report if we lack information.
  47913. //
  47914. // If the segment has a duration of 0 it is either a lack of information or a
  47915. // metadata only segment and shouldn't be reported here.
  47916. if (!segmentDuration) {
  47917. return null;
  47918. }
  47919. const targetDuration = segmentInfo.playlist.targetDuration;
  47920. const isSegmentWayTooLong = segmentTooLong({
  47921. segmentDuration,
  47922. maxDuration: targetDuration * 2
  47923. });
  47924. const isSegmentSlightlyTooLong = segmentTooLong({
  47925. segmentDuration,
  47926. maxDuration: targetDuration
  47927. });
  47928. 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';
  47929. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  47930. return {
  47931. severity: isSegmentWayTooLong ? 'warn' : 'info',
  47932. message: segmentTooLongMessage
  47933. };
  47934. }
  47935. return null;
  47936. };
  47937. /**
  47938. * An object that manages segment loading and appending.
  47939. *
  47940. * @class SegmentLoader
  47941. * @param {Object} options required and optional options
  47942. * @extends videojs.EventTarget
  47943. */
  47944. class SegmentLoader extends videojs.EventTarget {
  47945. constructor(settings, options = {}) {
  47946. super(); // check pre-conditions
  47947. if (!settings) {
  47948. throw new TypeError('Initialization settings are required');
  47949. }
  47950. if (typeof settings.currentTime !== 'function') {
  47951. throw new TypeError('No currentTime getter specified');
  47952. }
  47953. if (!settings.mediaSource) {
  47954. throw new TypeError('No MediaSource specified');
  47955. } // public properties
  47956. this.bandwidth = settings.bandwidth;
  47957. this.throughput = {
  47958. rate: 0,
  47959. count: 0
  47960. };
  47961. this.roundTrip = NaN;
  47962. this.resetStats_();
  47963. this.mediaIndex = null;
  47964. this.partIndex = null; // private settings
  47965. this.hasPlayed_ = settings.hasPlayed;
  47966. this.currentTime_ = settings.currentTime;
  47967. this.seekable_ = settings.seekable;
  47968. this.seeking_ = settings.seeking;
  47969. this.duration_ = settings.duration;
  47970. this.mediaSource_ = settings.mediaSource;
  47971. this.vhs_ = settings.vhs;
  47972. this.loaderType_ = settings.loaderType;
  47973. this.currentMediaInfo_ = void 0;
  47974. this.startingMediaInfo_ = void 0;
  47975. this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  47976. this.goalBufferLength_ = settings.goalBufferLength;
  47977. this.sourceType_ = settings.sourceType;
  47978. this.sourceUpdater_ = settings.sourceUpdater;
  47979. this.inbandTextTracks_ = settings.inbandTextTracks;
  47980. this.state_ = 'INIT';
  47981. this.timelineChangeController_ = settings.timelineChangeController;
  47982. this.shouldSaveSegmentTimingInfo_ = true;
  47983. this.parse708captions_ = settings.parse708captions;
  47984. this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  47985. this.captionServices_ = settings.captionServices;
  47986. this.exactManifestTimings = settings.exactManifestTimings; // private instance variables
  47987. this.checkBufferTimeout_ = null;
  47988. this.error_ = void 0;
  47989. this.currentTimeline_ = -1;
  47990. this.pendingSegment_ = null;
  47991. this.xhrOptions_ = null;
  47992. this.pendingSegments_ = [];
  47993. this.audioDisabled_ = false;
  47994. this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  47995. this.gopBuffer_ = [];
  47996. this.timeMapping_ = 0;
  47997. this.safeAppend_ = videojs.browser.IE_VERSION >= 11;
  47998. this.appendInitSegment_ = {
  47999. audio: true,
  48000. video: true
  48001. };
  48002. this.playlistOfLastInitSegment_ = {
  48003. audio: null,
  48004. video: null
  48005. };
  48006. this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  48007. // information yet to start the loading process (e.g., if the audio loader wants to
  48008. // load a segment from the next timeline but the main loader hasn't yet crossed that
  48009. // timeline), then the load call will be added to the queue until it is ready to be
  48010. // processed.
  48011. this.loadQueue_ = [];
  48012. this.metadataQueue_ = {
  48013. id3: [],
  48014. caption: []
  48015. };
  48016. this.waitingOnRemove_ = false;
  48017. this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  48018. this.activeInitSegmentId_ = null;
  48019. this.initSegments_ = {}; // HLSe playback
  48020. this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  48021. this.keyCache_ = {};
  48022. this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  48023. // between a time in the display time and a segment index within
  48024. // a playlist
  48025. this.syncController_ = settings.syncController;
  48026. this.syncPoint_ = {
  48027. segmentIndex: 0,
  48028. time: 0
  48029. };
  48030. this.transmuxer_ = this.createTransmuxer_();
  48031. this.triggerSyncInfoUpdate_ = () => this.trigger('syncinfoupdate');
  48032. this.syncController_.on('syncinfoupdate', this.triggerSyncInfoUpdate_);
  48033. this.mediaSource_.addEventListener('sourceopen', () => {
  48034. if (!this.isEndOfStream_()) {
  48035. this.ended_ = false;
  48036. }
  48037. }); // ...for determining the fetch location
  48038. this.fetchAtBuffer_ = false;
  48039. this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);
  48040. Object.defineProperty(this, 'state', {
  48041. get() {
  48042. return this.state_;
  48043. },
  48044. set(newState) {
  48045. if (newState !== this.state_) {
  48046. this.logger_(`${this.state_} -> ${newState}`);
  48047. this.state_ = newState;
  48048. this.trigger('statechange');
  48049. }
  48050. }
  48051. });
  48052. this.sourceUpdater_.on('ready', () => {
  48053. if (this.hasEnoughInfoToAppend_()) {
  48054. this.processCallQueue_();
  48055. }
  48056. }); // Only the main loader needs to listen for pending timeline changes, as the main
  48057. // loader should wait for audio to be ready to change its timeline so that both main
  48058. // and audio timelines change together. For more details, see the
  48059. // shouldWaitForTimelineChange function.
  48060. if (this.loaderType_ === 'main') {
  48061. this.timelineChangeController_.on('pendingtimelinechange', () => {
  48062. if (this.hasEnoughInfoToAppend_()) {
  48063. this.processCallQueue_();
  48064. }
  48065. });
  48066. } // The main loader only listens on pending timeline changes, but the audio loader,
  48067. // since its loads follow main, needs to listen on timeline changes. For more details,
  48068. // see the shouldWaitForTimelineChange function.
  48069. if (this.loaderType_ === 'audio') {
  48070. this.timelineChangeController_.on('timelinechange', () => {
  48071. if (this.hasEnoughInfoToLoad_()) {
  48072. this.processLoadQueue_();
  48073. }
  48074. if (this.hasEnoughInfoToAppend_()) {
  48075. this.processCallQueue_();
  48076. }
  48077. });
  48078. }
  48079. }
  48080. createTransmuxer_() {
  48081. return segmentTransmuxer.createTransmuxer({
  48082. remux: false,
  48083. alignGopsAtEnd: this.safeAppend_,
  48084. keepOriginalTimestamps: true,
  48085. parse708captions: this.parse708captions_,
  48086. captionServices: this.captionServices_
  48087. });
  48088. }
  48089. /**
  48090. * reset all of our media stats
  48091. *
  48092. * @private
  48093. */
  48094. resetStats_() {
  48095. this.mediaBytesTransferred = 0;
  48096. this.mediaRequests = 0;
  48097. this.mediaRequestsAborted = 0;
  48098. this.mediaRequestsTimedout = 0;
  48099. this.mediaRequestsErrored = 0;
  48100. this.mediaTransferDuration = 0;
  48101. this.mediaSecondsLoaded = 0;
  48102. this.mediaAppends = 0;
  48103. }
  48104. /**
  48105. * dispose of the SegmentLoader and reset to the default state
  48106. */
  48107. dispose() {
  48108. this.trigger('dispose');
  48109. this.state = 'DISPOSED';
  48110. this.pause();
  48111. this.abort_();
  48112. if (this.transmuxer_) {
  48113. this.transmuxer_.terminate();
  48114. }
  48115. this.resetStats_();
  48116. if (this.checkBufferTimeout_) {
  48117. window.clearTimeout(this.checkBufferTimeout_);
  48118. }
  48119. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  48120. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  48121. }
  48122. this.off();
  48123. }
  48124. setAudio(enable) {
  48125. this.audioDisabled_ = !enable;
  48126. if (enable) {
  48127. this.appendInitSegment_.audio = true;
  48128. } else {
  48129. // remove current track audio if it gets disabled
  48130. this.sourceUpdater_.removeAudio(0, this.duration_());
  48131. }
  48132. }
  48133. /**
  48134. * abort anything that is currently doing on with the SegmentLoader
  48135. * and reset to a default state
  48136. */
  48137. abort() {
  48138. if (this.state !== 'WAITING') {
  48139. if (this.pendingSegment_) {
  48140. this.pendingSegment_ = null;
  48141. }
  48142. return;
  48143. }
  48144. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  48145. // since we are no longer "waiting" on any requests. XHR callback is not always run
  48146. // when the request is aborted. This will prevent the loader from being stuck in the
  48147. // WAITING state indefinitely.
  48148. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  48149. // next segment
  48150. if (!this.paused()) {
  48151. this.monitorBuffer_();
  48152. }
  48153. }
  48154. /**
  48155. * abort all pending xhr requests and null any pending segements
  48156. *
  48157. * @private
  48158. */
  48159. abort_() {
  48160. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  48161. this.pendingSegment_.abortRequests();
  48162. } // clear out the segment being processed
  48163. this.pendingSegment_ = null;
  48164. this.callQueue_ = [];
  48165. this.loadQueue_ = [];
  48166. this.metadataQueue_.id3 = [];
  48167. this.metadataQueue_.caption = [];
  48168. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  48169. this.waitingOnRemove_ = false;
  48170. window.clearTimeout(this.quotaExceededErrorRetryTimeout_);
  48171. this.quotaExceededErrorRetryTimeout_ = null;
  48172. }
  48173. checkForAbort_(requestId) {
  48174. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  48175. // callback that happens should reset the state to READY so that loading can continue.
  48176. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  48177. this.state = 'READY';
  48178. return true;
  48179. }
  48180. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  48181. return true;
  48182. }
  48183. return false;
  48184. }
  48185. /**
  48186. * set an error on the segment loader and null out any pending segements
  48187. *
  48188. * @param {Error} error the error to set on the SegmentLoader
  48189. * @return {Error} the error that was set or that is currently set
  48190. */
  48191. error(error) {
  48192. if (typeof error !== 'undefined') {
  48193. this.logger_('error occurred:', error);
  48194. this.error_ = error;
  48195. }
  48196. this.pendingSegment_ = null;
  48197. return this.error_;
  48198. }
  48199. endOfStream() {
  48200. this.ended_ = true;
  48201. if (this.transmuxer_) {
  48202. // need to clear out any cached data to prepare for the new segment
  48203. segmentTransmuxer.reset(this.transmuxer_);
  48204. }
  48205. this.gopBuffer_.length = 0;
  48206. this.pause();
  48207. this.trigger('ended');
  48208. }
  48209. /**
  48210. * Indicates which time ranges are buffered
  48211. *
  48212. * @return {TimeRange}
  48213. * TimeRange object representing the current buffered ranges
  48214. */
  48215. buffered_() {
  48216. const trackInfo = this.getMediaInfo_();
  48217. if (!this.sourceUpdater_ || !trackInfo) {
  48218. return createTimeRanges();
  48219. }
  48220. if (this.loaderType_ === 'main') {
  48221. const {
  48222. hasAudio,
  48223. hasVideo,
  48224. isMuxed
  48225. } = trackInfo;
  48226. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  48227. return this.sourceUpdater_.buffered();
  48228. }
  48229. if (hasVideo) {
  48230. return this.sourceUpdater_.videoBuffered();
  48231. }
  48232. } // One case that can be ignored for now is audio only with alt audio,
  48233. // as we don't yet have proper support for that.
  48234. return this.sourceUpdater_.audioBuffered();
  48235. }
  48236. /**
  48237. * Gets and sets init segment for the provided map
  48238. *
  48239. * @param {Object} map
  48240. * The map object representing the init segment to get or set
  48241. * @param {boolean=} set
  48242. * If true, the init segment for the provided map should be saved
  48243. * @return {Object}
  48244. * map object for desired init segment
  48245. */
  48246. initSegmentForMap(map, set = false) {
  48247. if (!map) {
  48248. return null;
  48249. }
  48250. const id = initSegmentId(map);
  48251. let storedMap = this.initSegments_[id];
  48252. if (set && !storedMap && map.bytes) {
  48253. this.initSegments_[id] = storedMap = {
  48254. resolvedUri: map.resolvedUri,
  48255. byterange: map.byterange,
  48256. bytes: map.bytes,
  48257. tracks: map.tracks,
  48258. timescales: map.timescales
  48259. };
  48260. }
  48261. return storedMap || map;
  48262. }
  48263. /**
  48264. * Gets and sets key for the provided key
  48265. *
  48266. * @param {Object} key
  48267. * The key object representing the key to get or set
  48268. * @param {boolean=} set
  48269. * If true, the key for the provided key should be saved
  48270. * @return {Object}
  48271. * Key object for desired key
  48272. */
  48273. segmentKey(key, set = false) {
  48274. if (!key) {
  48275. return null;
  48276. }
  48277. const id = segmentKeyId(key);
  48278. let storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  48279. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  48280. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  48281. this.keyCache_[id] = storedKey = {
  48282. resolvedUri: key.resolvedUri,
  48283. bytes: key.bytes
  48284. };
  48285. }
  48286. const result = {
  48287. resolvedUri: (storedKey || key).resolvedUri
  48288. };
  48289. if (storedKey) {
  48290. result.bytes = storedKey.bytes;
  48291. }
  48292. return result;
  48293. }
  48294. /**
  48295. * Returns true if all configuration required for loading is present, otherwise false.
  48296. *
  48297. * @return {boolean} True if the all configuration is ready for loading
  48298. * @private
  48299. */
  48300. couldBeginLoading_() {
  48301. return this.playlist_ && !this.paused();
  48302. }
  48303. /**
  48304. * load a playlist and start to fill the buffer
  48305. */
  48306. load() {
  48307. // un-pause
  48308. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  48309. // specified
  48310. if (!this.playlist_) {
  48311. return;
  48312. } // if all the configuration is ready, initialize and begin loading
  48313. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  48314. return this.init_();
  48315. } // if we're in the middle of processing a segment already, don't
  48316. // kick off an additional segment request
  48317. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  48318. return;
  48319. }
  48320. this.state = 'READY';
  48321. }
  48322. /**
  48323. * Once all the starting parameters have been specified, begin
  48324. * operation. This method should only be invoked from the INIT
  48325. * state.
  48326. *
  48327. * @private
  48328. */
  48329. init_() {
  48330. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  48331. // audio data from the muxed content should be removed
  48332. this.resetEverything();
  48333. return this.monitorBuffer_();
  48334. }
  48335. /**
  48336. * set a playlist on the segment loader
  48337. *
  48338. * @param {PlaylistLoader} media the playlist to set on the segment loader
  48339. */
  48340. playlist(newPlaylist, options = {}) {
  48341. if (!newPlaylist) {
  48342. return;
  48343. }
  48344. const oldPlaylist = this.playlist_;
  48345. const segmentInfo = this.pendingSegment_;
  48346. this.playlist_ = newPlaylist;
  48347. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  48348. // is always our zero-time so force a sync update each time the playlist
  48349. // is refreshed from the server
  48350. //
  48351. // Use the INIT state to determine if playback has started, as the playlist sync info
  48352. // should be fixed once requests begin (as sync points are generated based on sync
  48353. // info), but not before then.
  48354. if (this.state === 'INIT') {
  48355. newPlaylist.syncInfo = {
  48356. mediaSequence: newPlaylist.mediaSequence,
  48357. time: 0
  48358. }; // Setting the date time mapping means mapping the program date time (if available)
  48359. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  48360. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  48361. // be updated as the playlist is refreshed before the loader starts loading, the
  48362. // program date time mapping needs to be updated as well.
  48363. //
  48364. // This mapping is only done for the main loader because a program date time should
  48365. // map equivalently between playlists.
  48366. if (this.loaderType_ === 'main') {
  48367. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  48368. }
  48369. }
  48370. let oldId = null;
  48371. if (oldPlaylist) {
  48372. if (oldPlaylist.id) {
  48373. oldId = oldPlaylist.id;
  48374. } else if (oldPlaylist.uri) {
  48375. oldId = oldPlaylist.uri;
  48376. }
  48377. }
  48378. this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  48379. // in LIVE, we always want to update with new playlists (including refreshes)
  48380. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  48381. // buffering now
  48382. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  48383. return this.init_();
  48384. }
  48385. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  48386. if (this.mediaIndex !== null) {
  48387. // we must reset/resync the segment loader when we switch renditions and
  48388. // the segment loader is already synced to the previous rendition
  48389. // on playlist changes we want it to be possible to fetch
  48390. // at the buffer for vod but not for live. So we use resetLoader
  48391. // for live and resyncLoader for vod. We want this because
  48392. // if a playlist uses independent and non-independent segments/parts the
  48393. // buffer may not accurately reflect the next segment that we should try
  48394. // downloading.
  48395. if (!newPlaylist.endList) {
  48396. this.resetLoader();
  48397. } else {
  48398. this.resyncLoader();
  48399. }
  48400. }
  48401. this.currentMediaInfo_ = void 0;
  48402. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  48403. return;
  48404. } // we reloaded the same playlist so we are in a live scenario
  48405. // and we will likely need to adjust the mediaIndex
  48406. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  48407. this.logger_(`live window shift [${mediaSequenceDiff}]`); // update the mediaIndex on the SegmentLoader
  48408. // this is important because we can abort a request and this value must be
  48409. // equal to the last appended mediaIndex
  48410. if (this.mediaIndex !== null) {
  48411. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  48412. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  48413. // new playlist was incremented by 1.
  48414. if (this.mediaIndex < 0) {
  48415. this.mediaIndex = null;
  48416. this.partIndex = null;
  48417. } else {
  48418. const segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  48419. // unless parts fell off of the playlist for this segment.
  48420. // In that case we need to reset partIndex and resync
  48421. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  48422. const mediaIndex = this.mediaIndex;
  48423. this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`);
  48424. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  48425. // as the part was dropped from our current playlists segment.
  48426. // The mediaIndex will still be valid so keep that around.
  48427. this.mediaIndex = mediaIndex;
  48428. }
  48429. }
  48430. } // update the mediaIndex on the SegmentInfo object
  48431. // this is important because we will update this.mediaIndex with this value
  48432. // in `handleAppendsDone_` after the segment has been successfully appended
  48433. if (segmentInfo) {
  48434. segmentInfo.mediaIndex -= mediaSequenceDiff;
  48435. if (segmentInfo.mediaIndex < 0) {
  48436. segmentInfo.mediaIndex = null;
  48437. segmentInfo.partIndex = null;
  48438. } else {
  48439. // we need to update the referenced segment so that timing information is
  48440. // saved for the new playlist's segment, however, if the segment fell off the
  48441. // playlist, we can leave the old reference and just lose the timing info
  48442. if (segmentInfo.mediaIndex >= 0) {
  48443. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  48444. }
  48445. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  48446. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  48447. }
  48448. }
  48449. }
  48450. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  48451. }
  48452. /**
  48453. * Prevent the loader from fetching additional segments. If there
  48454. * is a segment request outstanding, it will finish processing
  48455. * before the loader halts. A segment loader can be unpaused by
  48456. * calling load().
  48457. */
  48458. pause() {
  48459. if (this.checkBufferTimeout_) {
  48460. window.clearTimeout(this.checkBufferTimeout_);
  48461. this.checkBufferTimeout_ = null;
  48462. }
  48463. }
  48464. /**
  48465. * Returns whether the segment loader is fetching additional
  48466. * segments when given the opportunity. This property can be
  48467. * modified through calls to pause() and load().
  48468. */
  48469. paused() {
  48470. return this.checkBufferTimeout_ === null;
  48471. }
  48472. /**
  48473. * Delete all the buffered data and reset the SegmentLoader
  48474. *
  48475. * @param {Function} [done] an optional callback to be executed when the remove
  48476. * operation is complete
  48477. */
  48478. resetEverything(done) {
  48479. this.ended_ = false;
  48480. this.activeInitSegmentId_ = null;
  48481. this.appendInitSegment_ = {
  48482. audio: true,
  48483. video: true
  48484. };
  48485. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  48486. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  48487. // we then clamp the value to duration if necessary.
  48488. this.remove(0, Infinity, done); // clears fmp4 captions
  48489. if (this.transmuxer_) {
  48490. this.transmuxer_.postMessage({
  48491. action: 'clearAllMp4Captions'
  48492. }); // reset the cache in the transmuxer
  48493. this.transmuxer_.postMessage({
  48494. action: 'reset'
  48495. });
  48496. }
  48497. }
  48498. /**
  48499. * Force the SegmentLoader to resync and start loading around the currentTime instead
  48500. * of starting at the end of the buffer
  48501. *
  48502. * Useful for fast quality changes
  48503. */
  48504. resetLoader() {
  48505. this.fetchAtBuffer_ = false;
  48506. this.resyncLoader();
  48507. }
  48508. /**
  48509. * Force the SegmentLoader to restart synchronization and make a conservative guess
  48510. * before returning to the simple walk-forward method
  48511. */
  48512. resyncLoader() {
  48513. if (this.transmuxer_) {
  48514. // need to clear out any cached data to prepare for the new segment
  48515. segmentTransmuxer.reset(this.transmuxer_);
  48516. }
  48517. this.mediaIndex = null;
  48518. this.partIndex = null;
  48519. this.syncPoint_ = null;
  48520. this.isPendingTimestampOffset_ = false;
  48521. this.callQueue_ = [];
  48522. this.loadQueue_ = [];
  48523. this.metadataQueue_.id3 = [];
  48524. this.metadataQueue_.caption = [];
  48525. this.abort();
  48526. if (this.transmuxer_) {
  48527. this.transmuxer_.postMessage({
  48528. action: 'clearParsedMp4Captions'
  48529. });
  48530. }
  48531. }
  48532. /**
  48533. * Remove any data in the source buffer between start and end times
  48534. *
  48535. * @param {number} start - the start time of the region to remove from the buffer
  48536. * @param {number} end - the end time of the region to remove from the buffer
  48537. * @param {Function} [done] - an optional callback to be executed when the remove
  48538. * @param {boolean} force - force all remove operations to happen
  48539. * operation is complete
  48540. */
  48541. remove(start, end, done = () => {}, force = false) {
  48542. // clamp end to duration if we need to remove everything.
  48543. // This is due to a browser bug that causes issues if we remove to Infinity.
  48544. // videojs/videojs-contrib-hls#1225
  48545. if (end === Infinity) {
  48546. end = this.duration_();
  48547. } // skip removes that would throw an error
  48548. // commonly happens during a rendition switch at the start of a video
  48549. // from start 0 to end 0
  48550. if (end <= start) {
  48551. this.logger_('skipping remove because end ${end} is <= start ${start}');
  48552. return;
  48553. }
  48554. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  48555. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  48556. return;
  48557. } // set it to one to complete this function's removes
  48558. let removesRemaining = 1;
  48559. const removeFinished = () => {
  48560. removesRemaining--;
  48561. if (removesRemaining === 0) {
  48562. done();
  48563. }
  48564. };
  48565. if (force || !this.audioDisabled_) {
  48566. removesRemaining++;
  48567. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  48568. } // While it would be better to only remove video if the main loader has video, this
  48569. // should be safe with audio only as removeVideo will call back even if there's no
  48570. // video buffer.
  48571. //
  48572. // In theory we can check to see if there's video before calling the remove, but in
  48573. // the event that we're switching between renditions and from video to audio only
  48574. // (when we add support for that), we may need to clear the video contents despite
  48575. // what the new media will contain.
  48576. if (force || this.loaderType_ === 'main') {
  48577. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  48578. removesRemaining++;
  48579. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  48580. } // remove any captions and ID3 tags
  48581. for (const track in this.inbandTextTracks_) {
  48582. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  48583. }
  48584. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  48585. removeFinished();
  48586. }
  48587. /**
  48588. * (re-)schedule monitorBufferTick_ to run as soon as possible
  48589. *
  48590. * @private
  48591. */
  48592. monitorBuffer_() {
  48593. if (this.checkBufferTimeout_) {
  48594. window.clearTimeout(this.checkBufferTimeout_);
  48595. }
  48596. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), 1);
  48597. }
  48598. /**
  48599. * As long as the SegmentLoader is in the READY state, periodically
  48600. * invoke fillBuffer_().
  48601. *
  48602. * @private
  48603. */
  48604. monitorBufferTick_() {
  48605. if (this.state === 'READY') {
  48606. this.fillBuffer_();
  48607. }
  48608. if (this.checkBufferTimeout_) {
  48609. window.clearTimeout(this.checkBufferTimeout_);
  48610. }
  48611. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  48612. }
  48613. /**
  48614. * fill the buffer with segements unless the sourceBuffers are
  48615. * currently updating
  48616. *
  48617. * Note: this function should only ever be called by monitorBuffer_
  48618. * and never directly
  48619. *
  48620. * @private
  48621. */
  48622. fillBuffer_() {
  48623. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  48624. // except when we're ready for the next segment, this check can most likely be removed
  48625. if (this.sourceUpdater_.updating()) {
  48626. return;
  48627. } // see if we need to begin loading immediately
  48628. const segmentInfo = this.chooseNextRequest_();
  48629. if (!segmentInfo) {
  48630. return;
  48631. }
  48632. if (typeof segmentInfo.timestampOffset === 'number') {
  48633. this.isPendingTimestampOffset_ = false;
  48634. this.timelineChangeController_.pendingTimelineChange({
  48635. type: this.loaderType_,
  48636. from: this.currentTimeline_,
  48637. to: segmentInfo.timeline
  48638. });
  48639. }
  48640. this.loadSegment_(segmentInfo);
  48641. }
  48642. /**
  48643. * Determines if we should call endOfStream on the media source based
  48644. * on the state of the buffer or if appened segment was the final
  48645. * segment in the playlist.
  48646. *
  48647. * @param {number} [mediaIndex] the media index of segment we last appended
  48648. * @param {Object} [playlist] a media playlist object
  48649. * @return {boolean} do we need to call endOfStream on the MediaSource
  48650. */
  48651. isEndOfStream_(mediaIndex = this.mediaIndex, playlist = this.playlist_, partIndex = this.partIndex) {
  48652. if (!playlist || !this.mediaSource_) {
  48653. return false;
  48654. }
  48655. const segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  48656. const appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  48657. 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
  48658. // so that MediaSources can trigger the `ended` event when it runs out of
  48659. // buffered data instead of waiting for me
  48660. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  48661. }
  48662. /**
  48663. * Determines what request should be made given current segment loader state.
  48664. *
  48665. * @return {Object} a request object that describes the segment/part to load
  48666. */
  48667. chooseNextRequest_() {
  48668. const buffered = this.buffered_();
  48669. const bufferedEnd = lastBufferedEnd(buffered) || 0;
  48670. const bufferedTime = timeAheadOf(buffered, this.currentTime_());
  48671. const preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  48672. const haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  48673. const segments = this.playlist_.segments; // return no segment if:
  48674. // 1. we don't have segments
  48675. // 2. The video has not yet played and we already downloaded a segment
  48676. // 3. we already have enough buffered time
  48677. if (!segments.length || preloaded || haveEnoughBuffer) {
  48678. return null;
  48679. }
  48680. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
  48681. const next = {
  48682. partIndex: null,
  48683. mediaIndex: null,
  48684. startOfSegment: null,
  48685. playlist: this.playlist_,
  48686. isSyncRequest: Boolean(!this.syncPoint_)
  48687. };
  48688. if (next.isSyncRequest) {
  48689. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  48690. } else if (this.mediaIndex !== null) {
  48691. const segment = segments[this.mediaIndex];
  48692. const partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  48693. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  48694. if (segment.parts && segment.parts[partIndex + 1]) {
  48695. next.mediaIndex = this.mediaIndex;
  48696. next.partIndex = partIndex + 1;
  48697. } else {
  48698. next.mediaIndex = this.mediaIndex + 1;
  48699. }
  48700. } else {
  48701. // Find the segment containing the end of the buffer or current time.
  48702. const {
  48703. segmentIndex,
  48704. startTime,
  48705. partIndex
  48706. } = Playlist.getMediaInfoForTime({
  48707. exactManifestTimings: this.exactManifestTimings,
  48708. playlist: this.playlist_,
  48709. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  48710. startingPartIndex: this.syncPoint_.partIndex,
  48711. startingSegmentIndex: this.syncPoint_.segmentIndex,
  48712. startTime: this.syncPoint_.time
  48713. });
  48714. next.getMediaInfoForTime = this.fetchAtBuffer_ ? `bufferedEnd ${bufferedEnd}` : `currentTime ${this.currentTime_()}`;
  48715. next.mediaIndex = segmentIndex;
  48716. next.startOfSegment = startTime;
  48717. next.partIndex = partIndex;
  48718. }
  48719. const nextSegment = segments[next.mediaIndex];
  48720. let nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  48721. // the next partIndex is invalid do not choose a next segment.
  48722. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  48723. return null;
  48724. } // if the next segment has parts, and we don't have a partIndex.
  48725. // Set partIndex to 0
  48726. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  48727. next.partIndex = 0;
  48728. nextPart = nextSegment.parts[0];
  48729. } // if we have no buffered data then we need to make sure
  48730. // that the next part we append is "independent" if possible.
  48731. // So we check if the previous part is independent, and request
  48732. // it if it is.
  48733. if (!bufferedTime && nextPart && !nextPart.independent) {
  48734. if (next.partIndex === 0) {
  48735. const lastSegment = segments[next.mediaIndex - 1];
  48736. const lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  48737. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  48738. next.mediaIndex -= 1;
  48739. next.partIndex = lastSegment.parts.length - 1;
  48740. next.independent = 'previous segment';
  48741. }
  48742. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  48743. next.partIndex -= 1;
  48744. next.independent = 'previous part';
  48745. }
  48746. }
  48747. const ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  48748. // 1. this is the last segment in the playlist
  48749. // 2. end of stream has been called on the media source already
  48750. // 3. the player is not seeking
  48751. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  48752. return null;
  48753. }
  48754. return this.generateSegmentInfo_(next);
  48755. }
  48756. generateSegmentInfo_(options) {
  48757. const {
  48758. independent,
  48759. playlist,
  48760. mediaIndex,
  48761. startOfSegment,
  48762. isSyncRequest,
  48763. partIndex,
  48764. forceTimestampOffset,
  48765. getMediaInfoForTime
  48766. } = options;
  48767. const segment = playlist.segments[mediaIndex];
  48768. const part = typeof partIndex === 'number' && segment.parts[partIndex];
  48769. const segmentInfo = {
  48770. requestId: 'segment-loader-' + Math.random(),
  48771. // resolve the segment URL relative to the playlist
  48772. uri: part && part.resolvedUri || segment.resolvedUri,
  48773. // the segment's mediaIndex at the time it was requested
  48774. mediaIndex,
  48775. partIndex: part ? partIndex : null,
  48776. // whether or not to update the SegmentLoader's state with this
  48777. // segment's mediaIndex
  48778. isSyncRequest,
  48779. startOfSegment,
  48780. // the segment's playlist
  48781. playlist,
  48782. // unencrypted bytes of the segment
  48783. bytes: null,
  48784. // when a key is defined for this segment, the encrypted bytes
  48785. encryptedBytes: null,
  48786. // The target timestampOffset for this segment when we append it
  48787. // to the source buffer
  48788. timestampOffset: null,
  48789. // The timeline that the segment is in
  48790. timeline: segment.timeline,
  48791. // The expected duration of the segment in seconds
  48792. duration: part && part.duration || segment.duration,
  48793. // retain the segment in case the playlist updates while doing an async process
  48794. segment,
  48795. part,
  48796. byteLength: 0,
  48797. transmuxer: this.transmuxer_,
  48798. // type of getMediaInfoForTime that was used to get this segment
  48799. getMediaInfoForTime,
  48800. independent
  48801. };
  48802. const overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  48803. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  48804. segmentTimeline: segment.timeline,
  48805. currentTimeline: this.currentTimeline_,
  48806. startOfSegment,
  48807. buffered: this.buffered_(),
  48808. overrideCheck
  48809. });
  48810. const audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  48811. if (typeof audioBufferedEnd === 'number') {
  48812. // since the transmuxer is using the actual timing values, but the buffer is
  48813. // adjusted by the timestamp offset, we must adjust the value here
  48814. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  48815. }
  48816. if (this.sourceUpdater_.videoBuffered().length) {
  48817. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_,
  48818. // since the transmuxer is using the actual timing values, but the time is
  48819. // adjusted by the timestmap offset, we must adjust the value here
  48820. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  48821. }
  48822. return segmentInfo;
  48823. } // get the timestampoffset for a segment,
  48824. // added so that vtt segment loader can override and prevent
  48825. // adding timestamp offsets.
  48826. timestampOffsetForSegment_(options) {
  48827. return timestampOffsetForSegment(options);
  48828. }
  48829. /**
  48830. * Determines if the network has enough bandwidth to complete the current segment
  48831. * request in a timely manner. If not, the request will be aborted early and bandwidth
  48832. * updated to trigger a playlist switch.
  48833. *
  48834. * @param {Object} stats
  48835. * Object containing stats about the request timing and size
  48836. * @private
  48837. */
  48838. earlyAbortWhenNeeded_(stats) {
  48839. if (this.vhs_.tech_.paused() ||
  48840. // Don't abort if the current playlist is on the lowestEnabledRendition
  48841. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  48842. // the lowestEnabledRendition.
  48843. !this.xhrOptions_.timeout ||
  48844. // Don't abort if we have no bandwidth information to estimate segment sizes
  48845. !this.playlist_.attributes.BANDWIDTH) {
  48846. return;
  48847. } // Wait at least 1 second since the first byte of data has been received before
  48848. // using the calculated bandwidth from the progress event to allow the bitrate
  48849. // to stabilize
  48850. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  48851. return;
  48852. }
  48853. const currentTime = this.currentTime_();
  48854. const measuredBandwidth = stats.bandwidth;
  48855. const segmentDuration = this.pendingSegment_.duration;
  48856. const requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  48857. // if we are only left with less than 1 second when the request completes.
  48858. // A negative timeUntilRebuffering indicates we are already rebuffering
  48859. const timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  48860. // is larger than the estimated time until the player runs out of forward buffer
  48861. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  48862. return;
  48863. }
  48864. const switchCandidate = minRebufferMaxBandwidthSelector({
  48865. main: this.vhs_.playlists.main,
  48866. currentTime,
  48867. bandwidth: measuredBandwidth,
  48868. duration: this.duration_(),
  48869. segmentDuration,
  48870. timeUntilRebuffer: timeUntilRebuffer$1,
  48871. currentTimeline: this.currentTimeline_,
  48872. syncController: this.syncController_
  48873. });
  48874. if (!switchCandidate) {
  48875. return;
  48876. }
  48877. const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  48878. const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  48879. let minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  48880. // potential round trip time of the new request so that we are not too aggressive
  48881. // with switching to a playlist that might save us a fraction of a second.
  48882. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  48883. minimumTimeSaving = 1;
  48884. }
  48885. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  48886. return;
  48887. } // set the bandwidth to that of the desired playlist being sure to scale by
  48888. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  48889. // don't trigger a bandwidthupdate as the bandwidth is artifial
  48890. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  48891. this.trigger('earlyabort');
  48892. }
  48893. handleAbort_(segmentInfo) {
  48894. this.logger_(`Aborting ${segmentInfoString(segmentInfo)}`);
  48895. this.mediaRequestsAborted += 1;
  48896. }
  48897. /**
  48898. * XHR `progress` event handler
  48899. *
  48900. * @param {Event}
  48901. * The XHR `progress` event
  48902. * @param {Object} simpleSegment
  48903. * A simplified segment object copy
  48904. * @private
  48905. */
  48906. handleProgress_(event, simpleSegment) {
  48907. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  48908. if (this.checkForAbort_(simpleSegment.requestId)) {
  48909. return;
  48910. }
  48911. this.trigger('progress');
  48912. }
  48913. handleTrackInfo_(simpleSegment, trackInfo) {
  48914. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  48915. if (this.checkForAbort_(simpleSegment.requestId)) {
  48916. return;
  48917. }
  48918. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  48919. return;
  48920. }
  48921. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  48922. // Guard against cases where we're not getting track info at all until we are
  48923. // certain that all streams will provide it.
  48924. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  48925. this.appendInitSegment_ = {
  48926. audio: true,
  48927. video: true
  48928. };
  48929. this.startingMediaInfo_ = trackInfo;
  48930. this.currentMediaInfo_ = trackInfo;
  48931. this.logger_('trackinfo update', trackInfo);
  48932. this.trigger('trackinfo');
  48933. } // trackinfo may cause an abort if the trackinfo
  48934. // causes a codec change to an unsupported codec.
  48935. if (this.checkForAbort_(simpleSegment.requestId)) {
  48936. return;
  48937. } // set trackinfo on the pending segment so that
  48938. // it can append.
  48939. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  48940. if (this.hasEnoughInfoToAppend_()) {
  48941. this.processCallQueue_();
  48942. }
  48943. }
  48944. handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  48945. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  48946. if (this.checkForAbort_(simpleSegment.requestId)) {
  48947. return;
  48948. }
  48949. const segmentInfo = this.pendingSegment_;
  48950. const timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  48951. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  48952. segmentInfo[timingInfoProperty][timeType] = time;
  48953. this.logger_(`timinginfo: ${mediaType} - ${timeType} - ${time}`); // check if any calls were waiting on the timing info
  48954. if (this.hasEnoughInfoToAppend_()) {
  48955. this.processCallQueue_();
  48956. }
  48957. }
  48958. handleCaptions_(simpleSegment, captionData) {
  48959. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  48960. if (this.checkForAbort_(simpleSegment.requestId)) {
  48961. return;
  48962. } // This could only happen with fmp4 segments, but
  48963. // should still not happen in general
  48964. if (captionData.length === 0) {
  48965. this.logger_('SegmentLoader received no captions from a caption event');
  48966. return;
  48967. }
  48968. const segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  48969. // can be adjusted by the timestamp offset
  48970. if (!segmentInfo.hasAppendedData_) {
  48971. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  48972. return;
  48973. }
  48974. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  48975. const captionTracks = {}; // get total start/end and captions for each track/stream
  48976. captionData.forEach(caption => {
  48977. // caption.stream is actually a track name...
  48978. // set to the existing values in tracks or default values
  48979. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  48980. // Infinity, as any other value will be less than this
  48981. startTime: Infinity,
  48982. captions: [],
  48983. // 0 as an other value will be more than this
  48984. endTime: 0
  48985. };
  48986. const captionTrack = captionTracks[caption.stream];
  48987. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  48988. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  48989. captionTrack.captions.push(caption);
  48990. });
  48991. Object.keys(captionTracks).forEach(trackName => {
  48992. const {
  48993. startTime,
  48994. endTime,
  48995. captions
  48996. } = captionTracks[trackName];
  48997. const inbandTextTracks = this.inbandTextTracks_;
  48998. this.logger_(`adding cues from ${startTime} -> ${endTime} for ${trackName}`);
  48999. createCaptionsTrackIfNotExists(inbandTextTracks, this.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  49000. // We do this because a rendition change that also changes the timescale for captions
  49001. // will result in captions being re-parsed for certain segments. If we add them again
  49002. // without clearing we will have two of the same captions visible.
  49003. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  49004. addCaptionData({
  49005. captionArray: captions,
  49006. inbandTextTracks,
  49007. timestampOffset
  49008. });
  49009. }); // Reset stored captions since we added parsed
  49010. // captions to a text track at this point
  49011. if (this.transmuxer_) {
  49012. this.transmuxer_.postMessage({
  49013. action: 'clearParsedMp4Captions'
  49014. });
  49015. }
  49016. }
  49017. handleId3_(simpleSegment, id3Frames, dispatchType) {
  49018. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  49019. if (this.checkForAbort_(simpleSegment.requestId)) {
  49020. return;
  49021. }
  49022. const segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  49023. if (!segmentInfo.hasAppendedData_) {
  49024. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  49025. return;
  49026. }
  49027. 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
  49028. // audio/video source with a metadata track, and an alt audio with a metadata track.
  49029. // However, this probably won't happen, and if it does it can be handled then.
  49030. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
  49031. addMetadata({
  49032. inbandTextTracks: this.inbandTextTracks_,
  49033. metadataArray: id3Frames,
  49034. timestampOffset,
  49035. videoDuration: this.duration_()
  49036. });
  49037. }
  49038. processMetadataQueue_() {
  49039. this.metadataQueue_.id3.forEach(fn => fn());
  49040. this.metadataQueue_.caption.forEach(fn => fn());
  49041. this.metadataQueue_.id3 = [];
  49042. this.metadataQueue_.caption = [];
  49043. }
  49044. processCallQueue_() {
  49045. const callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  49046. // functions may check the length of the load queue and default to pushing themselves
  49047. // back onto the queue.
  49048. this.callQueue_ = [];
  49049. callQueue.forEach(fun => fun());
  49050. }
  49051. processLoadQueue_() {
  49052. const loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  49053. // functions may check the length of the load queue and default to pushing themselves
  49054. // back onto the queue.
  49055. this.loadQueue_ = [];
  49056. loadQueue.forEach(fun => fun());
  49057. }
  49058. /**
  49059. * Determines whether the loader has enough info to load the next segment.
  49060. *
  49061. * @return {boolean}
  49062. * Whether or not the loader has enough info to load the next segment
  49063. */
  49064. hasEnoughInfoToLoad_() {
  49065. // Since primary timing goes by video, only the audio loader potentially needs to wait
  49066. // to load.
  49067. if (this.loaderType_ !== 'audio') {
  49068. return true;
  49069. }
  49070. const segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  49071. // enough info to load.
  49072. if (!segmentInfo) {
  49073. return false;
  49074. } // The first segment can and should be loaded immediately so that source buffers are
  49075. // created together (before appending). Source buffer creation uses the presence of
  49076. // audio and video data to determine whether to create audio/video source buffers, and
  49077. // uses processed (transmuxed or parsed) media to determine the types required.
  49078. if (!this.getCurrentMediaInfo_()) {
  49079. return true;
  49080. }
  49081. if (
  49082. // Technically, instead of waiting to load a segment on timeline changes, a segment
  49083. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  49084. // But in practice, there are a few reasons why it is better to wait until a loader
  49085. // is ready to append that segment before requesting and downloading:
  49086. //
  49087. // 1. Because audio and main loaders cross discontinuities together, if this loader
  49088. // is waiting for the other to catch up, then instead of requesting another
  49089. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  49090. // allotted to the loader currently behind.
  49091. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  49092. // is ready to be processed or not, isolating the queueing behavior to the loader.
  49093. // 3. The audio loader bases some of its segment properties on timing information
  49094. // provided by the main loader, meaning that, if the logic for waiting on
  49095. // processing was in media-segment-request, then it would also need to know how
  49096. // to re-generate the segment information after the main loader caught up.
  49097. shouldWaitForTimelineChange({
  49098. timelineChangeController: this.timelineChangeController_,
  49099. currentTimeline: this.currentTimeline_,
  49100. segmentTimeline: segmentInfo.timeline,
  49101. loaderType: this.loaderType_,
  49102. audioDisabled: this.audioDisabled_
  49103. })) {
  49104. return false;
  49105. }
  49106. return true;
  49107. }
  49108. getCurrentMediaInfo_(segmentInfo = this.pendingSegment_) {
  49109. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  49110. }
  49111. getMediaInfo_(segmentInfo = this.pendingSegment_) {
  49112. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  49113. }
  49114. getPendingSegmentPlaylist() {
  49115. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  49116. }
  49117. hasEnoughInfoToAppend_() {
  49118. if (!this.sourceUpdater_.ready()) {
  49119. return false;
  49120. } // If content needs to be removed or the loader is waiting on an append reattempt,
  49121. // then no additional content should be appended until the prior append is resolved.
  49122. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  49123. return false;
  49124. }
  49125. const segmentInfo = this.pendingSegment_;
  49126. const trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  49127. // we do not have information on this specific
  49128. // segment yet
  49129. if (!segmentInfo || !trackInfo) {
  49130. return false;
  49131. }
  49132. const {
  49133. hasAudio,
  49134. hasVideo,
  49135. isMuxed
  49136. } = trackInfo;
  49137. if (hasVideo && !segmentInfo.videoTimingInfo) {
  49138. return false;
  49139. } // muxed content only relies on video timing information for now.
  49140. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  49141. return false;
  49142. }
  49143. if (shouldWaitForTimelineChange({
  49144. timelineChangeController: this.timelineChangeController_,
  49145. currentTimeline: this.currentTimeline_,
  49146. segmentTimeline: segmentInfo.timeline,
  49147. loaderType: this.loaderType_,
  49148. audioDisabled: this.audioDisabled_
  49149. })) {
  49150. return false;
  49151. }
  49152. return true;
  49153. }
  49154. handleData_(simpleSegment, result) {
  49155. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  49156. if (this.checkForAbort_(simpleSegment.requestId)) {
  49157. return;
  49158. } // If there's anything in the call queue, then this data came later and should be
  49159. // executed after the calls currently queued.
  49160. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  49161. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  49162. return;
  49163. }
  49164. const segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  49165. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  49166. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  49167. // logic may change behavior depending on the state, and changing state too early may
  49168. // inflate our estimates of bandwidth. In the future this should be re-examined to
  49169. // note more granular states.
  49170. // don't process and append data if the mediaSource is closed
  49171. if (this.mediaSource_.readyState === 'closed') {
  49172. return;
  49173. } // if this request included an initialization segment, save that data
  49174. // to the initSegment cache
  49175. if (simpleSegment.map) {
  49176. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  49177. segmentInfo.segment.map = simpleSegment.map;
  49178. } // if this request included a segment key, save that data in the cache
  49179. if (simpleSegment.key) {
  49180. this.segmentKey(simpleSegment.key, true);
  49181. }
  49182. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  49183. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  49184. if (segmentInfo.isFmp4) {
  49185. this.trigger('fmp4');
  49186. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  49187. } else {
  49188. const trackInfo = this.getCurrentMediaInfo_();
  49189. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  49190. let firstVideoFrameTimeForData;
  49191. if (useVideoTimingInfo) {
  49192. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  49193. } // Segment loader knows more about segment timing than the transmuxer (in certain
  49194. // aspects), so make any changes required for a more accurate start time.
  49195. // Don't set the end time yet, as the segment may not be finished processing.
  49196. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  49197. currentStart: segmentInfo.timingInfo.start,
  49198. playlist: segmentInfo.playlist,
  49199. mediaIndex: segmentInfo.mediaIndex,
  49200. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  49201. useVideoTimingInfo,
  49202. firstVideoFrameTimeForData,
  49203. videoTimingInfo: segmentInfo.videoTimingInfo,
  49204. audioTimingInfo: segmentInfo.audioTimingInfo
  49205. });
  49206. } // Init segments for audio and video only need to be appended in certain cases. Now
  49207. // that data is about to be appended, we can check the final cases to determine
  49208. // whether we should append an init segment.
  49209. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  49210. // as we use the start of the segment to offset the best guess (playlist provided)
  49211. // timestamp offset.
  49212. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  49213. // be appended or not.
  49214. if (segmentInfo.isSyncRequest) {
  49215. // first save/update our timing info for this segment.
  49216. // this is what allows us to choose an accurate segment
  49217. // and the main reason we make a sync request.
  49218. this.updateTimingInfoEnd_(segmentInfo);
  49219. this.syncController_.saveSegmentTimingInfo({
  49220. segmentInfo,
  49221. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  49222. });
  49223. const next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  49224. // after taking into account its timing info, do not append it.
  49225. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  49226. this.logger_('sync segment was incorrect, not appending');
  49227. return;
  49228. } // otherwise append it like any other segment as our guess was correct.
  49229. this.logger_('sync segment was correct, appending');
  49230. } // Save some state so that in the future anything waiting on first append (and/or
  49231. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  49232. // we need some notion of whether the timestamp offset or other relevant information
  49233. // has had a chance to be set.
  49234. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  49235. this.processMetadataQueue_();
  49236. this.appendData_(segmentInfo, result);
  49237. }
  49238. updateAppendInitSegmentStatus(segmentInfo, type) {
  49239. // alt audio doesn't manage timestamp offset
  49240. if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' &&
  49241. // in the case that we're handling partial data, we don't want to append an init
  49242. // segment for each chunk
  49243. !segmentInfo.changedTimestampOffset) {
  49244. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  49245. // append init segments
  49246. this.appendInitSegment_ = {
  49247. audio: true,
  49248. video: true
  49249. };
  49250. }
  49251. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  49252. // make sure we append init segment on playlist changes, in case the media config
  49253. // changed
  49254. this.appendInitSegment_[type] = true;
  49255. }
  49256. }
  49257. getInitSegmentAndUpdateState_({
  49258. type,
  49259. initSegment,
  49260. map,
  49261. playlist
  49262. }) {
  49263. // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  49264. // (Section 3) required to parse the applicable Media Segments. It applies to every
  49265. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  49266. // or until the end of the playlist."
  49267. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  49268. if (map) {
  49269. const id = initSegmentId(map);
  49270. if (this.activeInitSegmentId_ === id) {
  49271. // don't need to re-append the init segment if the ID matches
  49272. return null;
  49273. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  49274. // obtained) init segment
  49275. //
  49276. // this also caches the init segment for later use
  49277. initSegment = this.initSegmentForMap(map, true).bytes;
  49278. this.activeInitSegmentId_ = id;
  49279. } // We used to always prepend init segments for video, however, that shouldn't be
  49280. // necessary. Instead, we should only append on changes, similar to what we've always
  49281. // done for audio. This is more important (though may not be that important) for
  49282. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  49283. // appends.
  49284. if (initSegment && this.appendInitSegment_[type]) {
  49285. // Make sure we track the playlist that we last used for the init segment, so that
  49286. // we can re-append the init segment in the event that we get data from a new
  49287. // playlist. Discontinuities and track changes are handled in other sections.
  49288. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  49289. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  49290. // we are appending the muxer init segment
  49291. this.activeInitSegmentId_ = null;
  49292. return initSegment;
  49293. }
  49294. return null;
  49295. }
  49296. handleQuotaExceededError_({
  49297. segmentInfo,
  49298. type,
  49299. bytes
  49300. }, error) {
  49301. const audioBuffered = this.sourceUpdater_.audioBuffered();
  49302. const videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  49303. // should be cleared out during the buffer removals. However, log in case it helps
  49304. // debug.
  49305. if (audioBuffered.length > 1) {
  49306. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  49307. }
  49308. if (videoBuffered.length > 1) {
  49309. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  49310. }
  49311. const audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  49312. const audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  49313. const videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  49314. const videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  49315. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  49316. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  49317. // allow for appends of segments this size). In the future, it may be possible to
  49318. // split up the segment and append in pieces, but for now, error out this playlist
  49319. // in an attempt to switch to a more manageable rendition.
  49320. 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(', ')}, `);
  49321. this.error({
  49322. message: 'Quota exceeded error with append of a single segment of content',
  49323. excludeUntil: Infinity
  49324. });
  49325. this.trigger('error');
  49326. return;
  49327. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  49328. // that the segment-loader should block on future events until this one is handled, so
  49329. // that it doesn't keep moving onto further segments. Adding the call to the call
  49330. // queue will prevent further appends until waitingOnRemove_ and
  49331. // quotaExceededErrorRetryTimeout_ are cleared.
  49332. //
  49333. // Note that this will only block the current loader. In the case of demuxed content,
  49334. // the other load may keep filling as fast as possible. In practice, this should be
  49335. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  49336. // source buffer, or video fills without enough room for audio to append (and without
  49337. // the availability of clearing out seconds of back buffer to make room for audio).
  49338. // But it might still be good to handle this case in the future as a TODO.
  49339. this.waitingOnRemove_ = true;
  49340. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  49341. segmentInfo,
  49342. type,
  49343. bytes
  49344. }));
  49345. const currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  49346. // before retrying.
  49347. const timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  49348. this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${timeToRemoveUntil}`);
  49349. this.remove(0, timeToRemoveUntil, () => {
  49350. this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${MIN_BACK_BUFFER}s`);
  49351. this.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  49352. // attempts (since we can't clear less than the minimum)
  49353. this.quotaExceededErrorRetryTimeout_ = window.setTimeout(() => {
  49354. this.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  49355. this.quotaExceededErrorRetryTimeout_ = null;
  49356. this.processCallQueue_();
  49357. }, MIN_BACK_BUFFER * 1000);
  49358. }, true);
  49359. }
  49360. handleAppendError_({
  49361. segmentInfo,
  49362. type,
  49363. bytes
  49364. }, error) {
  49365. // if there's no error, nothing to do
  49366. if (!error) {
  49367. return;
  49368. }
  49369. if (error.code === QUOTA_EXCEEDED_ERR) {
  49370. this.handleQuotaExceededError_({
  49371. segmentInfo,
  49372. type,
  49373. bytes
  49374. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  49375. // to trigger an append error.
  49376. return;
  49377. }
  49378. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  49379. 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.
  49380. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  49381. //
  49382. // Trigger a special error so that it can be handled separately from normal,
  49383. // recoverable errors.
  49384. this.trigger('appenderror');
  49385. }
  49386. appendToSourceBuffer_({
  49387. segmentInfo,
  49388. type,
  49389. initSegment,
  49390. data,
  49391. bytes
  49392. }) {
  49393. // If this is a re-append, bytes were already created and don't need to be recreated
  49394. if (!bytes) {
  49395. const segments = [data];
  49396. let byteLength = data.byteLength;
  49397. if (initSegment) {
  49398. // if the media initialization segment is changing, append it before the content
  49399. // segment
  49400. segments.unshift(initSegment);
  49401. byteLength += initSegment.byteLength;
  49402. } // Technically we should be OK appending the init segment separately, however, we
  49403. // haven't yet tested that, and prepending is how we have always done things.
  49404. bytes = concatSegments({
  49405. bytes: byteLength,
  49406. segments
  49407. });
  49408. }
  49409. this.sourceUpdater_.appendBuffer({
  49410. segmentInfo,
  49411. type,
  49412. bytes
  49413. }, this.handleAppendError_.bind(this, {
  49414. segmentInfo,
  49415. type,
  49416. bytes
  49417. }));
  49418. }
  49419. handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  49420. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  49421. return;
  49422. }
  49423. const segment = this.pendingSegment_.segment;
  49424. const timingInfoProperty = `${type}TimingInfo`;
  49425. if (!segment[timingInfoProperty]) {
  49426. segment[timingInfoProperty] = {};
  49427. }
  49428. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  49429. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  49430. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  49431. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  49432. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  49433. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  49434. }
  49435. appendData_(segmentInfo, result) {
  49436. const {
  49437. type,
  49438. data
  49439. } = result;
  49440. if (!data || !data.byteLength) {
  49441. return;
  49442. }
  49443. if (type === 'audio' && this.audioDisabled_) {
  49444. return;
  49445. }
  49446. const initSegment = this.getInitSegmentAndUpdateState_({
  49447. type,
  49448. initSegment: result.initSegment,
  49449. playlist: segmentInfo.playlist,
  49450. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  49451. });
  49452. this.appendToSourceBuffer_({
  49453. segmentInfo,
  49454. type,
  49455. initSegment,
  49456. data
  49457. });
  49458. }
  49459. /**
  49460. * load a specific segment from a request into the buffer
  49461. *
  49462. * @private
  49463. */
  49464. loadSegment_(segmentInfo) {
  49465. this.state = 'WAITING';
  49466. this.pendingSegment_ = segmentInfo;
  49467. this.trimBackBuffer_(segmentInfo);
  49468. if (typeof segmentInfo.timestampOffset === 'number') {
  49469. if (this.transmuxer_) {
  49470. this.transmuxer_.postMessage({
  49471. action: 'clearAllMp4Captions'
  49472. });
  49473. }
  49474. }
  49475. if (!this.hasEnoughInfoToLoad_()) {
  49476. this.loadQueue_.push(() => {
  49477. // regenerate the audioAppendStart, timestampOffset, etc as they
  49478. // may have changed since this function was added to the queue.
  49479. const options = _extends$1({}, segmentInfo, {
  49480. forceTimestampOffset: true
  49481. });
  49482. _extends$1(segmentInfo, this.generateSegmentInfo_(options));
  49483. this.isPendingTimestampOffset_ = false;
  49484. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  49485. });
  49486. return;
  49487. }
  49488. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  49489. }
  49490. updateTransmuxerAndRequestSegment_(segmentInfo) {
  49491. // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  49492. // the transmuxer still needs to be updated before then.
  49493. //
  49494. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  49495. // offset must be passed to the transmuxer for stream correcting adjustments.
  49496. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  49497. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  49498. segmentInfo.gopsToAlignWith = [];
  49499. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  49500. this.transmuxer_.postMessage({
  49501. action: 'reset'
  49502. });
  49503. this.transmuxer_.postMessage({
  49504. action: 'setTimestampOffset',
  49505. timestampOffset: segmentInfo.timestampOffset
  49506. });
  49507. }
  49508. const simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  49509. const isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  49510. const isWalkingForward = this.mediaIndex !== null;
  49511. const isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ &&
  49512. // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  49513. // the first timeline
  49514. segmentInfo.timeline > 0;
  49515. const isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  49516. 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),
  49517. // then this init segment has never been seen before and should be appended.
  49518. //
  49519. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  49520. // both to true and leave the decision of whether to append the init segment to append time.
  49521. if (simpleSegment.map && !simpleSegment.map.bytes) {
  49522. this.logger_('going to request init segment.');
  49523. this.appendInitSegment_ = {
  49524. video: true,
  49525. audio: true
  49526. };
  49527. }
  49528. segmentInfo.abortRequests = mediaSegmentRequest({
  49529. xhr: this.vhs_.xhr,
  49530. xhrOptions: this.xhrOptions_,
  49531. decryptionWorker: this.decrypter_,
  49532. segment: simpleSegment,
  49533. abortFn: this.handleAbort_.bind(this, segmentInfo),
  49534. progressFn: this.handleProgress_.bind(this),
  49535. trackInfoFn: this.handleTrackInfo_.bind(this),
  49536. timingInfoFn: this.handleTimingInfo_.bind(this),
  49537. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  49538. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  49539. captionsFn: this.handleCaptions_.bind(this),
  49540. isEndOfTimeline,
  49541. endedTimelineFn: () => {
  49542. this.logger_('received endedtimeline callback');
  49543. },
  49544. id3Fn: this.handleId3_.bind(this),
  49545. dataFn: this.handleData_.bind(this),
  49546. doneFn: this.segmentRequestFinished_.bind(this),
  49547. onTransmuxerLog: ({
  49548. message,
  49549. level,
  49550. stream
  49551. }) => {
  49552. this.logger_(`${segmentInfoString(segmentInfo)} logged from transmuxer stream ${stream} as a ${level}: ${message}`);
  49553. }
  49554. });
  49555. }
  49556. /**
  49557. * trim the back buffer so that we don't have too much data
  49558. * in the source buffer
  49559. *
  49560. * @private
  49561. *
  49562. * @param {Object} segmentInfo - the current segment
  49563. */
  49564. trimBackBuffer_(segmentInfo) {
  49565. const removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  49566. // buffer and a very conservative "garbage collector"
  49567. // We manually clear out the old buffer to ensure
  49568. // we don't trigger the QuotaExceeded error
  49569. // on the source buffer during subsequent appends
  49570. if (removeToTime > 0) {
  49571. this.remove(0, removeToTime);
  49572. }
  49573. }
  49574. /**
  49575. * created a simplified copy of the segment object with just the
  49576. * information necessary to perform the XHR and decryption
  49577. *
  49578. * @private
  49579. *
  49580. * @param {Object} segmentInfo - the current segment
  49581. * @return {Object} a simplified segment object copy
  49582. */
  49583. createSimplifiedSegmentObj_(segmentInfo) {
  49584. const segment = segmentInfo.segment;
  49585. const part = segmentInfo.part;
  49586. const simpleSegment = {
  49587. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  49588. byterange: part ? part.byterange : segment.byterange,
  49589. requestId: segmentInfo.requestId,
  49590. transmuxer: segmentInfo.transmuxer,
  49591. audioAppendStart: segmentInfo.audioAppendStart,
  49592. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  49593. part: segmentInfo.part
  49594. };
  49595. const previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  49596. if (previousSegment && previousSegment.timeline === segment.timeline) {
  49597. // The baseStartTime of a segment is used to handle rollover when probing the TS
  49598. // segment to retrieve timing information. Since the probe only looks at the media's
  49599. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  49600. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  49601. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  49602. // seconds of media time, so should be used here. The previous segment is used since
  49603. // the end of the previous segment should represent the beginning of the current
  49604. // segment, so long as they are on the same timeline.
  49605. if (previousSegment.videoTimingInfo) {
  49606. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  49607. } else if (previousSegment.audioTimingInfo) {
  49608. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  49609. }
  49610. }
  49611. if (segment.key) {
  49612. // if the media sequence is greater than 2^32, the IV will be incorrect
  49613. // assuming 10s segments, that would be about 1300 years
  49614. const iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  49615. simpleSegment.key = this.segmentKey(segment.key);
  49616. simpleSegment.key.iv = iv;
  49617. }
  49618. if (segment.map) {
  49619. simpleSegment.map = this.initSegmentForMap(segment.map);
  49620. }
  49621. return simpleSegment;
  49622. }
  49623. saveTransferStats_(stats) {
  49624. // every request counts as a media request even if it has been aborted
  49625. // or canceled due to a timeout
  49626. this.mediaRequests += 1;
  49627. if (stats) {
  49628. this.mediaBytesTransferred += stats.bytesReceived;
  49629. this.mediaTransferDuration += stats.roundTripTime;
  49630. }
  49631. }
  49632. saveBandwidthRelatedStats_(duration, stats) {
  49633. // byteLength will be used for throughput, and should be based on bytes receieved,
  49634. // which we only know at the end of the request and should reflect total bytes
  49635. // downloaded rather than just bytes processed from components of the segment
  49636. this.pendingSegment_.byteLength = stats.bytesReceived;
  49637. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  49638. this.logger_(`Ignoring segment's bandwidth because its duration of ${duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
  49639. return;
  49640. }
  49641. this.bandwidth = stats.bandwidth;
  49642. this.roundTrip = stats.roundTripTime;
  49643. }
  49644. handleTimeout_() {
  49645. // although the VTT segment loader bandwidth isn't really used, it's good to
  49646. // maintain functinality between segment loaders
  49647. this.mediaRequestsTimedout += 1;
  49648. this.bandwidth = 1;
  49649. this.roundTrip = NaN;
  49650. this.trigger('bandwidthupdate');
  49651. this.trigger('timeout');
  49652. }
  49653. /**
  49654. * Handle the callback from the segmentRequest function and set the
  49655. * associated SegmentLoader state and errors if necessary
  49656. *
  49657. * @private
  49658. */
  49659. segmentRequestFinished_(error, simpleSegment, result) {
  49660. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  49661. // check the call queue directly since this function doesn't need to deal with any
  49662. // data, and can continue even if the source buffers are not set up and we didn't get
  49663. // any data from the segment
  49664. if (this.callQueue_.length) {
  49665. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  49666. return;
  49667. }
  49668. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  49669. if (!this.pendingSegment_) {
  49670. return;
  49671. } // the request was aborted and the SegmentLoader has already started
  49672. // another request. this can happen when the timeout for an aborted
  49673. // request triggers due to a limitation in the XHR library
  49674. // do not count this as any sort of request or we risk double-counting
  49675. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  49676. return;
  49677. } // an error occurred from the active pendingSegment_ so reset everything
  49678. if (error) {
  49679. this.pendingSegment_ = null;
  49680. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  49681. if (error.code === REQUEST_ERRORS.ABORTED) {
  49682. return;
  49683. }
  49684. this.pause(); // the error is really just that at least one of the requests timed-out
  49685. // set the bandwidth to a very low value and trigger an ABR switch to
  49686. // take emergency action
  49687. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  49688. this.handleTimeout_();
  49689. return;
  49690. } // if control-flow has arrived here, then the error is real
  49691. // emit an error event to exclude the current playlist
  49692. this.mediaRequestsErrored += 1;
  49693. this.error(error);
  49694. this.trigger('error');
  49695. return;
  49696. }
  49697. const segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  49698. // generated for ABR purposes
  49699. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  49700. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  49701. if (result.gopInfo) {
  49702. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  49703. } // Although we may have already started appending on progress, we shouldn't switch the
  49704. // state away from loading until we are officially done loading the segment data.
  49705. this.state = 'APPENDING'; // used for testing
  49706. this.trigger('appending');
  49707. this.waitForAppendsToComplete_(segmentInfo);
  49708. }
  49709. setTimeMapping_(timeline) {
  49710. const timelineMapping = this.syncController_.mappingForTimeline(timeline);
  49711. if (timelineMapping !== null) {
  49712. this.timeMapping_ = timelineMapping;
  49713. }
  49714. }
  49715. updateMediaSecondsLoaded_(segment) {
  49716. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  49717. this.mediaSecondsLoaded += segment.end - segment.start;
  49718. } else {
  49719. this.mediaSecondsLoaded += segment.duration;
  49720. }
  49721. }
  49722. shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  49723. if (timestampOffset === null) {
  49724. return false;
  49725. } // note that we're potentially using the same timestamp offset for both video and
  49726. // audio
  49727. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  49728. return true;
  49729. }
  49730. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  49731. return true;
  49732. }
  49733. return false;
  49734. }
  49735. trueSegmentStart_({
  49736. currentStart,
  49737. playlist,
  49738. mediaIndex,
  49739. firstVideoFrameTimeForData,
  49740. currentVideoTimestampOffset,
  49741. useVideoTimingInfo,
  49742. videoTimingInfo,
  49743. audioTimingInfo
  49744. }) {
  49745. if (typeof currentStart !== 'undefined') {
  49746. // if start was set once, keep using it
  49747. return currentStart;
  49748. }
  49749. if (!useVideoTimingInfo) {
  49750. return audioTimingInfo.start;
  49751. }
  49752. const previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  49753. // within that segment. Since the transmuxer maintains a cache of incomplete data
  49754. // from and/or the last frame seen, the start time may reflect a frame that starts
  49755. // in the previous segment. Check for that case and ensure the start time is
  49756. // accurate for the segment.
  49757. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  49758. return firstVideoFrameTimeForData;
  49759. }
  49760. return videoTimingInfo.start;
  49761. }
  49762. waitForAppendsToComplete_(segmentInfo) {
  49763. const trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  49764. if (!trackInfo) {
  49765. this.error({
  49766. message: 'No starting media returned, likely due to an unsupported media format.',
  49767. playlistExclusionDuration: Infinity
  49768. });
  49769. this.trigger('error');
  49770. return;
  49771. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  49772. // on each queue this loader is responsible for to ensure that the appends are
  49773. // complete.
  49774. const {
  49775. hasAudio,
  49776. hasVideo,
  49777. isMuxed
  49778. } = trackInfo;
  49779. const waitForVideo = this.loaderType_ === 'main' && hasVideo;
  49780. const waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  49781. segmentInfo.waitingOnAppends = 0; // segments with no data
  49782. if (!segmentInfo.hasAppendedData_) {
  49783. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  49784. // When there's no audio or video data in the segment, there's no audio or video
  49785. // timing information.
  49786. //
  49787. // If there's no audio or video timing information, then the timestamp offset
  49788. // can't be adjusted to the appropriate value for the transmuxer and source
  49789. // buffers.
  49790. //
  49791. // Therefore, the next segment should be used to set the timestamp offset.
  49792. this.isPendingTimestampOffset_ = true;
  49793. } // override settings for metadata only segments
  49794. segmentInfo.timingInfo = {
  49795. start: 0
  49796. };
  49797. segmentInfo.waitingOnAppends++;
  49798. if (!this.isPendingTimestampOffset_) {
  49799. // update the timestampoffset
  49800. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  49801. // no video/audio data.
  49802. this.processMetadataQueue_();
  49803. } // append is "done" instantly with no data.
  49804. this.checkAppendsDone_(segmentInfo);
  49805. return;
  49806. } // Since source updater could call back synchronously, do the increments first.
  49807. if (waitForVideo) {
  49808. segmentInfo.waitingOnAppends++;
  49809. }
  49810. if (waitForAudio) {
  49811. segmentInfo.waitingOnAppends++;
  49812. }
  49813. if (waitForVideo) {
  49814. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  49815. }
  49816. if (waitForAudio) {
  49817. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  49818. }
  49819. }
  49820. checkAppendsDone_(segmentInfo) {
  49821. if (this.checkForAbort_(segmentInfo.requestId)) {
  49822. return;
  49823. }
  49824. segmentInfo.waitingOnAppends--;
  49825. if (segmentInfo.waitingOnAppends === 0) {
  49826. this.handleAppendsDone_();
  49827. }
  49828. }
  49829. checkForIllegalMediaSwitch(trackInfo) {
  49830. const illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  49831. if (illegalMediaSwitchError) {
  49832. this.error({
  49833. message: illegalMediaSwitchError,
  49834. playlistExclusionDuration: Infinity
  49835. });
  49836. this.trigger('error');
  49837. return true;
  49838. }
  49839. return false;
  49840. }
  49841. updateSourceBufferTimestampOffset_(segmentInfo) {
  49842. if (segmentInfo.timestampOffset === null ||
  49843. // we don't yet have the start for whatever media type (video or audio) has
  49844. // priority, timing-wise, so we must wait
  49845. typeof segmentInfo.timingInfo.start !== 'number' ||
  49846. // already updated the timestamp offset for this segment
  49847. segmentInfo.changedTimestampOffset ||
  49848. // the alt audio loader should not be responsible for setting the timestamp offset
  49849. this.loaderType_ !== 'main') {
  49850. return;
  49851. }
  49852. let didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  49853. // the timing info here comes from video. In the event that the audio is longer than
  49854. // the video, this will trim the start of the audio.
  49855. // This also trims any offset from 0 at the beginning of the media
  49856. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  49857. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  49858. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  49859. timingInfo: segmentInfo.timingInfo
  49860. }); // In the event that there are part segment downloads, each will try to update the
  49861. // timestamp offset. Retaining this bit of state prevents us from updating in the
  49862. // future (within the same segment), however, there may be a better way to handle it.
  49863. segmentInfo.changedTimestampOffset = true;
  49864. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  49865. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  49866. didChange = true;
  49867. }
  49868. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  49869. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  49870. didChange = true;
  49871. }
  49872. if (didChange) {
  49873. this.trigger('timestampoffset');
  49874. }
  49875. }
  49876. getSegmentStartTimeForTimestampOffsetCalculation_({
  49877. videoTimingInfo,
  49878. audioTimingInfo,
  49879. timingInfo
  49880. }) {
  49881. if (!this.useDtsForTimestampOffset_) {
  49882. return timingInfo.start;
  49883. }
  49884. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  49885. return videoTimingInfo.transmuxedDecodeStart;
  49886. } // handle audio only
  49887. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  49888. return audioTimingInfo.transmuxedDecodeStart;
  49889. } // handle content not transmuxed (e.g., MP4)
  49890. return timingInfo.start;
  49891. }
  49892. updateTimingInfoEnd_(segmentInfo) {
  49893. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  49894. const trackInfo = this.getMediaInfo_();
  49895. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  49896. const prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  49897. if (!prioritizedTimingInfo) {
  49898. return;
  49899. }
  49900. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ?
  49901. // End time may not exist in a case where we aren't parsing the full segment (one
  49902. // current example is the case of fmp4), so use the rough duration to calculate an
  49903. // end time.
  49904. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  49905. }
  49906. /**
  49907. * callback to run when appendBuffer is finished. detects if we are
  49908. * in a good state to do things with the data we got, or if we need
  49909. * to wait for more
  49910. *
  49911. * @private
  49912. */
  49913. handleAppendsDone_() {
  49914. // appendsdone can cause an abort
  49915. if (this.pendingSegment_) {
  49916. this.trigger('appendsdone');
  49917. }
  49918. if (!this.pendingSegment_) {
  49919. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  49920. // all appending cases?
  49921. if (!this.paused()) {
  49922. this.monitorBuffer_();
  49923. }
  49924. return;
  49925. }
  49926. const segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  49927. // best to wait until all appends are done so we're sure that the primary media is
  49928. // finished (and we have its end time).
  49929. this.updateTimingInfoEnd_(segmentInfo);
  49930. if (this.shouldSaveSegmentTimingInfo_) {
  49931. // Timeline mappings should only be saved for the main loader. This is for multiple
  49932. // reasons:
  49933. //
  49934. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  49935. // and the main loader try to save the timeline mapping, whichever comes later
  49936. // will overwrite the first. In theory this is OK, as the mappings should be the
  49937. // same, however, it breaks for (2)
  49938. // 2) In the event of a live stream, the initial live point will make for a somewhat
  49939. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  49940. // the mapping will be off for one of the streams, dependent on which one was
  49941. // first saved (see (1)).
  49942. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  49943. //
  49944. // Since the audio loader will wait for the main loader to load the first segment,
  49945. // the main loader will save the first timeline mapping, and ensure that there won't
  49946. // be a case where audio loads two segments without saving a mapping (thus leading
  49947. // to missing segment timing info).
  49948. this.syncController_.saveSegmentTimingInfo({
  49949. segmentInfo,
  49950. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  49951. });
  49952. }
  49953. const segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  49954. if (segmentDurationMessage) {
  49955. if (segmentDurationMessage.severity === 'warn') {
  49956. videojs.log.warn(segmentDurationMessage.message);
  49957. } else {
  49958. this.logger_(segmentDurationMessage.message);
  49959. }
  49960. }
  49961. this.recordThroughput_(segmentInfo);
  49962. this.pendingSegment_ = null;
  49963. this.state = 'READY';
  49964. if (segmentInfo.isSyncRequest) {
  49965. this.trigger('syncinfoupdate'); // if the sync request was not appended
  49966. // then it was not the correct segment.
  49967. // throw it away and use the data it gave us
  49968. // to get the correct one.
  49969. if (!segmentInfo.hasAppendedData_) {
  49970. this.logger_(`Throwing away un-appended sync request ${segmentInfoString(segmentInfo)}`);
  49971. return;
  49972. }
  49973. }
  49974. this.logger_(`Appended ${segmentInfoString(segmentInfo)}`);
  49975. this.addSegmentMetadataCue_(segmentInfo);
  49976. this.fetchAtBuffer_ = true;
  49977. if (this.currentTimeline_ !== segmentInfo.timeline) {
  49978. this.timelineChangeController_.lastTimelineChange({
  49979. type: this.loaderType_,
  49980. from: this.currentTimeline_,
  49981. to: segmentInfo.timeline
  49982. }); // If audio is not disabled, the main segment loader is responsible for updating
  49983. // the audio timeline as well. If the content is video only, this won't have any
  49984. // impact.
  49985. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  49986. this.timelineChangeController_.lastTimelineChange({
  49987. type: 'audio',
  49988. from: this.currentTimeline_,
  49989. to: segmentInfo.timeline
  49990. });
  49991. }
  49992. }
  49993. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  49994. // the following conditional otherwise it may consider this a bad "guess"
  49995. // and attempt to resync when the post-update seekable window and live
  49996. // point would mean that this was the perfect segment to fetch
  49997. this.trigger('syncinfoupdate');
  49998. const segment = segmentInfo.segment;
  49999. const part = segmentInfo.part;
  50000. const badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  50001. 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
  50002. // the currentTime_ that means that our conservative guess was too conservative.
  50003. // In that case, reset the loader state so that we try to use any information gained
  50004. // from the previous request to create a new, more accurate, sync-point.
  50005. if (badSegmentGuess || badPartGuess) {
  50006. this.logger_(`bad ${badSegmentGuess ? 'segment' : 'part'} ${segmentInfoString(segmentInfo)}`);
  50007. this.resetEverything();
  50008. return;
  50009. }
  50010. const isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  50011. // and conservatively guess
  50012. if (isWalkingForward) {
  50013. this.trigger('bandwidthupdate');
  50014. }
  50015. this.trigger('progress');
  50016. this.mediaIndex = segmentInfo.mediaIndex;
  50017. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  50018. // buffer, end the stream. this ensures the "ended" event will
  50019. // fire if playback reaches that point.
  50020. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  50021. this.endOfStream();
  50022. } // used for testing
  50023. this.trigger('appended');
  50024. if (segmentInfo.hasAppendedData_) {
  50025. this.mediaAppends++;
  50026. }
  50027. if (!this.paused()) {
  50028. this.monitorBuffer_();
  50029. }
  50030. }
  50031. /**
  50032. * Records the current throughput of the decrypt, transmux, and append
  50033. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  50034. * moving average of the throughput. `throughput.count` is the number of
  50035. * data points in the average.
  50036. *
  50037. * @private
  50038. * @param {Object} segmentInfo the object returned by loadSegment
  50039. */
  50040. recordThroughput_(segmentInfo) {
  50041. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  50042. 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}`);
  50043. return;
  50044. }
  50045. const rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  50046. // by zero in the case where the throughput is ridiculously high
  50047. const segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  50048. const segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  50049. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  50050. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  50051. }
  50052. /**
  50053. * Adds a cue to the segment-metadata track with some metadata information about the
  50054. * segment
  50055. *
  50056. * @private
  50057. * @param {Object} segmentInfo
  50058. * the object returned by loadSegment
  50059. * @method addSegmentMetadataCue_
  50060. */
  50061. addSegmentMetadataCue_(segmentInfo) {
  50062. if (!this.segmentMetadataTrack_) {
  50063. return;
  50064. }
  50065. const segment = segmentInfo.segment;
  50066. const start = segment.start;
  50067. const end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  50068. if (!finite(start) || !finite(end)) {
  50069. return;
  50070. }
  50071. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  50072. const Cue = window.WebKitDataCue || window.VTTCue;
  50073. const value = {
  50074. custom: segment.custom,
  50075. dateTimeObject: segment.dateTimeObject,
  50076. dateTimeString: segment.dateTimeString,
  50077. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  50078. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  50079. codecs: segmentInfo.playlist.attributes.CODECS,
  50080. byteLength: segmentInfo.byteLength,
  50081. uri: segmentInfo.uri,
  50082. timeline: segmentInfo.timeline,
  50083. playlist: segmentInfo.playlist.id,
  50084. start,
  50085. end
  50086. };
  50087. const data = JSON.stringify(value);
  50088. const cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  50089. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  50090. cue.value = value;
  50091. this.segmentMetadataTrack_.addCue(cue);
  50092. }
  50093. }
  50094. function noop() {}
  50095. const toTitleCase = function (string) {
  50096. if (typeof string !== 'string') {
  50097. return string;
  50098. }
  50099. return string.replace(/./, w => w.toUpperCase());
  50100. };
  50101. /**
  50102. * @file source-updater.js
  50103. */
  50104. const bufferTypes = ['video', 'audio'];
  50105. const updating = (type, sourceUpdater) => {
  50106. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  50107. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  50108. };
  50109. const nextQueueIndexOfType = (type, queue) => {
  50110. for (let i = 0; i < queue.length; i++) {
  50111. const queueEntry = queue[i];
  50112. if (queueEntry.type === 'mediaSource') {
  50113. // If the next entry is a media source entry (uses multiple source buffers), block
  50114. // processing to allow it to go through first.
  50115. return null;
  50116. }
  50117. if (queueEntry.type === type) {
  50118. return i;
  50119. }
  50120. }
  50121. return null;
  50122. };
  50123. const shiftQueue = (type, sourceUpdater) => {
  50124. if (sourceUpdater.queue.length === 0) {
  50125. return;
  50126. }
  50127. let queueIndex = 0;
  50128. let queueEntry = sourceUpdater.queue[queueIndex];
  50129. if (queueEntry.type === 'mediaSource') {
  50130. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  50131. sourceUpdater.queue.shift();
  50132. queueEntry.action(sourceUpdater);
  50133. if (queueEntry.doneFn) {
  50134. queueEntry.doneFn();
  50135. } // Only specific source buffer actions must wait for async updateend events. Media
  50136. // Source actions process synchronously. Therefore, both audio and video source
  50137. // buffers are now clear to process the next queue entries.
  50138. shiftQueue('audio', sourceUpdater);
  50139. shiftQueue('video', sourceUpdater);
  50140. } // Media Source actions require both source buffers, so if the media source action
  50141. // couldn't process yet (because one or both source buffers are busy), block other
  50142. // queue actions until both are available and the media source action can process.
  50143. return;
  50144. }
  50145. if (type === 'mediaSource') {
  50146. // If the queue was shifted by a media source action (this happens when pushing a
  50147. // media source action onto the queue), then it wasn't from an updateend event from an
  50148. // audio or video source buffer, so there's no change from previous state, and no
  50149. // processing should be done.
  50150. return;
  50151. } // Media source queue entries don't need to consider whether the source updater is
  50152. // started (i.e., source buffers are created) as they don't need the source buffers, but
  50153. // source buffer queue entries do.
  50154. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || updating(type, sourceUpdater)) {
  50155. return;
  50156. }
  50157. if (queueEntry.type !== type) {
  50158. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  50159. if (queueIndex === null) {
  50160. // Either there's no queue entry that uses this source buffer type in the queue, or
  50161. // there's a media source queue entry before the next entry of this type, in which
  50162. // case wait for that action to process first.
  50163. return;
  50164. }
  50165. queueEntry = sourceUpdater.queue[queueIndex];
  50166. }
  50167. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  50168. //
  50169. // The queue pending operation must be set before the action is performed in the event
  50170. // that the action results in a synchronous event that is acted upon. For instance, if
  50171. // an exception is thrown that can be handled, it's possible that new actions will be
  50172. // appended to an empty queue and immediately executed, but would not have the correct
  50173. // pending information if this property was set after the action was performed.
  50174. sourceUpdater.queuePending[type] = queueEntry;
  50175. queueEntry.action(type, sourceUpdater);
  50176. if (!queueEntry.doneFn) {
  50177. // synchronous operation, process next entry
  50178. sourceUpdater.queuePending[type] = null;
  50179. shiftQueue(type, sourceUpdater);
  50180. return;
  50181. }
  50182. };
  50183. const cleanupBuffer = (type, sourceUpdater) => {
  50184. const buffer = sourceUpdater[`${type}Buffer`];
  50185. const titleType = toTitleCase(type);
  50186. if (!buffer) {
  50187. return;
  50188. }
  50189. buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  50190. buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  50191. sourceUpdater.codecs[type] = null;
  50192. sourceUpdater[`${type}Buffer`] = null;
  50193. };
  50194. const inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  50195. const actions = {
  50196. appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {
  50197. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  50198. // or the media source does not contain this source buffer.
  50199. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  50200. return;
  50201. }
  50202. sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);
  50203. try {
  50204. sourceBuffer.appendBuffer(bytes);
  50205. } catch (e) {
  50206. sourceUpdater.logger_(`Error with code ${e.code} ` + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);
  50207. sourceUpdater.queuePending[type] = null;
  50208. onError(e);
  50209. }
  50210. },
  50211. remove: (start, end) => (type, sourceUpdater) => {
  50212. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  50213. // or the media source does not contain this source buffer.
  50214. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  50215. return;
  50216. }
  50217. sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);
  50218. try {
  50219. sourceBuffer.remove(start, end);
  50220. } catch (e) {
  50221. sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);
  50222. }
  50223. },
  50224. timestampOffset: offset => (type, sourceUpdater) => {
  50225. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  50226. // or the media source does not contain this source buffer.
  50227. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  50228. return;
  50229. }
  50230. sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);
  50231. sourceBuffer.timestampOffset = offset;
  50232. },
  50233. callback: callback => (type, sourceUpdater) => {
  50234. callback();
  50235. },
  50236. endOfStream: error => sourceUpdater => {
  50237. if (sourceUpdater.mediaSource.readyState !== 'open') {
  50238. return;
  50239. }
  50240. sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);
  50241. try {
  50242. sourceUpdater.mediaSource.endOfStream(error);
  50243. } catch (e) {
  50244. videojs.log.warn('Failed to call media source endOfStream', e);
  50245. }
  50246. },
  50247. duration: duration => sourceUpdater => {
  50248. sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);
  50249. try {
  50250. sourceUpdater.mediaSource.duration = duration;
  50251. } catch (e) {
  50252. videojs.log.warn('Failed to set media source duration', e);
  50253. }
  50254. },
  50255. abort: () => (type, sourceUpdater) => {
  50256. if (sourceUpdater.mediaSource.readyState !== 'open') {
  50257. return;
  50258. }
  50259. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  50260. // or the media source does not contain this source buffer.
  50261. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  50262. return;
  50263. }
  50264. sourceUpdater.logger_(`calling abort on ${type}Buffer`);
  50265. try {
  50266. sourceBuffer.abort();
  50267. } catch (e) {
  50268. videojs.log.warn(`Failed to abort on ${type}Buffer`, e);
  50269. }
  50270. },
  50271. addSourceBuffer: (type, codec) => sourceUpdater => {
  50272. const titleType = toTitleCase(type);
  50273. const mime = getMimeForCodec(codec);
  50274. sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);
  50275. const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  50276. sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  50277. sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  50278. sourceUpdater.codecs[type] = codec;
  50279. sourceUpdater[`${type}Buffer`] = sourceBuffer;
  50280. },
  50281. removeSourceBuffer: type => sourceUpdater => {
  50282. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  50283. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  50284. // or the media source does not contain this source buffer.
  50285. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  50286. return;
  50287. }
  50288. sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);
  50289. try {
  50290. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  50291. } catch (e) {
  50292. videojs.log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);
  50293. }
  50294. },
  50295. changeType: codec => (type, sourceUpdater) => {
  50296. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  50297. const mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  50298. // or the media source does not contain this source buffer.
  50299. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  50300. return;
  50301. } // do not update codec if we don't need to.
  50302. if (sourceUpdater.codecs[type] === codec) {
  50303. return;
  50304. }
  50305. sourceUpdater.logger_(`changing ${type}Buffer codec from ${sourceUpdater.codecs[type]} to ${codec}`);
  50306. sourceBuffer.changeType(mime);
  50307. sourceUpdater.codecs[type] = codec;
  50308. }
  50309. };
  50310. const pushQueue = ({
  50311. type,
  50312. sourceUpdater,
  50313. action,
  50314. doneFn,
  50315. name
  50316. }) => {
  50317. sourceUpdater.queue.push({
  50318. type,
  50319. action,
  50320. doneFn,
  50321. name
  50322. });
  50323. shiftQueue(type, sourceUpdater);
  50324. };
  50325. const onUpdateend = (type, sourceUpdater) => e => {
  50326. // Although there should, in theory, be a pending action for any updateend receieved,
  50327. // there are some actions that may trigger updateend events without set definitions in
  50328. // the w3c spec. For instance, setting the duration on the media source may trigger
  50329. // updateend events on source buffers. This does not appear to be in the spec. As such,
  50330. // if we encounter an updateend without a corresponding pending action from our queue
  50331. // for that source buffer type, process the next action.
  50332. if (sourceUpdater.queuePending[type]) {
  50333. const doneFn = sourceUpdater.queuePending[type].doneFn;
  50334. sourceUpdater.queuePending[type] = null;
  50335. if (doneFn) {
  50336. // if there's an error, report it
  50337. doneFn(sourceUpdater[`${type}Error_`]);
  50338. }
  50339. }
  50340. shiftQueue(type, sourceUpdater);
  50341. };
  50342. /**
  50343. * A queue of callbacks to be serialized and applied when a
  50344. * MediaSource and its associated SourceBuffers are not in the
  50345. * updating state. It is used by the segment loader to update the
  50346. * underlying SourceBuffers when new data is loaded, for instance.
  50347. *
  50348. * @class SourceUpdater
  50349. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  50350. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  50351. */
  50352. class SourceUpdater extends videojs.EventTarget {
  50353. constructor(mediaSource) {
  50354. super();
  50355. this.mediaSource = mediaSource;
  50356. this.sourceopenListener_ = () => shiftQueue('mediaSource', this);
  50357. this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);
  50358. this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  50359. this.audioTimestampOffset_ = 0;
  50360. this.videoTimestampOffset_ = 0;
  50361. this.queue = [];
  50362. this.queuePending = {
  50363. audio: null,
  50364. video: null
  50365. };
  50366. this.delayedAudioAppendQueue_ = [];
  50367. this.videoAppendQueued_ = false;
  50368. this.codecs = {};
  50369. this.onVideoUpdateEnd_ = onUpdateend('video', this);
  50370. this.onAudioUpdateEnd_ = onUpdateend('audio', this);
  50371. this.onVideoError_ = e => {
  50372. // used for debugging
  50373. this.videoError_ = e;
  50374. };
  50375. this.onAudioError_ = e => {
  50376. // used for debugging
  50377. this.audioError_ = e;
  50378. };
  50379. this.createdSourceBuffers_ = false;
  50380. this.initializedEme_ = false;
  50381. this.triggeredReady_ = false;
  50382. }
  50383. initializedEme() {
  50384. this.initializedEme_ = true;
  50385. this.triggerReady();
  50386. }
  50387. hasCreatedSourceBuffers() {
  50388. // if false, likely waiting on one of the segment loaders to get enough data to create
  50389. // source buffers
  50390. return this.createdSourceBuffers_;
  50391. }
  50392. hasInitializedAnyEme() {
  50393. return this.initializedEme_;
  50394. }
  50395. ready() {
  50396. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  50397. }
  50398. createSourceBuffers(codecs) {
  50399. if (this.hasCreatedSourceBuffers()) {
  50400. // already created them before
  50401. return;
  50402. } // the intial addOrChangeSourceBuffers will always be
  50403. // two add buffers.
  50404. this.addOrChangeSourceBuffers(codecs);
  50405. this.createdSourceBuffers_ = true;
  50406. this.trigger('createdsourcebuffers');
  50407. this.triggerReady();
  50408. }
  50409. triggerReady() {
  50410. // only allow ready to be triggered once, this prevents the case
  50411. // where:
  50412. // 1. we trigger createdsourcebuffers
  50413. // 2. ie 11 synchronously initializates eme
  50414. // 3. the synchronous initialization causes us to trigger ready
  50415. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  50416. if (this.ready() && !this.triggeredReady_) {
  50417. this.triggeredReady_ = true;
  50418. this.trigger('ready');
  50419. }
  50420. }
  50421. /**
  50422. * Add a type of source buffer to the media source.
  50423. *
  50424. * @param {string} type
  50425. * The type of source buffer to add.
  50426. *
  50427. * @param {string} codec
  50428. * The codec to add the source buffer with.
  50429. */
  50430. addSourceBuffer(type, codec) {
  50431. pushQueue({
  50432. type: 'mediaSource',
  50433. sourceUpdater: this,
  50434. action: actions.addSourceBuffer(type, codec),
  50435. name: 'addSourceBuffer'
  50436. });
  50437. }
  50438. /**
  50439. * call abort on a source buffer.
  50440. *
  50441. * @param {string} type
  50442. * The type of source buffer to call abort on.
  50443. */
  50444. abort(type) {
  50445. pushQueue({
  50446. type,
  50447. sourceUpdater: this,
  50448. action: actions.abort(type),
  50449. name: 'abort'
  50450. });
  50451. }
  50452. /**
  50453. * Call removeSourceBuffer and remove a specific type
  50454. * of source buffer on the mediaSource.
  50455. *
  50456. * @param {string} type
  50457. * The type of source buffer to remove.
  50458. */
  50459. removeSourceBuffer(type) {
  50460. if (!this.canRemoveSourceBuffer()) {
  50461. videojs.log.error('removeSourceBuffer is not supported!');
  50462. return;
  50463. }
  50464. pushQueue({
  50465. type: 'mediaSource',
  50466. sourceUpdater: this,
  50467. action: actions.removeSourceBuffer(type),
  50468. name: 'removeSourceBuffer'
  50469. });
  50470. }
  50471. /**
  50472. * Whether or not the removeSourceBuffer function is supported
  50473. * on the mediaSource.
  50474. *
  50475. * @return {boolean}
  50476. * if removeSourceBuffer can be called.
  50477. */
  50478. canRemoveSourceBuffer() {
  50479. // IE reports that it supports removeSourceBuffer, but often throws
  50480. // errors when attempting to use the function. So we report that it
  50481. // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
  50482. // throws errors, so we report that it does not support this as well.
  50483. return !videojs.browser.IE_VERSION && !videojs.browser.IS_FIREFOX && window.MediaSource && window.MediaSource.prototype && typeof window.MediaSource.prototype.removeSourceBuffer === 'function';
  50484. }
  50485. /**
  50486. * Whether or not the changeType function is supported
  50487. * on our SourceBuffers.
  50488. *
  50489. * @return {boolean}
  50490. * if changeType can be called.
  50491. */
  50492. static canChangeType() {
  50493. return window.SourceBuffer && window.SourceBuffer.prototype && typeof window.SourceBuffer.prototype.changeType === 'function';
  50494. }
  50495. /**
  50496. * Whether or not the changeType function is supported
  50497. * on our SourceBuffers.
  50498. *
  50499. * @return {boolean}
  50500. * if changeType can be called.
  50501. */
  50502. canChangeType() {
  50503. return this.constructor.canChangeType();
  50504. }
  50505. /**
  50506. * Call the changeType function on a source buffer, given the code and type.
  50507. *
  50508. * @param {string} type
  50509. * The type of source buffer to call changeType on.
  50510. *
  50511. * @param {string} codec
  50512. * The codec string to change type with on the source buffer.
  50513. */
  50514. changeType(type, codec) {
  50515. if (!this.canChangeType()) {
  50516. videojs.log.error('changeType is not supported!');
  50517. return;
  50518. }
  50519. pushQueue({
  50520. type,
  50521. sourceUpdater: this,
  50522. action: actions.changeType(codec),
  50523. name: 'changeType'
  50524. });
  50525. }
  50526. /**
  50527. * Add source buffers with a codec or, if they are already created,
  50528. * call changeType on source buffers using changeType.
  50529. *
  50530. * @param {Object} codecs
  50531. * Codecs to switch to
  50532. */
  50533. addOrChangeSourceBuffers(codecs) {
  50534. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  50535. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  50536. }
  50537. Object.keys(codecs).forEach(type => {
  50538. const codec = codecs[type];
  50539. if (!this.hasCreatedSourceBuffers()) {
  50540. return this.addSourceBuffer(type, codec);
  50541. }
  50542. if (this.canChangeType()) {
  50543. this.changeType(type, codec);
  50544. }
  50545. });
  50546. }
  50547. /**
  50548. * Queue an update to append an ArrayBuffer.
  50549. *
  50550. * @param {MediaObject} object containing audioBytes and/or videoBytes
  50551. * @param {Function} done the function to call when done
  50552. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  50553. */
  50554. appendBuffer(options, doneFn) {
  50555. const {
  50556. segmentInfo,
  50557. type,
  50558. bytes
  50559. } = options;
  50560. this.processedAppend_ = true;
  50561. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  50562. this.delayedAudioAppendQueue_.push([options, doneFn]);
  50563. this.logger_(`delayed audio append of ${bytes.length} until video append`);
  50564. return;
  50565. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  50566. // not be fired. This means that the queue will be blocked until the next action
  50567. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  50568. // these errors by calling the doneFn with the specific error.
  50569. const onError = doneFn;
  50570. pushQueue({
  50571. type,
  50572. sourceUpdater: this,
  50573. action: actions.appendBuffer(bytes, segmentInfo || {
  50574. mediaIndex: -1
  50575. }, onError),
  50576. doneFn,
  50577. name: 'appendBuffer'
  50578. });
  50579. if (type === 'video') {
  50580. this.videoAppendQueued_ = true;
  50581. if (!this.delayedAudioAppendQueue_.length) {
  50582. return;
  50583. }
  50584. const queue = this.delayedAudioAppendQueue_.slice();
  50585. this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);
  50586. this.delayedAudioAppendQueue_.length = 0;
  50587. queue.forEach(que => {
  50588. this.appendBuffer.apply(this, que);
  50589. });
  50590. }
  50591. }
  50592. /**
  50593. * Get the audio buffer's buffered timerange.
  50594. *
  50595. * @return {TimeRange}
  50596. * The audio buffer's buffered time range
  50597. */
  50598. audioBuffered() {
  50599. // no media source/source buffer or it isn't in the media sources
  50600. // source buffer list
  50601. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  50602. return createTimeRanges();
  50603. }
  50604. return this.audioBuffer.buffered ? this.audioBuffer.buffered : createTimeRanges();
  50605. }
  50606. /**
  50607. * Get the video buffer's buffered timerange.
  50608. *
  50609. * @return {TimeRange}
  50610. * The video buffer's buffered time range
  50611. */
  50612. videoBuffered() {
  50613. // no media source/source buffer or it isn't in the media sources
  50614. // source buffer list
  50615. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  50616. return createTimeRanges();
  50617. }
  50618. return this.videoBuffer.buffered ? this.videoBuffer.buffered : createTimeRanges();
  50619. }
  50620. /**
  50621. * Get a combined video/audio buffer's buffered timerange.
  50622. *
  50623. * @return {TimeRange}
  50624. * the combined time range
  50625. */
  50626. buffered() {
  50627. const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  50628. const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  50629. if (audio && !video) {
  50630. return this.audioBuffered();
  50631. }
  50632. if (video && !audio) {
  50633. return this.videoBuffered();
  50634. }
  50635. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  50636. }
  50637. /**
  50638. * Add a callback to the queue that will set duration on the mediaSource.
  50639. *
  50640. * @param {number} duration
  50641. * The duration to set
  50642. *
  50643. * @param {Function} [doneFn]
  50644. * function to run after duration has been set.
  50645. */
  50646. setDuration(duration, doneFn = noop) {
  50647. // In order to set the duration on the media source, it's necessary to wait for all
  50648. // source buffers to no longer be updating. "If the updating attribute equals true on
  50649. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  50650. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  50651. pushQueue({
  50652. type: 'mediaSource',
  50653. sourceUpdater: this,
  50654. action: actions.duration(duration),
  50655. name: 'duration',
  50656. doneFn
  50657. });
  50658. }
  50659. /**
  50660. * Add a mediaSource endOfStream call to the queue
  50661. *
  50662. * @param {Error} [error]
  50663. * Call endOfStream with an error
  50664. *
  50665. * @param {Function} [doneFn]
  50666. * A function that should be called when the
  50667. * endOfStream call has finished.
  50668. */
  50669. endOfStream(error = null, doneFn = noop) {
  50670. if (typeof error !== 'string') {
  50671. error = undefined;
  50672. } // In order to set the duration on the media source, it's necessary to wait for all
  50673. // source buffers to no longer be updating. "If the updating attribute equals true on
  50674. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  50675. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  50676. pushQueue({
  50677. type: 'mediaSource',
  50678. sourceUpdater: this,
  50679. action: actions.endOfStream(error),
  50680. name: 'endOfStream',
  50681. doneFn
  50682. });
  50683. }
  50684. /**
  50685. * Queue an update to remove a time range from the buffer.
  50686. *
  50687. * @param {number} start where to start the removal
  50688. * @param {number} end where to end the removal
  50689. * @param {Function} [done=noop] optional callback to be executed when the remove
  50690. * operation is complete
  50691. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  50692. */
  50693. removeAudio(start, end, done = noop) {
  50694. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  50695. done();
  50696. return;
  50697. }
  50698. pushQueue({
  50699. type: 'audio',
  50700. sourceUpdater: this,
  50701. action: actions.remove(start, end),
  50702. doneFn: done,
  50703. name: 'remove'
  50704. });
  50705. }
  50706. /**
  50707. * Queue an update to remove a time range from the buffer.
  50708. *
  50709. * @param {number} start where to start the removal
  50710. * @param {number} end where to end the removal
  50711. * @param {Function} [done=noop] optional callback to be executed when the remove
  50712. * operation is complete
  50713. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  50714. */
  50715. removeVideo(start, end, done = noop) {
  50716. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  50717. done();
  50718. return;
  50719. }
  50720. pushQueue({
  50721. type: 'video',
  50722. sourceUpdater: this,
  50723. action: actions.remove(start, end),
  50724. doneFn: done,
  50725. name: 'remove'
  50726. });
  50727. }
  50728. /**
  50729. * Whether the underlying sourceBuffer is updating or not
  50730. *
  50731. * @return {boolean} the updating status of the SourceBuffer
  50732. */
  50733. updating() {
  50734. // the audio/video source buffer is updating
  50735. if (updating('audio', this) || updating('video', this)) {
  50736. return true;
  50737. }
  50738. return false;
  50739. }
  50740. /**
  50741. * Set/get the timestampoffset on the audio SourceBuffer
  50742. *
  50743. * @return {number} the timestamp offset
  50744. */
  50745. audioTimestampOffset(offset) {
  50746. if (typeof offset !== 'undefined' && this.audioBuffer &&
  50747. // no point in updating if it's the same
  50748. this.audioTimestampOffset_ !== offset) {
  50749. pushQueue({
  50750. type: 'audio',
  50751. sourceUpdater: this,
  50752. action: actions.timestampOffset(offset),
  50753. name: 'timestampOffset'
  50754. });
  50755. this.audioTimestampOffset_ = offset;
  50756. }
  50757. return this.audioTimestampOffset_;
  50758. }
  50759. /**
  50760. * Set/get the timestampoffset on the video SourceBuffer
  50761. *
  50762. * @return {number} the timestamp offset
  50763. */
  50764. videoTimestampOffset(offset) {
  50765. if (typeof offset !== 'undefined' && this.videoBuffer &&
  50766. // no point in updating if it's the same
  50767. this.videoTimestampOffset !== offset) {
  50768. pushQueue({
  50769. type: 'video',
  50770. sourceUpdater: this,
  50771. action: actions.timestampOffset(offset),
  50772. name: 'timestampOffset'
  50773. });
  50774. this.videoTimestampOffset_ = offset;
  50775. }
  50776. return this.videoTimestampOffset_;
  50777. }
  50778. /**
  50779. * Add a function to the queue that will be called
  50780. * when it is its turn to run in the audio queue.
  50781. *
  50782. * @param {Function} callback
  50783. * The callback to queue.
  50784. */
  50785. audioQueueCallback(callback) {
  50786. if (!this.audioBuffer) {
  50787. return;
  50788. }
  50789. pushQueue({
  50790. type: 'audio',
  50791. sourceUpdater: this,
  50792. action: actions.callback(callback),
  50793. name: 'callback'
  50794. });
  50795. }
  50796. /**
  50797. * Add a function to the queue that will be called
  50798. * when it is its turn to run in the video queue.
  50799. *
  50800. * @param {Function} callback
  50801. * The callback to queue.
  50802. */
  50803. videoQueueCallback(callback) {
  50804. if (!this.videoBuffer) {
  50805. return;
  50806. }
  50807. pushQueue({
  50808. type: 'video',
  50809. sourceUpdater: this,
  50810. action: actions.callback(callback),
  50811. name: 'callback'
  50812. });
  50813. }
  50814. /**
  50815. * dispose of the source updater and the underlying sourceBuffer
  50816. */
  50817. dispose() {
  50818. this.trigger('dispose');
  50819. bufferTypes.forEach(type => {
  50820. this.abort(type);
  50821. if (this.canRemoveSourceBuffer()) {
  50822. this.removeSourceBuffer(type);
  50823. } else {
  50824. this[`${type}QueueCallback`](() => cleanupBuffer(type, this));
  50825. }
  50826. });
  50827. this.videoAppendQueued_ = false;
  50828. this.delayedAudioAppendQueue_.length = 0;
  50829. if (this.sourceopenListener_) {
  50830. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  50831. }
  50832. this.off();
  50833. }
  50834. }
  50835. const uint8ToUtf8 = uintArray => decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  50836. /**
  50837. * @file vtt-segment-loader.js
  50838. */
  50839. const VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(char => char.charCodeAt(0)));
  50840. class NoVttJsError extends Error {
  50841. constructor() {
  50842. super('Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.');
  50843. }
  50844. }
  50845. /**
  50846. * An object that manages segment loading and appending.
  50847. *
  50848. * @class VTTSegmentLoader
  50849. * @param {Object} options required and optional options
  50850. * @extends videojs.EventTarget
  50851. */
  50852. class VTTSegmentLoader extends SegmentLoader {
  50853. constructor(settings, options = {}) {
  50854. super(settings, options); // SegmentLoader requires a MediaSource be specified or it will throw an error;
  50855. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  50856. this.mediaSource_ = null;
  50857. this.subtitlesTrack_ = null;
  50858. this.loaderType_ = 'subtitle';
  50859. this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  50860. this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  50861. // the sync controller leads to improper behavior.
  50862. this.shouldSaveSegmentTimingInfo_ = false;
  50863. }
  50864. createTransmuxer_() {
  50865. // don't need to transmux any subtitles
  50866. return null;
  50867. }
  50868. /**
  50869. * Indicates which time ranges are buffered
  50870. *
  50871. * @return {TimeRange}
  50872. * TimeRange object representing the current buffered ranges
  50873. */
  50874. buffered_() {
  50875. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  50876. return createTimeRanges();
  50877. }
  50878. const cues = this.subtitlesTrack_.cues;
  50879. const start = cues[0].startTime;
  50880. const end = cues[cues.length - 1].startTime;
  50881. return createTimeRanges([[start, end]]);
  50882. }
  50883. /**
  50884. * Gets and sets init segment for the provided map
  50885. *
  50886. * @param {Object} map
  50887. * The map object representing the init segment to get or set
  50888. * @param {boolean=} set
  50889. * If true, the init segment for the provided map should be saved
  50890. * @return {Object}
  50891. * map object for desired init segment
  50892. */
  50893. initSegmentForMap(map, set = false) {
  50894. if (!map) {
  50895. return null;
  50896. }
  50897. const id = initSegmentId(map);
  50898. let storedMap = this.initSegments_[id];
  50899. if (set && !storedMap && map.bytes) {
  50900. // append WebVTT line terminators to the media initialization segment if it exists
  50901. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  50902. // requires two or more WebVTT line terminators between the WebVTT header and the
  50903. // rest of the file
  50904. const combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  50905. const combinedSegment = new Uint8Array(combinedByteLength);
  50906. combinedSegment.set(map.bytes);
  50907. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  50908. this.initSegments_[id] = storedMap = {
  50909. resolvedUri: map.resolvedUri,
  50910. byterange: map.byterange,
  50911. bytes: combinedSegment
  50912. };
  50913. }
  50914. return storedMap || map;
  50915. }
  50916. /**
  50917. * Returns true if all configuration required for loading is present, otherwise false.
  50918. *
  50919. * @return {boolean} True if the all configuration is ready for loading
  50920. * @private
  50921. */
  50922. couldBeginLoading_() {
  50923. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  50924. }
  50925. /**
  50926. * Once all the starting parameters have been specified, begin
  50927. * operation. This method should only be invoked from the INIT
  50928. * state.
  50929. *
  50930. * @private
  50931. */
  50932. init_() {
  50933. this.state = 'READY';
  50934. this.resetEverything();
  50935. return this.monitorBuffer_();
  50936. }
  50937. /**
  50938. * Set a subtitle track on the segment loader to add subtitles to
  50939. *
  50940. * @param {TextTrack=} track
  50941. * The text track to add loaded subtitles to
  50942. * @return {TextTrack}
  50943. * Returns the subtitles track
  50944. */
  50945. track(track) {
  50946. if (typeof track === 'undefined') {
  50947. return this.subtitlesTrack_;
  50948. }
  50949. this.subtitlesTrack_ = track; // if we were unpaused but waiting for a sourceUpdater, start
  50950. // buffering now
  50951. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  50952. this.init_();
  50953. }
  50954. return this.subtitlesTrack_;
  50955. }
  50956. /**
  50957. * Remove any data in the source buffer between start and end times
  50958. *
  50959. * @param {number} start - the start time of the region to remove from the buffer
  50960. * @param {number} end - the end time of the region to remove from the buffer
  50961. */
  50962. remove(start, end) {
  50963. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  50964. }
  50965. /**
  50966. * fill the buffer with segements unless the sourceBuffers are
  50967. * currently updating
  50968. *
  50969. * Note: this function should only ever be called by monitorBuffer_
  50970. * and never directly
  50971. *
  50972. * @private
  50973. */
  50974. fillBuffer_() {
  50975. // see if we need to begin loading immediately
  50976. const segmentInfo = this.chooseNextRequest_();
  50977. if (!segmentInfo) {
  50978. return;
  50979. }
  50980. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  50981. // We don't have the timestamp offset that we need to sync subtitles.
  50982. // Rerun on a timestamp offset or user interaction.
  50983. const checkTimestampOffset = () => {
  50984. this.state = 'READY';
  50985. if (!this.paused()) {
  50986. // if not paused, queue a buffer check as soon as possible
  50987. this.monitorBuffer_();
  50988. }
  50989. };
  50990. this.syncController_.one('timestampoffset', checkTimestampOffset);
  50991. this.state = 'WAITING_ON_TIMELINE';
  50992. return;
  50993. }
  50994. this.loadSegment_(segmentInfo);
  50995. } // never set a timestamp offset for vtt segments.
  50996. timestampOffsetForSegment_() {
  50997. return null;
  50998. }
  50999. chooseNextRequest_() {
  51000. return this.skipEmptySegments_(super.chooseNextRequest_());
  51001. }
  51002. /**
  51003. * Prevents the segment loader from requesting segments we know contain no subtitles
  51004. * by walking forward until we find the next segment that we don't know whether it is
  51005. * empty or not.
  51006. *
  51007. * @param {Object} segmentInfo
  51008. * a segment info object that describes the current segment
  51009. * @return {Object}
  51010. * a segment info object that describes the current segment
  51011. */
  51012. skipEmptySegments_(segmentInfo) {
  51013. while (segmentInfo && segmentInfo.segment.empty) {
  51014. // stop at the last possible segmentInfo
  51015. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  51016. segmentInfo = null;
  51017. break;
  51018. }
  51019. segmentInfo = this.generateSegmentInfo_({
  51020. playlist: segmentInfo.playlist,
  51021. mediaIndex: segmentInfo.mediaIndex + 1,
  51022. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  51023. isSyncRequest: segmentInfo.isSyncRequest
  51024. });
  51025. }
  51026. return segmentInfo;
  51027. }
  51028. stopForError(error) {
  51029. this.error(error);
  51030. this.state = 'READY';
  51031. this.pause();
  51032. this.trigger('error');
  51033. }
  51034. /**
  51035. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  51036. *
  51037. * @private
  51038. */
  51039. segmentRequestFinished_(error, simpleSegment, result) {
  51040. if (!this.subtitlesTrack_) {
  51041. this.state = 'READY';
  51042. return;
  51043. }
  51044. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  51045. if (!this.pendingSegment_) {
  51046. this.state = 'READY';
  51047. this.mediaRequestsAborted += 1;
  51048. return;
  51049. }
  51050. if (error) {
  51051. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  51052. this.handleTimeout_();
  51053. }
  51054. if (error.code === REQUEST_ERRORS.ABORTED) {
  51055. this.mediaRequestsAborted += 1;
  51056. } else {
  51057. this.mediaRequestsErrored += 1;
  51058. }
  51059. this.stopForError(error);
  51060. return;
  51061. }
  51062. const segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  51063. // maintain functionality between segment loaders
  51064. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  51065. if (simpleSegment.key) {
  51066. this.segmentKey(simpleSegment.key, true);
  51067. }
  51068. this.state = 'APPENDING'; // used for tests
  51069. this.trigger('appending');
  51070. const segment = segmentInfo.segment;
  51071. if (segment.map) {
  51072. segment.map.bytes = simpleSegment.map.bytes;
  51073. }
  51074. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  51075. if (typeof window.WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  51076. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  51077. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  51078. this.loadVttJs().then(() => this.segmentRequestFinished_(error, simpleSegment, result), () => this.stopForError({
  51079. message: 'Error loading vtt.js'
  51080. }));
  51081. return;
  51082. }
  51083. segment.requested = true;
  51084. try {
  51085. this.parseVTTCues_(segmentInfo);
  51086. } catch (e) {
  51087. this.stopForError({
  51088. message: e.message
  51089. });
  51090. return;
  51091. }
  51092. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  51093. if (segmentInfo.cues.length) {
  51094. segmentInfo.timingInfo = {
  51095. start: segmentInfo.cues[0].startTime,
  51096. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  51097. };
  51098. } else {
  51099. segmentInfo.timingInfo = {
  51100. start: segmentInfo.startOfSegment,
  51101. end: segmentInfo.startOfSegment + segmentInfo.duration
  51102. };
  51103. }
  51104. if (segmentInfo.isSyncRequest) {
  51105. this.trigger('syncinfoupdate');
  51106. this.pendingSegment_ = null;
  51107. this.state = 'READY';
  51108. return;
  51109. }
  51110. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  51111. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  51112. // the subtitle track
  51113. segmentInfo.cues.forEach(cue => {
  51114. this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_ ? new window.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  51115. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  51116. // cues to have identical time-intervals, but if the text is also identical
  51117. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  51118. // "overlaps" VTT segments)
  51119. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  51120. this.handleAppendsDone_();
  51121. }
  51122. handleData_() {// noop as we shouldn't be getting video/audio data captions
  51123. // that we do not support here.
  51124. }
  51125. updateTimingInfoEnd_() {// noop
  51126. }
  51127. /**
  51128. * Uses the WebVTT parser to parse the segment response
  51129. *
  51130. * @throws NoVttJsError
  51131. *
  51132. * @param {Object} segmentInfo
  51133. * a segment info object that describes the current segment
  51134. * @private
  51135. */
  51136. parseVTTCues_(segmentInfo) {
  51137. let decoder;
  51138. let decodeBytesToString = false;
  51139. if (typeof window.WebVTT !== 'function') {
  51140. // caller is responsible for exception handling.
  51141. throw new NoVttJsError();
  51142. }
  51143. if (typeof window.TextDecoder === 'function') {
  51144. decoder = new window.TextDecoder('utf8');
  51145. } else {
  51146. decoder = window.WebVTT.StringDecoder();
  51147. decodeBytesToString = true;
  51148. }
  51149. const parser = new window.WebVTT.Parser(window, window.vttjs, decoder);
  51150. segmentInfo.cues = [];
  51151. segmentInfo.timestampmap = {
  51152. MPEGTS: 0,
  51153. LOCAL: 0
  51154. };
  51155. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  51156. parser.ontimestampmap = map => {
  51157. segmentInfo.timestampmap = map;
  51158. };
  51159. parser.onparsingerror = error => {
  51160. videojs.log.warn('Error encountered when parsing cues: ' + error.message);
  51161. };
  51162. if (segmentInfo.segment.map) {
  51163. let mapData = segmentInfo.segment.map.bytes;
  51164. if (decodeBytesToString) {
  51165. mapData = uint8ToUtf8(mapData);
  51166. }
  51167. parser.parse(mapData);
  51168. }
  51169. let segmentData = segmentInfo.bytes;
  51170. if (decodeBytesToString) {
  51171. segmentData = uint8ToUtf8(segmentData);
  51172. }
  51173. parser.parse(segmentData);
  51174. parser.flush();
  51175. }
  51176. /**
  51177. * Updates the start and end times of any cues parsed by the WebVTT parser using
  51178. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  51179. * from the SyncController
  51180. *
  51181. * @param {Object} segmentInfo
  51182. * a segment info object that describes the current segment
  51183. * @param {Object} mappingObj
  51184. * object containing a mapping from TS to media time
  51185. * @param {Object} playlist
  51186. * the playlist object containing the segment
  51187. * @private
  51188. */
  51189. updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  51190. const segment = segmentInfo.segment;
  51191. if (!mappingObj) {
  51192. // If the sync controller does not have a mapping of TS to Media Time for the
  51193. // timeline, then we don't have enough information to update the cue
  51194. // start/end times
  51195. return;
  51196. }
  51197. if (!segmentInfo.cues.length) {
  51198. // If there are no cues, we also do not have enough information to figure out
  51199. // segment timing. Mark that the segment contains no cues so we don't re-request
  51200. // an empty segment.
  51201. segment.empty = true;
  51202. return;
  51203. }
  51204. const timestampmap = segmentInfo.timestampmap;
  51205. const diff = timestampmap.MPEGTS / clock_1 - timestampmap.LOCAL + mappingObj.mapping;
  51206. segmentInfo.cues.forEach(cue => {
  51207. // First convert cue time to TS time using the timestamp-map provided within the vtt
  51208. cue.startTime += diff;
  51209. cue.endTime += diff;
  51210. });
  51211. if (!playlist.syncInfo) {
  51212. const firstStart = segmentInfo.cues[0].startTime;
  51213. const lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  51214. playlist.syncInfo = {
  51215. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  51216. time: Math.min(firstStart, lastStart - segment.duration)
  51217. };
  51218. }
  51219. }
  51220. }
  51221. /**
  51222. * @file ad-cue-tags.js
  51223. */
  51224. /**
  51225. * Searches for an ad cue that overlaps with the given mediaTime
  51226. *
  51227. * @param {Object} track
  51228. * the track to find the cue for
  51229. *
  51230. * @param {number} mediaTime
  51231. * the time to find the cue at
  51232. *
  51233. * @return {Object|null}
  51234. * the found cue or null
  51235. */
  51236. const findAdCue = function (track, mediaTime) {
  51237. const cues = track.cues;
  51238. for (let i = 0; i < cues.length; i++) {
  51239. const cue = cues[i];
  51240. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  51241. return cue;
  51242. }
  51243. }
  51244. return null;
  51245. };
  51246. const updateAdCues = function (media, track, offset = 0) {
  51247. if (!media.segments) {
  51248. return;
  51249. }
  51250. let mediaTime = offset;
  51251. let cue;
  51252. for (let i = 0; i < media.segments.length; i++) {
  51253. const segment = media.segments[i];
  51254. if (!cue) {
  51255. // Since the cues will span for at least the segment duration, adding a fudge
  51256. // factor of half segment duration will prevent duplicate cues from being
  51257. // created when timing info is not exact (e.g. cue start time initialized
  51258. // at 10.006677, but next call mediaTime is 10.003332 )
  51259. cue = findAdCue(track, mediaTime + segment.duration / 2);
  51260. }
  51261. if (cue) {
  51262. if ('cueIn' in segment) {
  51263. // Found a CUE-IN so end the cue
  51264. cue.endTime = mediaTime;
  51265. cue.adEndTime = mediaTime;
  51266. mediaTime += segment.duration;
  51267. cue = null;
  51268. continue;
  51269. }
  51270. if (mediaTime < cue.endTime) {
  51271. // Already processed this mediaTime for this cue
  51272. mediaTime += segment.duration;
  51273. continue;
  51274. } // otherwise extend cue until a CUE-IN is found
  51275. cue.endTime += segment.duration;
  51276. } else {
  51277. if ('cueOut' in segment) {
  51278. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  51279. cue.adStartTime = mediaTime; // Assumes tag format to be
  51280. // #EXT-X-CUE-OUT:30
  51281. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  51282. track.addCue(cue);
  51283. }
  51284. if ('cueOutCont' in segment) {
  51285. // Entered into the middle of an ad cue
  51286. // Assumes tag formate to be
  51287. // #EXT-X-CUE-OUT-CONT:10/30
  51288. const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);
  51289. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, '');
  51290. cue.adStartTime = mediaTime - adOffset;
  51291. cue.adEndTime = cue.adStartTime + adTotal;
  51292. track.addCue(cue);
  51293. }
  51294. }
  51295. mediaTime += segment.duration;
  51296. }
  51297. };
  51298. /**
  51299. * @file sync-controller.js
  51300. */
  51301. // synchronize expired playlist segments.
  51302. // the max media sequence diff is 48 hours of live stream
  51303. // content with two second segments. Anything larger than that
  51304. // will likely be invalid.
  51305. const MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  51306. const syncPointStrategies = [
  51307. // Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  51308. // the equivalence display-time 0 === segment-index 0
  51309. {
  51310. name: 'VOD',
  51311. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  51312. if (duration !== Infinity) {
  51313. const syncPoint = {
  51314. time: 0,
  51315. segmentIndex: 0,
  51316. partIndex: null
  51317. };
  51318. return syncPoint;
  51319. }
  51320. return null;
  51321. }
  51322. },
  51323. // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  51324. {
  51325. name: 'ProgramDateTime',
  51326. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  51327. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  51328. return null;
  51329. }
  51330. let syncPoint = null;
  51331. let lastDistance = null;
  51332. const partsAndSegments = getPartsAndSegments(playlist);
  51333. currentTime = currentTime || 0;
  51334. for (let i = 0; i < partsAndSegments.length; i++) {
  51335. // start from the end and loop backwards for live
  51336. // or start from the front and loop forwards for non-live
  51337. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  51338. const partAndSegment = partsAndSegments[index];
  51339. const segment = partAndSegment.segment;
  51340. const datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  51341. if (!datetimeMapping || !segment.dateTimeObject) {
  51342. continue;
  51343. }
  51344. const segmentTime = segment.dateTimeObject.getTime() / 1000;
  51345. let start = segmentTime + datetimeMapping; // take part duration into account.
  51346. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  51347. for (let z = 0; z < partAndSegment.partIndex; z++) {
  51348. start += segment.parts[z].duration;
  51349. }
  51350. }
  51351. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  51352. // currentTime and can stop looking for better candidates
  51353. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  51354. break;
  51355. }
  51356. lastDistance = distance;
  51357. syncPoint = {
  51358. time: start,
  51359. segmentIndex: partAndSegment.segmentIndex,
  51360. partIndex: partAndSegment.partIndex
  51361. };
  51362. }
  51363. return syncPoint;
  51364. }
  51365. },
  51366. // Stategy "Segment": We have a known time mapping for a timeline and a
  51367. // segment in the current timeline with timing data
  51368. {
  51369. name: 'Segment',
  51370. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  51371. let syncPoint = null;
  51372. let lastDistance = null;
  51373. currentTime = currentTime || 0;
  51374. const partsAndSegments = getPartsAndSegments(playlist);
  51375. for (let i = 0; i < partsAndSegments.length; i++) {
  51376. // start from the end and loop backwards for live
  51377. // or start from the front and loop forwards for non-live
  51378. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  51379. const partAndSegment = partsAndSegments[index];
  51380. const segment = partAndSegment.segment;
  51381. const start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  51382. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  51383. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  51384. // currentTime and can stop looking for better candidates
  51385. if (lastDistance !== null && lastDistance < distance) {
  51386. break;
  51387. }
  51388. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  51389. lastDistance = distance;
  51390. syncPoint = {
  51391. time: start,
  51392. segmentIndex: partAndSegment.segmentIndex,
  51393. partIndex: partAndSegment.partIndex
  51394. };
  51395. }
  51396. }
  51397. }
  51398. return syncPoint;
  51399. }
  51400. },
  51401. // Stategy "Discontinuity": We have a discontinuity with a known
  51402. // display-time
  51403. {
  51404. name: 'Discontinuity',
  51405. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  51406. let syncPoint = null;
  51407. currentTime = currentTime || 0;
  51408. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  51409. let lastDistance = null;
  51410. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  51411. const segmentIndex = playlist.discontinuityStarts[i];
  51412. const discontinuity = playlist.discontinuitySequence + i + 1;
  51413. const discontinuitySync = syncController.discontinuities[discontinuity];
  51414. if (discontinuitySync) {
  51415. const distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  51416. // currentTime and can stop looking for better candidates
  51417. if (lastDistance !== null && lastDistance < distance) {
  51418. break;
  51419. }
  51420. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  51421. lastDistance = distance;
  51422. syncPoint = {
  51423. time: discontinuitySync.time,
  51424. segmentIndex,
  51425. partIndex: null
  51426. };
  51427. }
  51428. }
  51429. }
  51430. }
  51431. return syncPoint;
  51432. }
  51433. },
  51434. // Stategy "Playlist": We have a playlist with a known mapping of
  51435. // segment index to display time
  51436. {
  51437. name: 'Playlist',
  51438. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  51439. if (playlist.syncInfo) {
  51440. const syncPoint = {
  51441. time: playlist.syncInfo.time,
  51442. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  51443. partIndex: null
  51444. };
  51445. return syncPoint;
  51446. }
  51447. return null;
  51448. }
  51449. }];
  51450. class SyncController extends videojs.EventTarget {
  51451. constructor(options = {}) {
  51452. super(); // ...for synching across variants
  51453. this.timelines = [];
  51454. this.discontinuities = [];
  51455. this.timelineToDatetimeMappings = {};
  51456. this.logger_ = logger('SyncController');
  51457. }
  51458. /**
  51459. * Find a sync-point for the playlist specified
  51460. *
  51461. * A sync-point is defined as a known mapping from display-time to
  51462. * a segment-index in the current playlist.
  51463. *
  51464. * @param {Playlist} playlist
  51465. * The playlist that needs a sync-point
  51466. * @param {number} duration
  51467. * Duration of the MediaSource (Infinite if playing a live source)
  51468. * @param {number} currentTimeline
  51469. * The last timeline from which a segment was loaded
  51470. * @return {Object}
  51471. * A sync-point object
  51472. */
  51473. getSyncPoint(playlist, duration, currentTimeline, currentTime) {
  51474. const syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
  51475. if (!syncPoints.length) {
  51476. // Signal that we need to attempt to get a sync-point manually
  51477. // by fetching a segment in the playlist and constructing
  51478. // a sync-point from that information
  51479. return null;
  51480. } // Now find the sync-point that is closest to the currentTime because
  51481. // that should result in the most accurate guess about which segment
  51482. // to fetch
  51483. return this.selectSyncPoint_(syncPoints, {
  51484. key: 'time',
  51485. value: currentTime
  51486. });
  51487. }
  51488. /**
  51489. * Calculate the amount of time that has expired off the playlist during playback
  51490. *
  51491. * @param {Playlist} playlist
  51492. * Playlist object to calculate expired from
  51493. * @param {number} duration
  51494. * Duration of the MediaSource (Infinity if playling a live source)
  51495. * @return {number|null}
  51496. * The amount of time that has expired off the playlist during playback. Null
  51497. * if no sync-points for the playlist can be found.
  51498. */
  51499. getExpiredTime(playlist, duration) {
  51500. if (!playlist || !playlist.segments) {
  51501. return null;
  51502. }
  51503. const syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
  51504. if (!syncPoints.length) {
  51505. return null;
  51506. }
  51507. const syncPoint = this.selectSyncPoint_(syncPoints, {
  51508. key: 'segmentIndex',
  51509. value: 0
  51510. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  51511. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  51512. if (syncPoint.segmentIndex > 0) {
  51513. syncPoint.time *= -1;
  51514. }
  51515. return Math.abs(syncPoint.time + sumDurations({
  51516. defaultDuration: playlist.targetDuration,
  51517. durationList: playlist.segments,
  51518. startIndex: syncPoint.segmentIndex,
  51519. endIndex: 0
  51520. }));
  51521. }
  51522. /**
  51523. * Runs each sync-point strategy and returns a list of sync-points returned by the
  51524. * strategies
  51525. *
  51526. * @private
  51527. * @param {Playlist} playlist
  51528. * The playlist that needs a sync-point
  51529. * @param {number} duration
  51530. * Duration of the MediaSource (Infinity if playing a live source)
  51531. * @param {number} currentTimeline
  51532. * The last timeline from which a segment was loaded
  51533. * @return {Array}
  51534. * A list of sync-point objects
  51535. */
  51536. runStrategies_(playlist, duration, currentTimeline, currentTime) {
  51537. const syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  51538. for (let i = 0; i < syncPointStrategies.length; i++) {
  51539. const strategy = syncPointStrategies[i];
  51540. const syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
  51541. if (syncPoint) {
  51542. syncPoint.strategy = strategy.name;
  51543. syncPoints.push({
  51544. strategy: strategy.name,
  51545. syncPoint
  51546. });
  51547. }
  51548. }
  51549. return syncPoints;
  51550. }
  51551. /**
  51552. * Selects the sync-point nearest the specified target
  51553. *
  51554. * @private
  51555. * @param {Array} syncPoints
  51556. * List of sync-points to select from
  51557. * @param {Object} target
  51558. * Object specifying the property and value we are targeting
  51559. * @param {string} target.key
  51560. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  51561. * @param {number} target.value
  51562. * The value to target for the specified key.
  51563. * @return {Object}
  51564. * The sync-point nearest the target
  51565. */
  51566. selectSyncPoint_(syncPoints, target) {
  51567. let bestSyncPoint = syncPoints[0].syncPoint;
  51568. let bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  51569. let bestStrategy = syncPoints[0].strategy;
  51570. for (let i = 1; i < syncPoints.length; i++) {
  51571. const newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  51572. if (newDistance < bestDistance) {
  51573. bestDistance = newDistance;
  51574. bestSyncPoint = syncPoints[i].syncPoint;
  51575. bestStrategy = syncPoints[i].strategy;
  51576. }
  51577. }
  51578. 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}` : '') + ']');
  51579. return bestSyncPoint;
  51580. }
  51581. /**
  51582. * Save any meta-data present on the segments when segments leave
  51583. * the live window to the playlist to allow for synchronization at the
  51584. * playlist level later.
  51585. *
  51586. * @param {Playlist} oldPlaylist - The previous active playlist
  51587. * @param {Playlist} newPlaylist - The updated and most current playlist
  51588. */
  51589. saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  51590. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  51591. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  51592. videojs.log.warn(`Not saving expired segment info. Media sequence gap ${mediaSequenceDiff} is too large.`);
  51593. return;
  51594. } // When a segment expires from the playlist and it has a start time
  51595. // save that information as a possible sync-point reference in future
  51596. for (let i = mediaSequenceDiff - 1; i >= 0; i--) {
  51597. const lastRemovedSegment = oldPlaylist.segments[i];
  51598. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  51599. newPlaylist.syncInfo = {
  51600. mediaSequence: oldPlaylist.mediaSequence + i,
  51601. time: lastRemovedSegment.start
  51602. };
  51603. this.logger_(`playlist refresh sync: [time:${newPlaylist.syncInfo.time},` + ` mediaSequence: ${newPlaylist.syncInfo.mediaSequence}]`);
  51604. this.trigger('syncinfoupdate');
  51605. break;
  51606. }
  51607. }
  51608. }
  51609. /**
  51610. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  51611. * before segments start to load.
  51612. *
  51613. * @param {Playlist} playlist - The currently active playlist
  51614. */
  51615. setDateTimeMappingForStart(playlist) {
  51616. // It's possible for the playlist to be updated before playback starts, meaning time
  51617. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  51618. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  51619. // unless the mappings are cleared.
  51620. this.timelineToDatetimeMappings = {};
  51621. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  51622. const firstSegment = playlist.segments[0];
  51623. const playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  51624. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  51625. }
  51626. }
  51627. /**
  51628. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  51629. * based on the latest timing information.
  51630. *
  51631. * @param {Object} options
  51632. * Options object
  51633. * @param {SegmentInfo} options.segmentInfo
  51634. * The current active request information
  51635. * @param {boolean} options.shouldSaveTimelineMapping
  51636. * If there's a timeline change, determines if the timeline mapping should be
  51637. * saved for timeline mapping and program date time mappings.
  51638. */
  51639. saveSegmentTimingInfo({
  51640. segmentInfo,
  51641. shouldSaveTimelineMapping
  51642. }) {
  51643. const didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  51644. const segment = segmentInfo.segment;
  51645. if (didCalculateSegmentTimeMapping) {
  51646. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  51647. // now with segment timing information
  51648. if (!segmentInfo.playlist.syncInfo) {
  51649. segmentInfo.playlist.syncInfo = {
  51650. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  51651. time: segment.start
  51652. };
  51653. }
  51654. }
  51655. const dateTime = segment.dateTimeObject;
  51656. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  51657. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  51658. }
  51659. }
  51660. timestampOffsetForTimeline(timeline) {
  51661. if (typeof this.timelines[timeline] === 'undefined') {
  51662. return null;
  51663. }
  51664. return this.timelines[timeline].time;
  51665. }
  51666. mappingForTimeline(timeline) {
  51667. if (typeof this.timelines[timeline] === 'undefined') {
  51668. return null;
  51669. }
  51670. return this.timelines[timeline].mapping;
  51671. }
  51672. /**
  51673. * Use the "media time" for a segment to generate a mapping to "display time" and
  51674. * save that display time to the segment.
  51675. *
  51676. * @private
  51677. * @param {SegmentInfo} segmentInfo
  51678. * The current active request information
  51679. * @param {Object} timingInfo
  51680. * The start and end time of the current segment in "media time"
  51681. * @param {boolean} shouldSaveTimelineMapping
  51682. * If there's a timeline change, determines if the timeline mapping should be
  51683. * saved in timelines.
  51684. * @return {boolean}
  51685. * Returns false if segment time mapping could not be calculated
  51686. */
  51687. calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  51688. // TODO: remove side effects
  51689. const segment = segmentInfo.segment;
  51690. const part = segmentInfo.part;
  51691. let mappingObj = this.timelines[segmentInfo.timeline];
  51692. let start;
  51693. let end;
  51694. if (typeof segmentInfo.timestampOffset === 'number') {
  51695. mappingObj = {
  51696. time: segmentInfo.startOfSegment,
  51697. mapping: segmentInfo.startOfSegment - timingInfo.start
  51698. };
  51699. if (shouldSaveTimelineMapping) {
  51700. this.timelines[segmentInfo.timeline] = mappingObj;
  51701. this.trigger('timestampoffset');
  51702. this.logger_(`time mapping for timeline ${segmentInfo.timeline}: ` + `[time: ${mappingObj.time}] [mapping: ${mappingObj.mapping}]`);
  51703. }
  51704. start = segmentInfo.startOfSegment;
  51705. end = timingInfo.end + mappingObj.mapping;
  51706. } else if (mappingObj) {
  51707. start = timingInfo.start + mappingObj.mapping;
  51708. end = timingInfo.end + mappingObj.mapping;
  51709. } else {
  51710. return false;
  51711. }
  51712. if (part) {
  51713. part.start = start;
  51714. part.end = end;
  51715. } // If we don't have a segment start yet or the start value we got
  51716. // is less than our current segment.start value, save a new start value.
  51717. // We have to do this because parts will have segment timing info saved
  51718. // multiple times and we want segment start to be the earliest part start
  51719. // value for that segment.
  51720. if (!segment.start || start < segment.start) {
  51721. segment.start = start;
  51722. }
  51723. segment.end = end;
  51724. return true;
  51725. }
  51726. /**
  51727. * Each time we have discontinuity in the playlist, attempt to calculate the location
  51728. * in display of the start of the discontinuity and save that. We also save an accuracy
  51729. * value so that we save values with the most accuracy (closest to 0.)
  51730. *
  51731. * @private
  51732. * @param {SegmentInfo} segmentInfo - The current active request information
  51733. */
  51734. saveDiscontinuitySyncInfo_(segmentInfo) {
  51735. const playlist = segmentInfo.playlist;
  51736. const segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  51737. // the start of the range and it's accuracy is 0 (greater accuracy values
  51738. // mean more approximation)
  51739. if (segment.discontinuity) {
  51740. this.discontinuities[segment.timeline] = {
  51741. time: segment.start,
  51742. accuracy: 0
  51743. };
  51744. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  51745. // Search for future discontinuities that we can provide better timing
  51746. // information for and save that information for sync purposes
  51747. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  51748. const segmentIndex = playlist.discontinuityStarts[i];
  51749. const discontinuity = playlist.discontinuitySequence + i + 1;
  51750. const mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  51751. const accuracy = Math.abs(mediaIndexDiff);
  51752. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  51753. let time;
  51754. if (mediaIndexDiff < 0) {
  51755. time = segment.start - sumDurations({
  51756. defaultDuration: playlist.targetDuration,
  51757. durationList: playlist.segments,
  51758. startIndex: segmentInfo.mediaIndex,
  51759. endIndex: segmentIndex
  51760. });
  51761. } else {
  51762. time = segment.end + sumDurations({
  51763. defaultDuration: playlist.targetDuration,
  51764. durationList: playlist.segments,
  51765. startIndex: segmentInfo.mediaIndex + 1,
  51766. endIndex: segmentIndex
  51767. });
  51768. }
  51769. this.discontinuities[discontinuity] = {
  51770. time,
  51771. accuracy
  51772. };
  51773. }
  51774. }
  51775. }
  51776. }
  51777. dispose() {
  51778. this.trigger('dispose');
  51779. this.off();
  51780. }
  51781. }
  51782. /**
  51783. * The TimelineChangeController acts as a source for segment loaders to listen for and
  51784. * keep track of latest and pending timeline changes. This is useful to ensure proper
  51785. * sync, as each loader may need to make a consideration for what timeline the other
  51786. * loader is on before making changes which could impact the other loader's media.
  51787. *
  51788. * @class TimelineChangeController
  51789. * @extends videojs.EventTarget
  51790. */
  51791. class TimelineChangeController extends videojs.EventTarget {
  51792. constructor() {
  51793. super();
  51794. this.pendingTimelineChanges_ = {};
  51795. this.lastTimelineChanges_ = {};
  51796. }
  51797. clearPendingTimelineChange(type) {
  51798. this.pendingTimelineChanges_[type] = null;
  51799. this.trigger('pendingtimelinechange');
  51800. }
  51801. pendingTimelineChange({
  51802. type,
  51803. from,
  51804. to
  51805. }) {
  51806. if (typeof from === 'number' && typeof to === 'number') {
  51807. this.pendingTimelineChanges_[type] = {
  51808. type,
  51809. from,
  51810. to
  51811. };
  51812. this.trigger('pendingtimelinechange');
  51813. }
  51814. return this.pendingTimelineChanges_[type];
  51815. }
  51816. lastTimelineChange({
  51817. type,
  51818. from,
  51819. to
  51820. }) {
  51821. if (typeof from === 'number' && typeof to === 'number') {
  51822. this.lastTimelineChanges_[type] = {
  51823. type,
  51824. from,
  51825. to
  51826. };
  51827. delete this.pendingTimelineChanges_[type];
  51828. this.trigger('timelinechange');
  51829. }
  51830. return this.lastTimelineChanges_[type];
  51831. }
  51832. dispose() {
  51833. this.trigger('dispose');
  51834. this.pendingTimelineChanges_ = {};
  51835. this.lastTimelineChanges_ = {};
  51836. this.off();
  51837. }
  51838. }
  51839. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  51840. const workerCode = transform(getWorkerString(function () {
  51841. /**
  51842. * @file stream.js
  51843. */
  51844. /**
  51845. * A lightweight readable stream implemention that handles event dispatching.
  51846. *
  51847. * @class Stream
  51848. */
  51849. var Stream = /*#__PURE__*/function () {
  51850. function Stream() {
  51851. this.listeners = {};
  51852. }
  51853. /**
  51854. * Add a listener for a specified event type.
  51855. *
  51856. * @param {string} type the event name
  51857. * @param {Function} listener the callback to be invoked when an event of
  51858. * the specified type occurs
  51859. */
  51860. var _proto = Stream.prototype;
  51861. _proto.on = function on(type, listener) {
  51862. if (!this.listeners[type]) {
  51863. this.listeners[type] = [];
  51864. }
  51865. this.listeners[type].push(listener);
  51866. }
  51867. /**
  51868. * Remove a listener for a specified event type.
  51869. *
  51870. * @param {string} type the event name
  51871. * @param {Function} listener a function previously registered for this
  51872. * type of event through `on`
  51873. * @return {boolean} if we could turn it off or not
  51874. */;
  51875. _proto.off = function off(type, listener) {
  51876. if (!this.listeners[type]) {
  51877. return false;
  51878. }
  51879. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  51880. // In Video.js we slice listener functions
  51881. // on trigger so that it does not mess up the order
  51882. // while we loop through.
  51883. //
  51884. // Here we slice on off so that the loop in trigger
  51885. // can continue using it's old reference to loop without
  51886. // messing up the order.
  51887. this.listeners[type] = this.listeners[type].slice(0);
  51888. this.listeners[type].splice(index, 1);
  51889. return index > -1;
  51890. }
  51891. /**
  51892. * Trigger an event of the specified type on this stream. Any additional
  51893. * arguments to this function are passed as parameters to event listeners.
  51894. *
  51895. * @param {string} type the event name
  51896. */;
  51897. _proto.trigger = function trigger(type) {
  51898. var callbacks = this.listeners[type];
  51899. if (!callbacks) {
  51900. return;
  51901. } // Slicing the arguments on every invocation of this method
  51902. // can add a significant amount of overhead. Avoid the
  51903. // intermediate object creation for the common case of a
  51904. // single callback argument
  51905. if (arguments.length === 2) {
  51906. var length = callbacks.length;
  51907. for (var i = 0; i < length; ++i) {
  51908. callbacks[i].call(this, arguments[1]);
  51909. }
  51910. } else {
  51911. var args = Array.prototype.slice.call(arguments, 1);
  51912. var _length = callbacks.length;
  51913. for (var _i = 0; _i < _length; ++_i) {
  51914. callbacks[_i].apply(this, args);
  51915. }
  51916. }
  51917. }
  51918. /**
  51919. * Destroys the stream and cleans up.
  51920. */;
  51921. _proto.dispose = function dispose() {
  51922. this.listeners = {};
  51923. }
  51924. /**
  51925. * Forwards all `data` events on this stream to the destination stream. The
  51926. * destination stream should provide a method `push` to receive the data
  51927. * events as they arrive.
  51928. *
  51929. * @param {Stream} destination the stream that will receive all `data` events
  51930. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  51931. */;
  51932. _proto.pipe = function pipe(destination) {
  51933. this.on('data', function (data) {
  51934. destination.push(data);
  51935. });
  51936. };
  51937. return Stream;
  51938. }();
  51939. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  51940. /**
  51941. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  51942. *
  51943. * @param padded {Uint8Array} unencrypted bytes that have been padded
  51944. * @return {Uint8Array} the unpadded bytes
  51945. * @see http://tools.ietf.org/html/rfc5652
  51946. */
  51947. function unpad(padded) {
  51948. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  51949. }
  51950. /*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */
  51951. /**
  51952. * @file aes.js
  51953. *
  51954. * This file contains an adaptation of the AES decryption algorithm
  51955. * from the Standford Javascript Cryptography Library. That work is
  51956. * covered by the following copyright and permissions notice:
  51957. *
  51958. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  51959. * All rights reserved.
  51960. *
  51961. * Redistribution and use in source and binary forms, with or without
  51962. * modification, are permitted provided that the following conditions are
  51963. * met:
  51964. *
  51965. * 1. Redistributions of source code must retain the above copyright
  51966. * notice, this list of conditions and the following disclaimer.
  51967. *
  51968. * 2. Redistributions in binary form must reproduce the above
  51969. * copyright notice, this list of conditions and the following
  51970. * disclaimer in the documentation and/or other materials provided
  51971. * with the distribution.
  51972. *
  51973. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  51974. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  51975. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  51976. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  51977. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  51978. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  51979. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  51980. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  51981. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  51982. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  51983. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  51984. *
  51985. * The views and conclusions contained in the software and documentation
  51986. * are those of the authors and should not be interpreted as representing
  51987. * official policies, either expressed or implied, of the authors.
  51988. */
  51989. /**
  51990. * Expand the S-box tables.
  51991. *
  51992. * @private
  51993. */
  51994. const precompute = function () {
  51995. const tables = [[[], [], [], [], []], [[], [], [], [], []]];
  51996. const encTable = tables[0];
  51997. const decTable = tables[1];
  51998. const sbox = encTable[4];
  51999. const sboxInv = decTable[4];
  52000. let i;
  52001. let x;
  52002. let xInv;
  52003. const d = [];
  52004. const th = [];
  52005. let x2;
  52006. let x4;
  52007. let x8;
  52008. let s;
  52009. let tEnc;
  52010. let tDec; // Compute double and third tables
  52011. for (i = 0; i < 256; i++) {
  52012. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  52013. }
  52014. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  52015. // Compute sbox
  52016. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  52017. s = s >> 8 ^ s & 255 ^ 99;
  52018. sbox[x] = s;
  52019. sboxInv[s] = x; // Compute MixColumns
  52020. x8 = d[x4 = d[x2 = d[x]]];
  52021. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  52022. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  52023. for (i = 0; i < 4; i++) {
  52024. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  52025. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  52026. }
  52027. } // Compactify. Considerable speedup on Firefox.
  52028. for (i = 0; i < 5; i++) {
  52029. encTable[i] = encTable[i].slice(0);
  52030. decTable[i] = decTable[i].slice(0);
  52031. }
  52032. return tables;
  52033. };
  52034. let aesTables = null;
  52035. /**
  52036. * Schedule out an AES key for both encryption and decryption. This
  52037. * is a low-level class. Use a cipher mode to do bulk encryption.
  52038. *
  52039. * @class AES
  52040. * @param key {Array} The key as an array of 4, 6 or 8 words.
  52041. */
  52042. class AES {
  52043. constructor(key) {
  52044. /**
  52045. * The expanded S-box and inverse S-box tables. These will be computed
  52046. * on the client so that we don't have to send them down the wire.
  52047. *
  52048. * There are two tables, _tables[0] is for encryption and
  52049. * _tables[1] is for decryption.
  52050. *
  52051. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  52052. * last (_tables[01][4]) is the S-box itself.
  52053. *
  52054. * @private
  52055. */
  52056. // if we have yet to precompute the S-box tables
  52057. // do so now
  52058. if (!aesTables) {
  52059. aesTables = precompute();
  52060. } // then make a copy of that object for use
  52061. 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()]];
  52062. let i;
  52063. let j;
  52064. let tmp;
  52065. const sbox = this._tables[0][4];
  52066. const decTable = this._tables[1];
  52067. const keyLen = key.length;
  52068. let rcon = 1;
  52069. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  52070. throw new Error('Invalid aes key size');
  52071. }
  52072. const encKey = key.slice(0);
  52073. const decKey = [];
  52074. this._key = [encKey, decKey]; // schedule encryption keys
  52075. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  52076. tmp = encKey[i - 1]; // apply sbox
  52077. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  52078. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  52079. if (i % keyLen === 0) {
  52080. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  52081. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  52082. }
  52083. }
  52084. encKey[i] = encKey[i - keyLen] ^ tmp;
  52085. } // schedule decryption keys
  52086. for (j = 0; i; j++, i--) {
  52087. tmp = encKey[j & 3 ? i : i - 4];
  52088. if (i <= 4 || j < 4) {
  52089. decKey[j] = tmp;
  52090. } else {
  52091. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  52092. }
  52093. }
  52094. }
  52095. /**
  52096. * Decrypt 16 bytes, specified as four 32-bit words.
  52097. *
  52098. * @param {number} encrypted0 the first word to decrypt
  52099. * @param {number} encrypted1 the second word to decrypt
  52100. * @param {number} encrypted2 the third word to decrypt
  52101. * @param {number} encrypted3 the fourth word to decrypt
  52102. * @param {Int32Array} out the array to write the decrypted words
  52103. * into
  52104. * @param {number} offset the offset into the output array to start
  52105. * writing results
  52106. * @return {Array} The plaintext.
  52107. */
  52108. decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  52109. const key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  52110. let a = encrypted0 ^ key[0];
  52111. let b = encrypted3 ^ key[1];
  52112. let c = encrypted2 ^ key[2];
  52113. let d = encrypted1 ^ key[3];
  52114. let a2;
  52115. let b2;
  52116. let c2; // key.length === 2 ?
  52117. const nInnerRounds = key.length / 4 - 2;
  52118. let i;
  52119. let kIndex = 4;
  52120. const table = this._tables[1]; // load up the tables
  52121. const table0 = table[0];
  52122. const table1 = table[1];
  52123. const table2 = table[2];
  52124. const table3 = table[3];
  52125. const sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  52126. for (i = 0; i < nInnerRounds; i++) {
  52127. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  52128. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  52129. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  52130. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  52131. kIndex += 4;
  52132. a = a2;
  52133. b = b2;
  52134. c = c2;
  52135. } // Last round.
  52136. for (i = 0; i < 4; i++) {
  52137. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  52138. a2 = a;
  52139. a = b;
  52140. b = c;
  52141. c = d;
  52142. d = a2;
  52143. }
  52144. }
  52145. }
  52146. /**
  52147. * @file async-stream.js
  52148. */
  52149. /**
  52150. * A wrapper around the Stream class to use setTimeout
  52151. * and run stream "jobs" Asynchronously
  52152. *
  52153. * @class AsyncStream
  52154. * @extends Stream
  52155. */
  52156. class AsyncStream extends Stream {
  52157. constructor() {
  52158. super(Stream);
  52159. this.jobs = [];
  52160. this.delay = 1;
  52161. this.timeout_ = null;
  52162. }
  52163. /**
  52164. * process an async job
  52165. *
  52166. * @private
  52167. */
  52168. processJob_() {
  52169. this.jobs.shift()();
  52170. if (this.jobs.length) {
  52171. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  52172. } else {
  52173. this.timeout_ = null;
  52174. }
  52175. }
  52176. /**
  52177. * push a job into the stream
  52178. *
  52179. * @param {Function} job the job to push into the stream
  52180. */
  52181. push(job) {
  52182. this.jobs.push(job);
  52183. if (!this.timeout_) {
  52184. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  52185. }
  52186. }
  52187. }
  52188. /**
  52189. * @file decrypter.js
  52190. *
  52191. * An asynchronous implementation of AES-128 CBC decryption with
  52192. * PKCS#7 padding.
  52193. */
  52194. /**
  52195. * Convert network-order (big-endian) bytes into their little-endian
  52196. * representation.
  52197. */
  52198. const ntoh = function (word) {
  52199. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  52200. };
  52201. /**
  52202. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  52203. *
  52204. * @param {Uint8Array} encrypted the encrypted bytes
  52205. * @param {Uint32Array} key the bytes of the decryption key
  52206. * @param {Uint32Array} initVector the initialization vector (IV) to
  52207. * use for the first round of CBC.
  52208. * @return {Uint8Array} the decrypted bytes
  52209. *
  52210. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  52211. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  52212. * @see https://tools.ietf.org/html/rfc2315
  52213. */
  52214. const decrypt = function (encrypted, key, initVector) {
  52215. // word-level access to the encrypted bytes
  52216. const encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  52217. const decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  52218. const decrypted = new Uint8Array(encrypted.byteLength);
  52219. const decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  52220. // decrypted data
  52221. let init0;
  52222. let init1;
  52223. let init2;
  52224. let init3;
  52225. let encrypted0;
  52226. let encrypted1;
  52227. let encrypted2;
  52228. let encrypted3; // iteration variable
  52229. let wordIx; // pull out the words of the IV to ensure we don't modify the
  52230. // passed-in reference and easier access
  52231. init0 = initVector[0];
  52232. init1 = initVector[1];
  52233. init2 = initVector[2];
  52234. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  52235. // to each decrypted block
  52236. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  52237. // convert big-endian (network order) words into little-endian
  52238. // (javascript order)
  52239. encrypted0 = ntoh(encrypted32[wordIx]);
  52240. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  52241. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  52242. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  52243. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  52244. // plaintext
  52245. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  52246. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  52247. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  52248. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  52249. init0 = encrypted0;
  52250. init1 = encrypted1;
  52251. init2 = encrypted2;
  52252. init3 = encrypted3;
  52253. }
  52254. return decrypted;
  52255. };
  52256. /**
  52257. * The `Decrypter` class that manages decryption of AES
  52258. * data through `AsyncStream` objects and the `decrypt`
  52259. * function
  52260. *
  52261. * @param {Uint8Array} encrypted the encrypted bytes
  52262. * @param {Uint32Array} key the bytes of the decryption key
  52263. * @param {Uint32Array} initVector the initialization vector (IV) to
  52264. * @param {Function} done the function to run when done
  52265. * @class Decrypter
  52266. */
  52267. class Decrypter {
  52268. constructor(encrypted, key, initVector, done) {
  52269. const step = Decrypter.STEP;
  52270. const encrypted32 = new Int32Array(encrypted.buffer);
  52271. const decrypted = new Uint8Array(encrypted.byteLength);
  52272. let i = 0;
  52273. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  52274. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  52275. for (i = step; i < encrypted32.length; i += step) {
  52276. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  52277. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  52278. } // invoke the done() callback when everything is finished
  52279. this.asyncStream_.push(function () {
  52280. // remove pkcs#7 padding from the decrypted bytes
  52281. done(null, unpad(decrypted));
  52282. });
  52283. }
  52284. /**
  52285. * a getter for step the maximum number of bytes to process at one time
  52286. *
  52287. * @return {number} the value of step 32000
  52288. */
  52289. static get STEP() {
  52290. // 4 * 8000;
  52291. return 32000;
  52292. }
  52293. /**
  52294. * @private
  52295. */
  52296. decryptChunk_(encrypted, key, initVector, decrypted) {
  52297. return function () {
  52298. const bytes = decrypt(encrypted, key, initVector);
  52299. decrypted.set(bytes, encrypted.byteOffset);
  52300. };
  52301. }
  52302. }
  52303. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  52304. var win;
  52305. if (typeof window !== "undefined") {
  52306. win = window;
  52307. } else if (typeof commonjsGlobal !== "undefined") {
  52308. win = commonjsGlobal;
  52309. } else if (typeof self !== "undefined") {
  52310. win = self;
  52311. } else {
  52312. win = {};
  52313. }
  52314. var window_1 = win;
  52315. var isArrayBufferView = function isArrayBufferView(obj) {
  52316. if (ArrayBuffer.isView === 'function') {
  52317. return ArrayBuffer.isView(obj);
  52318. }
  52319. return obj && obj.buffer instanceof ArrayBuffer;
  52320. };
  52321. var BigInt = window_1.BigInt || Number;
  52322. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  52323. (function () {
  52324. var a = new Uint16Array([0xFFCC]);
  52325. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  52326. if (b[0] === 0xFF) {
  52327. return 'big';
  52328. }
  52329. if (b[0] === 0xCC) {
  52330. return 'little';
  52331. }
  52332. return 'unknown';
  52333. })();
  52334. /**
  52335. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  52336. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  52337. *
  52338. * @param {Object} message
  52339. * Object of properties and values to send to the web worker
  52340. * @return {Object}
  52341. * Modified message with TypedArray values expanded
  52342. * @function createTransferableMessage
  52343. */
  52344. const createTransferableMessage = function (message) {
  52345. const transferable = {};
  52346. Object.keys(message).forEach(key => {
  52347. const value = message[key];
  52348. if (isArrayBufferView(value)) {
  52349. transferable[key] = {
  52350. bytes: value.buffer,
  52351. byteOffset: value.byteOffset,
  52352. byteLength: value.byteLength
  52353. };
  52354. } else {
  52355. transferable[key] = value;
  52356. }
  52357. });
  52358. return transferable;
  52359. };
  52360. /* global self */
  52361. /**
  52362. * Our web worker interface so that things can talk to aes-decrypter
  52363. * that will be running in a web worker. the scope is passed to this by
  52364. * webworkify.
  52365. */
  52366. self.onmessage = function (event) {
  52367. const data = event.data;
  52368. const encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  52369. const key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  52370. const iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  52371. /* eslint-disable no-new, handle-callback-err */
  52372. new Decrypter(encrypted, key, iv, function (err, bytes) {
  52373. self.postMessage(createTransferableMessage({
  52374. source: data.source,
  52375. decrypted: bytes
  52376. }), [bytes.buffer]);
  52377. });
  52378. /* eslint-enable */
  52379. };
  52380. }));
  52381. var Decrypter = factory(workerCode);
  52382. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  52383. /**
  52384. * Convert the properties of an HLS track into an audioTrackKind.
  52385. *
  52386. * @private
  52387. */
  52388. const audioTrackKind_ = properties => {
  52389. let kind = properties.default ? 'main' : 'alternative';
  52390. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  52391. kind = 'main-desc';
  52392. }
  52393. return kind;
  52394. };
  52395. /**
  52396. * Pause provided segment loader and playlist loader if active
  52397. *
  52398. * @param {SegmentLoader} segmentLoader
  52399. * SegmentLoader to pause
  52400. * @param {Object} mediaType
  52401. * Active media type
  52402. * @function stopLoaders
  52403. */
  52404. const stopLoaders = (segmentLoader, mediaType) => {
  52405. segmentLoader.abort();
  52406. segmentLoader.pause();
  52407. if (mediaType && mediaType.activePlaylistLoader) {
  52408. mediaType.activePlaylistLoader.pause();
  52409. mediaType.activePlaylistLoader = null;
  52410. }
  52411. };
  52412. /**
  52413. * Start loading provided segment loader and playlist loader
  52414. *
  52415. * @param {PlaylistLoader} playlistLoader
  52416. * PlaylistLoader to start loading
  52417. * @param {Object} mediaType
  52418. * Active media type
  52419. * @function startLoaders
  52420. */
  52421. const startLoaders = (playlistLoader, mediaType) => {
  52422. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  52423. // playlist loader
  52424. mediaType.activePlaylistLoader = playlistLoader;
  52425. playlistLoader.load();
  52426. };
  52427. /**
  52428. * Returns a function to be called when the media group changes. It performs a
  52429. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  52430. * change of group is merely a rendition switch of the same content at another encoding,
  52431. * rather than a change of content, such as switching audio from English to Spanish.
  52432. *
  52433. * @param {string} type
  52434. * MediaGroup type
  52435. * @param {Object} settings
  52436. * Object containing required information for media groups
  52437. * @return {Function}
  52438. * Handler for a non-destructive resync of SegmentLoader when the active media
  52439. * group changes.
  52440. * @function onGroupChanged
  52441. */
  52442. const onGroupChanged = (type, settings) => () => {
  52443. const {
  52444. segmentLoaders: {
  52445. [type]: segmentLoader,
  52446. main: mainSegmentLoader
  52447. },
  52448. mediaTypes: {
  52449. [type]: mediaType
  52450. }
  52451. } = settings;
  52452. const activeTrack = mediaType.activeTrack();
  52453. const activeGroup = mediaType.getActiveGroup();
  52454. const previousActiveLoader = mediaType.activePlaylistLoader;
  52455. const lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  52456. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  52457. return;
  52458. }
  52459. mediaType.lastGroup_ = activeGroup;
  52460. mediaType.lastTrack_ = activeTrack;
  52461. stopLoaders(segmentLoader, mediaType);
  52462. if (!activeGroup || activeGroup.isMainPlaylist) {
  52463. // there is no group active or active group is a main playlist and won't change
  52464. return;
  52465. }
  52466. if (!activeGroup.playlistLoader) {
  52467. if (previousActiveLoader) {
  52468. // The previous group had a playlist loader but the new active group does not
  52469. // this means we are switching from demuxed to muxed audio. In this case we want to
  52470. // do a destructive reset of the main segment loader and not restart the audio
  52471. // loaders.
  52472. mainSegmentLoader.resetEverything();
  52473. }
  52474. return;
  52475. } // Non-destructive resync
  52476. segmentLoader.resyncLoader();
  52477. startLoaders(activeGroup.playlistLoader, mediaType);
  52478. };
  52479. const onGroupChanging = (type, settings) => () => {
  52480. const {
  52481. segmentLoaders: {
  52482. [type]: segmentLoader
  52483. },
  52484. mediaTypes: {
  52485. [type]: mediaType
  52486. }
  52487. } = settings;
  52488. mediaType.lastGroup_ = null;
  52489. segmentLoader.abort();
  52490. segmentLoader.pause();
  52491. };
  52492. /**
  52493. * Returns a function to be called when the media track changes. It performs a
  52494. * destructive reset of the SegmentLoader to ensure we start loading as close to
  52495. * currentTime as possible.
  52496. *
  52497. * @param {string} type
  52498. * MediaGroup type
  52499. * @param {Object} settings
  52500. * Object containing required information for media groups
  52501. * @return {Function}
  52502. * Handler for a destructive reset of SegmentLoader when the active media
  52503. * track changes.
  52504. * @function onTrackChanged
  52505. */
  52506. const onTrackChanged = (type, settings) => () => {
  52507. const {
  52508. mainPlaylistLoader,
  52509. segmentLoaders: {
  52510. [type]: segmentLoader,
  52511. main: mainSegmentLoader
  52512. },
  52513. mediaTypes: {
  52514. [type]: mediaType
  52515. }
  52516. } = settings;
  52517. const activeTrack = mediaType.activeTrack();
  52518. const activeGroup = mediaType.getActiveGroup();
  52519. const previousActiveLoader = mediaType.activePlaylistLoader;
  52520. const lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  52521. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  52522. return;
  52523. }
  52524. mediaType.lastGroup_ = activeGroup;
  52525. mediaType.lastTrack_ = activeTrack;
  52526. stopLoaders(segmentLoader, mediaType);
  52527. if (!activeGroup) {
  52528. // there is no group active so we do not want to restart loaders
  52529. return;
  52530. }
  52531. if (activeGroup.isMainPlaylist) {
  52532. // track did not change, do nothing
  52533. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  52534. return;
  52535. }
  52536. const pc = settings.vhs.playlistController_;
  52537. const newPlaylist = pc.selectPlaylist(); // media will not change do nothing
  52538. if (pc.media() === newPlaylist) {
  52539. return;
  52540. }
  52541. mediaType.logger_(`track change. Switching main audio from ${lastTrack.id} to ${activeTrack.id}`);
  52542. mainPlaylistLoader.pause();
  52543. mainSegmentLoader.resetEverything();
  52544. pc.fastQualityChange_(newPlaylist);
  52545. return;
  52546. }
  52547. if (type === 'AUDIO') {
  52548. if (!activeGroup.playlistLoader) {
  52549. // when switching from demuxed audio/video to muxed audio/video (noted by no
  52550. // playlist loader for the audio group), we want to do a destructive reset of the
  52551. // main segment loader and not restart the audio loaders
  52552. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  52553. // it should be stopped
  52554. mainSegmentLoader.resetEverything();
  52555. return;
  52556. } // although the segment loader is an audio segment loader, call the setAudio
  52557. // function to ensure it is prepared to re-append the init segment (or handle other
  52558. // config changes)
  52559. segmentLoader.setAudio(true);
  52560. mainSegmentLoader.setAudio(false);
  52561. }
  52562. if (previousActiveLoader === activeGroup.playlistLoader) {
  52563. // Nothing has actually changed. This can happen because track change events can fire
  52564. // multiple times for a "single" change. One for enabling the new active track, and
  52565. // one for disabling the track that was active
  52566. startLoaders(activeGroup.playlistLoader, mediaType);
  52567. return;
  52568. }
  52569. if (segmentLoader.track) {
  52570. // For WebVTT, set the new text track in the segmentloader
  52571. segmentLoader.track(activeTrack);
  52572. } // destructive reset
  52573. segmentLoader.resetEverything();
  52574. startLoaders(activeGroup.playlistLoader, mediaType);
  52575. };
  52576. const onError = {
  52577. /**
  52578. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  52579. * an error.
  52580. *
  52581. * @param {string} type
  52582. * MediaGroup type
  52583. * @param {Object} settings
  52584. * Object containing required information for media groups
  52585. * @return {Function}
  52586. * Error handler. Logs warning (or error if the playlist is excluded) to
  52587. * console and switches back to default audio track.
  52588. * @function onError.AUDIO
  52589. */
  52590. AUDIO: (type, settings) => () => {
  52591. const {
  52592. segmentLoaders: {
  52593. [type]: segmentLoader
  52594. },
  52595. mediaTypes: {
  52596. [type]: mediaType
  52597. },
  52598. excludePlaylist
  52599. } = settings;
  52600. stopLoaders(segmentLoader, mediaType); // switch back to default audio track
  52601. const activeTrack = mediaType.activeTrack();
  52602. const activeGroup = mediaType.activeGroup();
  52603. const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;
  52604. const defaultTrack = mediaType.tracks[id];
  52605. if (activeTrack === defaultTrack) {
  52606. // Default track encountered an error. All we can do now is exclude the current
  52607. // rendition and hope another will switch audio groups
  52608. excludePlaylist({
  52609. error: {
  52610. message: 'Problem encountered loading the default audio track.'
  52611. }
  52612. });
  52613. return;
  52614. }
  52615. videojs.log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  52616. for (const trackId in mediaType.tracks) {
  52617. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  52618. }
  52619. mediaType.onTrackChanged();
  52620. },
  52621. /**
  52622. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  52623. * an error.
  52624. *
  52625. * @param {string} type
  52626. * MediaGroup type
  52627. * @param {Object} settings
  52628. * Object containing required information for media groups
  52629. * @return {Function}
  52630. * Error handler. Logs warning to console and disables the active subtitle track
  52631. * @function onError.SUBTITLES
  52632. */
  52633. SUBTITLES: (type, settings) => () => {
  52634. const {
  52635. segmentLoaders: {
  52636. [type]: segmentLoader
  52637. },
  52638. mediaTypes: {
  52639. [type]: mediaType
  52640. }
  52641. } = settings;
  52642. videojs.log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  52643. stopLoaders(segmentLoader, mediaType);
  52644. const track = mediaType.activeTrack();
  52645. if (track) {
  52646. track.mode = 'disabled';
  52647. }
  52648. mediaType.onTrackChanged();
  52649. }
  52650. };
  52651. const setupListeners = {
  52652. /**
  52653. * Setup event listeners for audio playlist loader
  52654. *
  52655. * @param {string} type
  52656. * MediaGroup type
  52657. * @param {PlaylistLoader|null} playlistLoader
  52658. * PlaylistLoader to register listeners on
  52659. * @param {Object} settings
  52660. * Object containing required information for media groups
  52661. * @function setupListeners.AUDIO
  52662. */
  52663. AUDIO: (type, playlistLoader, settings) => {
  52664. if (!playlistLoader) {
  52665. // no playlist loader means audio will be muxed with the video
  52666. return;
  52667. }
  52668. const {
  52669. tech,
  52670. requestOptions,
  52671. segmentLoaders: {
  52672. [type]: segmentLoader
  52673. }
  52674. } = settings;
  52675. playlistLoader.on('loadedmetadata', () => {
  52676. const media = playlistLoader.media();
  52677. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  52678. // permits, start downloading segments
  52679. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  52680. segmentLoader.load();
  52681. }
  52682. });
  52683. playlistLoader.on('loadedplaylist', () => {
  52684. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  52685. if (!tech.paused()) {
  52686. segmentLoader.load();
  52687. }
  52688. });
  52689. playlistLoader.on('error', onError[type](type, settings));
  52690. },
  52691. /**
  52692. * Setup event listeners for subtitle playlist loader
  52693. *
  52694. * @param {string} type
  52695. * MediaGroup type
  52696. * @param {PlaylistLoader|null} playlistLoader
  52697. * PlaylistLoader to register listeners on
  52698. * @param {Object} settings
  52699. * Object containing required information for media groups
  52700. * @function setupListeners.SUBTITLES
  52701. */
  52702. SUBTITLES: (type, playlistLoader, settings) => {
  52703. const {
  52704. tech,
  52705. requestOptions,
  52706. segmentLoaders: {
  52707. [type]: segmentLoader
  52708. },
  52709. mediaTypes: {
  52710. [type]: mediaType
  52711. }
  52712. } = settings;
  52713. playlistLoader.on('loadedmetadata', () => {
  52714. const media = playlistLoader.media();
  52715. segmentLoader.playlist(media, requestOptions);
  52716. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  52717. // permits, start downloading segments
  52718. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  52719. segmentLoader.load();
  52720. }
  52721. });
  52722. playlistLoader.on('loadedplaylist', () => {
  52723. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  52724. if (!tech.paused()) {
  52725. segmentLoader.load();
  52726. }
  52727. });
  52728. playlistLoader.on('error', onError[type](type, settings));
  52729. }
  52730. };
  52731. const initialize = {
  52732. /**
  52733. * Setup PlaylistLoaders and AudioTracks for the audio groups
  52734. *
  52735. * @param {string} type
  52736. * MediaGroup type
  52737. * @param {Object} settings
  52738. * Object containing required information for media groups
  52739. * @function initialize.AUDIO
  52740. */
  52741. 'AUDIO': (type, settings) => {
  52742. const {
  52743. vhs,
  52744. sourceType,
  52745. segmentLoaders: {
  52746. [type]: segmentLoader
  52747. },
  52748. requestOptions,
  52749. main: {
  52750. mediaGroups
  52751. },
  52752. mediaTypes: {
  52753. [type]: {
  52754. groups,
  52755. tracks,
  52756. logger_
  52757. }
  52758. },
  52759. mainPlaylistLoader
  52760. } = settings;
  52761. const audioOnlyMain = isAudioOnly(mainPlaylistLoader.main); // force a default if we have none
  52762. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  52763. mediaGroups[type] = {
  52764. main: {
  52765. default: {
  52766. default: true
  52767. }
  52768. }
  52769. };
  52770. if (audioOnlyMain) {
  52771. mediaGroups[type].main.default.playlists = mainPlaylistLoader.main.playlists;
  52772. }
  52773. }
  52774. for (const groupId in mediaGroups[type]) {
  52775. if (!groups[groupId]) {
  52776. groups[groupId] = [];
  52777. }
  52778. for (const variantLabel in mediaGroups[type][groupId]) {
  52779. let properties = mediaGroups[type][groupId][variantLabel];
  52780. let playlistLoader;
  52781. if (audioOnlyMain) {
  52782. logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a main playlist`);
  52783. properties.isMainPlaylist = true;
  52784. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  52785. // use the resolved media playlist object
  52786. } else if (sourceType === 'vhs-json' && properties.playlists) {
  52787. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  52788. } else if (properties.resolvedUri) {
  52789. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  52790. // should we even have properties.playlists in this check.
  52791. } else if (properties.playlists && sourceType === 'dash') {
  52792. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  52793. } else {
  52794. // no resolvedUri means the audio is muxed with the video when using this
  52795. // audio track
  52796. playlistLoader = null;
  52797. }
  52798. properties = merge({
  52799. id: variantLabel,
  52800. playlistLoader
  52801. }, properties);
  52802. setupListeners[type](type, properties.playlistLoader, settings);
  52803. groups[groupId].push(properties);
  52804. if (typeof tracks[variantLabel] === 'undefined') {
  52805. const track = new videojs.AudioTrack({
  52806. id: variantLabel,
  52807. kind: audioTrackKind_(properties),
  52808. enabled: false,
  52809. language: properties.language,
  52810. default: properties.default,
  52811. label: variantLabel
  52812. });
  52813. tracks[variantLabel] = track;
  52814. }
  52815. }
  52816. } // setup single error event handler for the segment loader
  52817. segmentLoader.on('error', onError[type](type, settings));
  52818. },
  52819. /**
  52820. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  52821. *
  52822. * @param {string} type
  52823. * MediaGroup type
  52824. * @param {Object} settings
  52825. * Object containing required information for media groups
  52826. * @function initialize.SUBTITLES
  52827. */
  52828. 'SUBTITLES': (type, settings) => {
  52829. const {
  52830. tech,
  52831. vhs,
  52832. sourceType,
  52833. segmentLoaders: {
  52834. [type]: segmentLoader
  52835. },
  52836. requestOptions,
  52837. main: {
  52838. mediaGroups
  52839. },
  52840. mediaTypes: {
  52841. [type]: {
  52842. groups,
  52843. tracks
  52844. }
  52845. },
  52846. mainPlaylistLoader
  52847. } = settings;
  52848. for (const groupId in mediaGroups[type]) {
  52849. if (!groups[groupId]) {
  52850. groups[groupId] = [];
  52851. }
  52852. for (const variantLabel in mediaGroups[type][groupId]) {
  52853. if (mediaGroups[type][groupId][variantLabel].forced) {
  52854. // Subtitle playlists with the forced attribute are not selectable in Safari.
  52855. // According to Apple's HLS Authoring Specification:
  52856. // If content has forced subtitles and regular subtitles in a given language,
  52857. // the regular subtitles track in that language MUST contain both the forced
  52858. // subtitles and the regular subtitles for that language.
  52859. // Because of this requirement and that Safari does not add forced subtitles,
  52860. // forced subtitles are skipped here to maintain consistent experience across
  52861. // all platforms
  52862. continue;
  52863. }
  52864. let properties = mediaGroups[type][groupId][variantLabel];
  52865. let playlistLoader;
  52866. if (sourceType === 'hls') {
  52867. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  52868. } else if (sourceType === 'dash') {
  52869. const playlists = properties.playlists.filter(p => p.excludeUntil !== Infinity);
  52870. if (!playlists.length) {
  52871. return;
  52872. }
  52873. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  52874. } else if (sourceType === 'vhs-json') {
  52875. playlistLoader = new PlaylistLoader(
  52876. // if the vhs-json object included the media playlist, use the media playlist
  52877. // as provided, otherwise use the resolved URI to load the playlist
  52878. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  52879. }
  52880. properties = merge({
  52881. id: variantLabel,
  52882. playlistLoader
  52883. }, properties);
  52884. setupListeners[type](type, properties.playlistLoader, settings);
  52885. groups[groupId].push(properties);
  52886. if (typeof tracks[variantLabel] === 'undefined') {
  52887. const track = tech.addRemoteTextTrack({
  52888. id: variantLabel,
  52889. kind: 'subtitles',
  52890. default: properties.default && properties.autoselect,
  52891. language: properties.language,
  52892. label: variantLabel
  52893. }, false).track;
  52894. tracks[variantLabel] = track;
  52895. }
  52896. }
  52897. } // setup single error event handler for the segment loader
  52898. segmentLoader.on('error', onError[type](type, settings));
  52899. },
  52900. /**
  52901. * Setup TextTracks for the closed-caption groups
  52902. *
  52903. * @param {String} type
  52904. * MediaGroup type
  52905. * @param {Object} settings
  52906. * Object containing required information for media groups
  52907. * @function initialize['CLOSED-CAPTIONS']
  52908. */
  52909. 'CLOSED-CAPTIONS': (type, settings) => {
  52910. const {
  52911. tech,
  52912. main: {
  52913. mediaGroups
  52914. },
  52915. mediaTypes: {
  52916. [type]: {
  52917. groups,
  52918. tracks
  52919. }
  52920. }
  52921. } = settings;
  52922. for (const groupId in mediaGroups[type]) {
  52923. if (!groups[groupId]) {
  52924. groups[groupId] = [];
  52925. }
  52926. for (const variantLabel in mediaGroups[type][groupId]) {
  52927. const properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  52928. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  52929. continue;
  52930. }
  52931. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  52932. let newProps = {
  52933. label: variantLabel,
  52934. language: properties.language,
  52935. instreamId: properties.instreamId,
  52936. default: properties.default && properties.autoselect
  52937. };
  52938. if (captionServices[newProps.instreamId]) {
  52939. newProps = merge(newProps, captionServices[newProps.instreamId]);
  52940. }
  52941. if (newProps.default === undefined) {
  52942. delete newProps.default;
  52943. } // No PlaylistLoader is required for Closed-Captions because the captions are
  52944. // embedded within the video stream
  52945. groups[groupId].push(merge({
  52946. id: variantLabel
  52947. }, properties));
  52948. if (typeof tracks[variantLabel] === 'undefined') {
  52949. const track = tech.addRemoteTextTrack({
  52950. id: newProps.instreamId,
  52951. kind: 'captions',
  52952. default: newProps.default,
  52953. language: newProps.language,
  52954. label: newProps.label
  52955. }, false).track;
  52956. tracks[variantLabel] = track;
  52957. }
  52958. }
  52959. }
  52960. }
  52961. };
  52962. const groupMatch = (list, media) => {
  52963. for (let i = 0; i < list.length; i++) {
  52964. if (playlistMatch(media, list[i])) {
  52965. return true;
  52966. }
  52967. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  52968. return true;
  52969. }
  52970. }
  52971. return false;
  52972. };
  52973. /**
  52974. * Returns a function used to get the active group of the provided type
  52975. *
  52976. * @param {string} type
  52977. * MediaGroup type
  52978. * @param {Object} settings
  52979. * Object containing required information for media groups
  52980. * @return {Function}
  52981. * Function that returns the active media group for the provided type. Takes an
  52982. * optional parameter {TextTrack} track. If no track is provided, a list of all
  52983. * variants in the group, otherwise the variant corresponding to the provided
  52984. * track is returned.
  52985. * @function activeGroup
  52986. */
  52987. const activeGroup = (type, settings) => track => {
  52988. const {
  52989. mainPlaylistLoader,
  52990. mediaTypes: {
  52991. [type]: {
  52992. groups
  52993. }
  52994. }
  52995. } = settings;
  52996. const media = mainPlaylistLoader.media();
  52997. if (!media) {
  52998. return null;
  52999. }
  53000. let variants = null; // set to variants to main media active group
  53001. if (media.attributes[type]) {
  53002. variants = groups[media.attributes[type]];
  53003. }
  53004. const groupKeys = Object.keys(groups);
  53005. if (!variants) {
  53006. // find the mainPlaylistLoader media
  53007. // that is in a media group if we are dealing
  53008. // with audio only
  53009. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.main)) {
  53010. for (let i = 0; i < groupKeys.length; i++) {
  53011. const groupPropertyList = groups[groupKeys[i]];
  53012. if (groupMatch(groupPropertyList, media)) {
  53013. variants = groupPropertyList;
  53014. break;
  53015. }
  53016. } // use the main group if it exists
  53017. } else if (groups.main) {
  53018. variants = groups.main; // only one group, use that one
  53019. } else if (groupKeys.length === 1) {
  53020. variants = groups[groupKeys[0]];
  53021. }
  53022. }
  53023. if (typeof track === 'undefined') {
  53024. return variants;
  53025. }
  53026. if (track === null || !variants) {
  53027. // An active track was specified so a corresponding group is expected. track === null
  53028. // means no track is currently active so there is no corresponding group
  53029. return null;
  53030. }
  53031. return variants.filter(props => props.id === track.id)[0] || null;
  53032. };
  53033. const activeTrack = {
  53034. /**
  53035. * Returns a function used to get the active track of type provided
  53036. *
  53037. * @param {string} type
  53038. * MediaGroup type
  53039. * @param {Object} settings
  53040. * Object containing required information for media groups
  53041. * @return {Function}
  53042. * Function that returns the active media track for the provided type. Returns
  53043. * null if no track is active
  53044. * @function activeTrack.AUDIO
  53045. */
  53046. AUDIO: (type, settings) => () => {
  53047. const {
  53048. mediaTypes: {
  53049. [type]: {
  53050. tracks
  53051. }
  53052. }
  53053. } = settings;
  53054. for (const id in tracks) {
  53055. if (tracks[id].enabled) {
  53056. return tracks[id];
  53057. }
  53058. }
  53059. return null;
  53060. },
  53061. /**
  53062. * Returns a function used to get the active track of type provided
  53063. *
  53064. * @param {string} type
  53065. * MediaGroup type
  53066. * @param {Object} settings
  53067. * Object containing required information for media groups
  53068. * @return {Function}
  53069. * Function that returns the active media track for the provided type. Returns
  53070. * null if no track is active
  53071. * @function activeTrack.SUBTITLES
  53072. */
  53073. SUBTITLES: (type, settings) => () => {
  53074. const {
  53075. mediaTypes: {
  53076. [type]: {
  53077. tracks
  53078. }
  53079. }
  53080. } = settings;
  53081. for (const id in tracks) {
  53082. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  53083. return tracks[id];
  53084. }
  53085. }
  53086. return null;
  53087. }
  53088. };
  53089. const getActiveGroup = (type, {
  53090. mediaTypes
  53091. }) => () => {
  53092. const activeTrack_ = mediaTypes[type].activeTrack();
  53093. if (!activeTrack_) {
  53094. return null;
  53095. }
  53096. return mediaTypes[type].activeGroup(activeTrack_);
  53097. };
  53098. /**
  53099. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  53100. * Closed-Captions) specified in the main manifest.
  53101. *
  53102. * @param {Object} settings
  53103. * Object containing required information for setting up the media groups
  53104. * @param {Tech} settings.tech
  53105. * The tech of the player
  53106. * @param {Object} settings.requestOptions
  53107. * XHR request options used by the segment loaders
  53108. * @param {PlaylistLoader} settings.mainPlaylistLoader
  53109. * PlaylistLoader for the main source
  53110. * @param {VhsHandler} settings.vhs
  53111. * VHS SourceHandler
  53112. * @param {Object} settings.main
  53113. * The parsed main manifest
  53114. * @param {Object} settings.mediaTypes
  53115. * Object to store the loaders, tracks, and utility methods for each media type
  53116. * @param {Function} settings.excludePlaylist
  53117. * Excludes the current rendition and forces a rendition switch.
  53118. * @function setupMediaGroups
  53119. */
  53120. const setupMediaGroups = settings => {
  53121. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  53122. initialize[type](type, settings);
  53123. });
  53124. const {
  53125. mediaTypes,
  53126. mainPlaylistLoader,
  53127. tech,
  53128. vhs,
  53129. segmentLoaders: {
  53130. ['AUDIO']: audioSegmentLoader,
  53131. main: mainSegmentLoader
  53132. }
  53133. } = settings; // setup active group and track getters and change event handlers
  53134. ['AUDIO', 'SUBTITLES'].forEach(type => {
  53135. mediaTypes[type].activeGroup = activeGroup(type, settings);
  53136. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  53137. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  53138. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  53139. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  53140. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  53141. }); // DO NOT enable the default subtitle or caption track.
  53142. // DO enable the default audio track
  53143. const audioGroup = mediaTypes.AUDIO.activeGroup();
  53144. if (audioGroup) {
  53145. const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;
  53146. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  53147. mediaTypes.AUDIO.onGroupChanged();
  53148. mediaTypes.AUDIO.onTrackChanged();
  53149. const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  53150. // track is changed, but needs to be handled here since the track may not be considered
  53151. // changed on the first call to onTrackChanged
  53152. if (!activeAudioGroup.playlistLoader) {
  53153. // either audio is muxed with video or the stream is audio only
  53154. mainSegmentLoader.setAudio(true);
  53155. } else {
  53156. // audio is demuxed
  53157. mainSegmentLoader.setAudio(false);
  53158. audioSegmentLoader.setAudio(true);
  53159. }
  53160. }
  53161. mainPlaylistLoader.on('mediachange', () => {
  53162. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());
  53163. });
  53164. mainPlaylistLoader.on('mediachanging', () => {
  53165. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());
  53166. }); // custom audio track change event handler for usage event
  53167. const onAudioTrackChanged = () => {
  53168. mediaTypes.AUDIO.onTrackChanged();
  53169. tech.trigger({
  53170. type: 'usage',
  53171. name: 'vhs-audio-change'
  53172. });
  53173. };
  53174. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  53175. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  53176. vhs.on('dispose', () => {
  53177. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  53178. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  53179. }); // clear existing audio tracks and add the ones we just created
  53180. tech.clearTracks('audio');
  53181. for (const id in mediaTypes.AUDIO.tracks) {
  53182. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  53183. }
  53184. };
  53185. /**
  53186. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  53187. * media type
  53188. *
  53189. * @return {Object}
  53190. * Object to store the loaders, tracks, and utility methods for each media type
  53191. * @function createMediaTypes
  53192. */
  53193. const createMediaTypes = () => {
  53194. const mediaTypes = {};
  53195. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  53196. mediaTypes[type] = {
  53197. groups: {},
  53198. tracks: {},
  53199. activePlaylistLoader: null,
  53200. activeGroup: noop,
  53201. activeTrack: noop,
  53202. getActiveGroup: noop,
  53203. onGroupChanged: noop,
  53204. onTrackChanged: noop,
  53205. lastTrack_: null,
  53206. logger_: logger(`MediaGroups[${type}]`)
  53207. };
  53208. });
  53209. return mediaTypes;
  53210. };
  53211. /**
  53212. * @file playlist-controller.js
  53213. */
  53214. const ABORT_EARLY_EXCLUSION_SECONDS = 60 * 2;
  53215. let Vhs$1; // SegmentLoader stats that need to have each loader's
  53216. // values summed to calculate the final value
  53217. const loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  53218. const sumLoaderStat = function (stat) {
  53219. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  53220. };
  53221. const shouldSwitchToMedia = function ({
  53222. currentPlaylist,
  53223. buffered,
  53224. currentTime,
  53225. nextPlaylist,
  53226. bufferLowWaterLine,
  53227. bufferHighWaterLine,
  53228. duration,
  53229. bufferBasedABR,
  53230. log
  53231. }) {
  53232. // we have no other playlist to switch to
  53233. if (!nextPlaylist) {
  53234. videojs.log.warn('We received no playlist to switch to. Please check your stream.');
  53235. return false;
  53236. }
  53237. const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;
  53238. if (!currentPlaylist) {
  53239. log(`${sharedLogLine} as current playlist is not set`);
  53240. return true;
  53241. } // no need to switch if playlist is the same
  53242. if (nextPlaylist.id === currentPlaylist.id) {
  53243. return false;
  53244. } // determine if current time is in a buffered range.
  53245. const isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  53246. // This is because in LIVE, the player plays 3 segments from the end of the
  53247. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  53248. // in those segments, a viewer will never experience a rendition upswitch.
  53249. if (!currentPlaylist.endList) {
  53250. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  53251. // doubles the time to first playback.
  53252. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  53253. log(`not ${sharedLogLine} as current playlist is live llhls, but currentTime isn't in buffered.`);
  53254. return false;
  53255. }
  53256. log(`${sharedLogLine} as current playlist is live`);
  53257. return true;
  53258. }
  53259. const forwardBuffer = timeAheadOf(buffered, currentTime);
  53260. 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
  53261. // duration is below the max potential low water line
  53262. if (duration < maxBufferLowWaterLine) {
  53263. log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);
  53264. return true;
  53265. }
  53266. const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  53267. const currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  53268. // we can switch down
  53269. if (nextBandwidth < currBandwidth && (!bufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  53270. let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;
  53271. if (bufferBasedABR) {
  53272. logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;
  53273. }
  53274. log(logLine);
  53275. return true;
  53276. } // and if our buffer is higher than the low water line,
  53277. // we can switch up
  53278. if ((!bufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  53279. let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;
  53280. if (bufferBasedABR) {
  53281. logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;
  53282. }
  53283. log(logLine);
  53284. return true;
  53285. }
  53286. log(`not ${sharedLogLine} as no switching criteria met`);
  53287. return false;
  53288. };
  53289. /**
  53290. * the main playlist controller controller all interactons
  53291. * between playlists and segmentloaders. At this time this mainly
  53292. * involves a main playlist and a series of audio playlists
  53293. * if they are available
  53294. *
  53295. * @class PlaylistController
  53296. * @extends videojs.EventTarget
  53297. */
  53298. class PlaylistController extends videojs.EventTarget {
  53299. constructor(options) {
  53300. super();
  53301. const {
  53302. src,
  53303. withCredentials,
  53304. tech,
  53305. bandwidth,
  53306. externVhs,
  53307. useCueTags,
  53308. playlistExclusionDuration,
  53309. enableLowInitialPlaylist,
  53310. sourceType,
  53311. cacheEncryptionKeys,
  53312. bufferBasedABR,
  53313. leastPixelDiffSelector,
  53314. captionServices
  53315. } = options;
  53316. if (!src) {
  53317. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  53318. }
  53319. let {
  53320. maxPlaylistRetries
  53321. } = options;
  53322. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  53323. maxPlaylistRetries = Infinity;
  53324. }
  53325. Vhs$1 = externVhs;
  53326. this.bufferBasedABR = Boolean(bufferBasedABR);
  53327. this.leastPixelDiffSelector = Boolean(leastPixelDiffSelector);
  53328. this.withCredentials = withCredentials;
  53329. this.tech_ = tech;
  53330. this.vhs_ = tech.vhs;
  53331. this.sourceType_ = sourceType;
  53332. this.useCueTags_ = useCueTags;
  53333. this.playlistExclusionDuration = playlistExclusionDuration;
  53334. this.maxPlaylistRetries = maxPlaylistRetries;
  53335. this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  53336. if (this.useCueTags_) {
  53337. this.cueTagsTrack_ = this.tech_.addTextTrack('metadata', 'ad-cues');
  53338. this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  53339. }
  53340. this.requestOptions_ = {
  53341. withCredentials,
  53342. maxPlaylistRetries,
  53343. timeout: null
  53344. };
  53345. this.on('error', this.pauseLoading);
  53346. this.mediaTypes_ = createMediaTypes();
  53347. this.mediaSource = new window.MediaSource();
  53348. this.handleDurationChange_ = this.handleDurationChange_.bind(this);
  53349. this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);
  53350. this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);
  53351. this.mediaSource.addEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  53352. this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);
  53353. this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  53354. // everything, and the MediaSource should not be detached without a proper disposal
  53355. this.seekable_ = createTimeRanges();
  53356. this.hasPlayed_ = false;
  53357. this.syncController_ = new SyncController(options);
  53358. this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  53359. kind: 'metadata',
  53360. label: 'segment-metadata'
  53361. }, false).track;
  53362. this.decrypter_ = new Decrypter();
  53363. this.sourceUpdater_ = new SourceUpdater(this.mediaSource);
  53364. this.inbandTextTracks_ = {};
  53365. this.timelineChangeController_ = new TimelineChangeController();
  53366. const segmentLoaderSettings = {
  53367. vhs: this.vhs_,
  53368. parse708captions: options.parse708captions,
  53369. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  53370. captionServices,
  53371. mediaSource: this.mediaSource,
  53372. currentTime: this.tech_.currentTime.bind(this.tech_),
  53373. seekable: () => this.seekable(),
  53374. seeking: () => this.tech_.seeking(),
  53375. duration: () => this.duration(),
  53376. hasPlayed: () => this.hasPlayed_,
  53377. goalBufferLength: () => this.goalBufferLength(),
  53378. bandwidth,
  53379. syncController: this.syncController_,
  53380. decrypter: this.decrypter_,
  53381. sourceType: this.sourceType_,
  53382. inbandTextTracks: this.inbandTextTracks_,
  53383. cacheEncryptionKeys,
  53384. sourceUpdater: this.sourceUpdater_,
  53385. timelineChangeController: this.timelineChangeController_,
  53386. exactManifestTimings: options.exactManifestTimings
  53387. }; // The source type check not only determines whether a special DASH playlist loader
  53388. // should be used, but also covers the case where the provided src is a vhs-json
  53389. // manifest object (instead of a URL). In the case of vhs-json, the default
  53390. // PlaylistLoader should be used.
  53391. this.mainPlaylistLoader_ = this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, this.vhs_, this.requestOptions_) : new PlaylistLoader(src, this.vhs_, this.requestOptions_);
  53392. this.setupMainPlaylistLoaderListeners_(); // setup segment loaders
  53393. // combined audio/video or just video when alternate audio track is selected
  53394. this.mainSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  53395. segmentMetadataTrack: this.segmentMetadataTrack_,
  53396. loaderType: 'main'
  53397. }), options); // alternate audio track
  53398. this.audioSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  53399. loaderType: 'audio'
  53400. }), options);
  53401. this.subtitleSegmentLoader_ = new VTTSegmentLoader(merge(segmentLoaderSettings, {
  53402. loaderType: 'vtt',
  53403. featuresNativeTextTracks: this.tech_.featuresNativeTextTracks,
  53404. loadVttJs: () => new Promise((resolve, reject) => {
  53405. function onLoad() {
  53406. tech.off('vttjserror', onError);
  53407. resolve();
  53408. }
  53409. function onError() {
  53410. tech.off('vttjsloaded', onLoad);
  53411. reject();
  53412. }
  53413. tech.one('vttjsloaded', onLoad);
  53414. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  53415. tech.addWebVttScript_();
  53416. })
  53417. }), options);
  53418. this.setupSegmentLoaderListeners_();
  53419. if (this.bufferBasedABR) {
  53420. this.mainPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());
  53421. this.tech_.on('pause', () => this.stopABRTimer_());
  53422. this.tech_.on('play', () => this.startABRTimer_());
  53423. } // Create SegmentLoader stat-getters
  53424. // mediaRequests_
  53425. // mediaRequestsAborted_
  53426. // mediaRequestsTimedout_
  53427. // mediaRequestsErrored_
  53428. // mediaTransferDuration_
  53429. // mediaBytesTransferred_
  53430. // mediaAppends_
  53431. loaderStats.forEach(stat => {
  53432. this[stat + '_'] = sumLoaderStat.bind(this, stat);
  53433. });
  53434. this.logger_ = logger('pc');
  53435. this.triggeredFmp4Usage = false;
  53436. if (this.tech_.preload() === 'none') {
  53437. this.loadOnPlay_ = () => {
  53438. this.loadOnPlay_ = null;
  53439. this.mainPlaylistLoader_.load();
  53440. };
  53441. this.tech_.one('play', this.loadOnPlay_);
  53442. } else {
  53443. this.mainPlaylistLoader_.load();
  53444. }
  53445. this.timeToLoadedData__ = -1;
  53446. this.mainAppendsToLoadedData__ = -1;
  53447. this.audioAppendsToLoadedData__ = -1;
  53448. const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  53449. this.tech_.one(event, () => {
  53450. const timeToLoadedDataStart = Date.now();
  53451. this.tech_.one('loadeddata', () => {
  53452. this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  53453. this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;
  53454. this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;
  53455. });
  53456. });
  53457. }
  53458. mainAppendsToLoadedData_() {
  53459. return this.mainAppendsToLoadedData__;
  53460. }
  53461. audioAppendsToLoadedData_() {
  53462. return this.audioAppendsToLoadedData__;
  53463. }
  53464. appendsToLoadedData_() {
  53465. const main = this.mainAppendsToLoadedData_();
  53466. const audio = this.audioAppendsToLoadedData_();
  53467. if (main === -1 || audio === -1) {
  53468. return -1;
  53469. }
  53470. return main + audio;
  53471. }
  53472. timeToLoadedData_() {
  53473. return this.timeToLoadedData__;
  53474. }
  53475. /**
  53476. * Run selectPlaylist and switch to the new playlist if we should
  53477. *
  53478. * @param {string} [reason=abr] a reason for why the ABR check is made
  53479. * @private
  53480. */
  53481. checkABR_(reason = 'abr') {
  53482. const nextPlaylist = this.selectPlaylist();
  53483. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  53484. this.switchMedia_(nextPlaylist, reason);
  53485. }
  53486. }
  53487. switchMedia_(playlist, cause, delay) {
  53488. const oldMedia = this.media();
  53489. const oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  53490. const newId = playlist.id || playlist.uri;
  53491. if (oldId && oldId !== newId) {
  53492. this.logger_(`switch media ${oldId} -> ${newId} from ${cause}`);
  53493. this.tech_.trigger({
  53494. type: 'usage',
  53495. name: `vhs-rendition-change-${cause}`
  53496. });
  53497. }
  53498. this.mainPlaylistLoader_.media(playlist, delay);
  53499. }
  53500. /**
  53501. * Start a timer that periodically calls checkABR_
  53502. *
  53503. * @private
  53504. */
  53505. startABRTimer_() {
  53506. this.stopABRTimer_();
  53507. this.abrTimer_ = window.setInterval(() => this.checkABR_(), 250);
  53508. }
  53509. /**
  53510. * Stop the timer that periodically calls checkABR_
  53511. *
  53512. * @private
  53513. */
  53514. stopABRTimer_() {
  53515. // if we're scrubbing, we don't need to pause.
  53516. // This getter will be added to Video.js in version 7.11.
  53517. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  53518. return;
  53519. }
  53520. window.clearInterval(this.abrTimer_);
  53521. this.abrTimer_ = null;
  53522. }
  53523. /**
  53524. * Get a list of playlists for the currently selected audio playlist
  53525. *
  53526. * @return {Array} the array of audio playlists
  53527. */
  53528. getAudioTrackPlaylists_() {
  53529. const main = this.main();
  53530. const defaultPlaylists = main && main.playlists || []; // if we don't have any audio groups then we can only
  53531. // assume that the audio tracks are contained in main
  53532. // playlist array, use that or an empty array.
  53533. if (!main || !main.mediaGroups || !main.mediaGroups.AUDIO) {
  53534. return defaultPlaylists;
  53535. }
  53536. const AUDIO = main.mediaGroups.AUDIO;
  53537. const groupKeys = Object.keys(AUDIO);
  53538. let track; // get the current active track
  53539. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  53540. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from main if mediaTypes_ isn't setup yet
  53541. } else {
  53542. // default group is `main` or just the first group.
  53543. const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  53544. for (const label in defaultGroup) {
  53545. if (defaultGroup[label].default) {
  53546. track = {
  53547. label
  53548. };
  53549. break;
  53550. }
  53551. }
  53552. } // no active track no playlists.
  53553. if (!track) {
  53554. return defaultPlaylists;
  53555. }
  53556. const playlists = []; // get all of the playlists that are possible for the
  53557. // active track.
  53558. for (const group in AUDIO) {
  53559. if (AUDIO[group][track.label]) {
  53560. const properties = AUDIO[group][track.label];
  53561. if (properties.playlists && properties.playlists.length) {
  53562. playlists.push.apply(playlists, properties.playlists);
  53563. } else if (properties.uri) {
  53564. playlists.push(properties);
  53565. } else if (main.playlists.length) {
  53566. // if an audio group does not have a uri
  53567. // see if we have main playlists that use it as a group.
  53568. // if we do then add those to the playlists list.
  53569. for (let i = 0; i < main.playlists.length; i++) {
  53570. const playlist = main.playlists[i];
  53571. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  53572. playlists.push(playlist);
  53573. }
  53574. }
  53575. }
  53576. }
  53577. }
  53578. if (!playlists.length) {
  53579. return defaultPlaylists;
  53580. }
  53581. return playlists;
  53582. }
  53583. /**
  53584. * Register event handlers on the main playlist loader. A helper
  53585. * function for construction time.
  53586. *
  53587. * @private
  53588. */
  53589. setupMainPlaylistLoaderListeners_() {
  53590. this.mainPlaylistLoader_.on('loadedmetadata', () => {
  53591. const media = this.mainPlaylistLoader_.media();
  53592. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  53593. // timeout the request.
  53594. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  53595. this.requestOptions_.timeout = 0;
  53596. } else {
  53597. this.requestOptions_.timeout = requestTimeout;
  53598. } // if this isn't a live video and preload permits, start
  53599. // downloading segments
  53600. if (media.endList && this.tech_.preload() !== 'none') {
  53601. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  53602. this.mainSegmentLoader_.load();
  53603. }
  53604. setupMediaGroups({
  53605. sourceType: this.sourceType_,
  53606. segmentLoaders: {
  53607. AUDIO: this.audioSegmentLoader_,
  53608. SUBTITLES: this.subtitleSegmentLoader_,
  53609. main: this.mainSegmentLoader_
  53610. },
  53611. tech: this.tech_,
  53612. requestOptions: this.requestOptions_,
  53613. mainPlaylistLoader: this.mainPlaylistLoader_,
  53614. vhs: this.vhs_,
  53615. main: this.main(),
  53616. mediaTypes: this.mediaTypes_,
  53617. excludePlaylist: this.excludePlaylist.bind(this)
  53618. });
  53619. this.triggerPresenceUsage_(this.main(), media);
  53620. this.setupFirstPlay();
  53621. if (!this.mediaTypes_.AUDIO.activePlaylistLoader || this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  53622. this.trigger('selectedinitialmedia');
  53623. } else {
  53624. // We must wait for the active audio playlist loader to
  53625. // finish setting up before triggering this event so the
  53626. // representations API and EME setup is correct
  53627. this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {
  53628. this.trigger('selectedinitialmedia');
  53629. });
  53630. }
  53631. });
  53632. this.mainPlaylistLoader_.on('loadedplaylist', () => {
  53633. if (this.loadOnPlay_) {
  53634. this.tech_.off('play', this.loadOnPlay_);
  53635. }
  53636. let updatedPlaylist = this.mainPlaylistLoader_.media();
  53637. if (!updatedPlaylist) {
  53638. // exclude any variants that are not supported by the browser before selecting
  53639. // an initial media as the playlist selectors do not consider browser support
  53640. this.excludeUnsupportedVariants_();
  53641. let selectedMedia;
  53642. if (this.enableLowInitialPlaylist) {
  53643. selectedMedia = this.selectInitialPlaylist();
  53644. }
  53645. if (!selectedMedia) {
  53646. selectedMedia = this.selectPlaylist();
  53647. }
  53648. if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {
  53649. return;
  53650. }
  53651. this.initialMedia_ = selectedMedia;
  53652. this.switchMedia_(this.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  53653. // fire again since the playlist will be requested. In the case of vhs-json
  53654. // (where the manifest object is provided as the source), when the media
  53655. // playlist's `segments` list is already available, a media playlist won't be
  53656. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  53657. // called on its own here.
  53658. const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;
  53659. if (!haveJsonSource) {
  53660. return;
  53661. }
  53662. updatedPlaylist = this.initialMedia_;
  53663. }
  53664. this.handleUpdatedMediaPlaylist(updatedPlaylist);
  53665. });
  53666. this.mainPlaylistLoader_.on('error', () => {
  53667. const error = this.mainPlaylistLoader_.error;
  53668. this.excludePlaylist({
  53669. playlistToExclude: error.playlist,
  53670. error
  53671. });
  53672. });
  53673. this.mainPlaylistLoader_.on('mediachanging', () => {
  53674. this.mainSegmentLoader_.abort();
  53675. this.mainSegmentLoader_.pause();
  53676. });
  53677. this.mainPlaylistLoader_.on('mediachange', () => {
  53678. const media = this.mainPlaylistLoader_.media();
  53679. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  53680. // timeout the request.
  53681. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  53682. this.requestOptions_.timeout = 0;
  53683. } else {
  53684. this.requestOptions_.timeout = requestTimeout;
  53685. }
  53686. this.mainPlaylistLoader_.load(); // TODO: Create a new event on the PlaylistLoader that signals
  53687. // that the segments have changed in some way and use that to
  53688. // update the SegmentLoader instead of doing it twice here and
  53689. // on `loadedplaylist`
  53690. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  53691. this.mainSegmentLoader_.load();
  53692. this.tech_.trigger({
  53693. type: 'mediachange',
  53694. bubbles: true
  53695. });
  53696. });
  53697. this.mainPlaylistLoader_.on('playlistunchanged', () => {
  53698. const updatedPlaylist = this.mainPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  53699. // excluded for not-changing. We likely just have a really slowly updating
  53700. // playlist.
  53701. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  53702. return;
  53703. }
  53704. const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);
  53705. if (playlistOutdated) {
  53706. // Playlist has stopped updating and we're stuck at its end. Try to
  53707. // exclude it and switch to another playlist in the hope that that
  53708. // one is updating (and give the player a chance to re-adjust to the
  53709. // safe live point).
  53710. this.excludePlaylist({
  53711. error: {
  53712. message: 'Playlist no longer updating.',
  53713. reason: 'playlist-unchanged'
  53714. }
  53715. }); // useful for monitoring QoS
  53716. this.tech_.trigger('playliststuck');
  53717. }
  53718. });
  53719. this.mainPlaylistLoader_.on('renditiondisabled', () => {
  53720. this.tech_.trigger({
  53721. type: 'usage',
  53722. name: 'vhs-rendition-disabled'
  53723. });
  53724. });
  53725. this.mainPlaylistLoader_.on('renditionenabled', () => {
  53726. this.tech_.trigger({
  53727. type: 'usage',
  53728. name: 'vhs-rendition-enabled'
  53729. });
  53730. });
  53731. }
  53732. /**
  53733. * Given an updated media playlist (whether it was loaded for the first time, or
  53734. * refreshed for live playlists), update any relevant properties and state to reflect
  53735. * changes in the media that should be accounted for (e.g., cues and duration).
  53736. *
  53737. * @param {Object} updatedPlaylist the updated media playlist object
  53738. *
  53739. * @private
  53740. */
  53741. handleUpdatedMediaPlaylist(updatedPlaylist) {
  53742. if (this.useCueTags_) {
  53743. this.updateAdCues_(updatedPlaylist);
  53744. } // TODO: Create a new event on the PlaylistLoader that signals
  53745. // that the segments have changed in some way and use that to
  53746. // update the SegmentLoader instead of doing it twice here and
  53747. // on `mediachange`
  53748. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  53749. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  53750. // as it is possible that it was temporarily stopped while waiting for
  53751. // a playlist (e.g., in case the playlist errored and we re-requested it).
  53752. if (!this.tech_.paused()) {
  53753. this.mainSegmentLoader_.load();
  53754. if (this.audioSegmentLoader_) {
  53755. this.audioSegmentLoader_.load();
  53756. }
  53757. }
  53758. }
  53759. /**
  53760. * A helper function for triggerring presence usage events once per source
  53761. *
  53762. * @private
  53763. */
  53764. triggerPresenceUsage_(main, media) {
  53765. const mediaGroups = main.mediaGroups || {};
  53766. let defaultDemuxed = true;
  53767. const audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  53768. for (const mediaGroup in mediaGroups.AUDIO) {
  53769. for (const label in mediaGroups.AUDIO[mediaGroup]) {
  53770. const properties = mediaGroups.AUDIO[mediaGroup][label];
  53771. if (!properties.uri) {
  53772. defaultDemuxed = false;
  53773. }
  53774. }
  53775. }
  53776. if (defaultDemuxed) {
  53777. this.tech_.trigger({
  53778. type: 'usage',
  53779. name: 'vhs-demuxed'
  53780. });
  53781. }
  53782. if (Object.keys(mediaGroups.SUBTITLES).length) {
  53783. this.tech_.trigger({
  53784. type: 'usage',
  53785. name: 'vhs-webvtt'
  53786. });
  53787. }
  53788. if (Vhs$1.Playlist.isAes(media)) {
  53789. this.tech_.trigger({
  53790. type: 'usage',
  53791. name: 'vhs-aes'
  53792. });
  53793. }
  53794. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  53795. this.tech_.trigger({
  53796. type: 'usage',
  53797. name: 'vhs-alternate-audio'
  53798. });
  53799. }
  53800. if (this.useCueTags_) {
  53801. this.tech_.trigger({
  53802. type: 'usage',
  53803. name: 'vhs-playlist-cue-tags'
  53804. });
  53805. }
  53806. }
  53807. shouldSwitchToMedia_(nextPlaylist) {
  53808. const currentPlaylist = this.mainPlaylistLoader_.media() || this.mainPlaylistLoader_.pendingMedia_;
  53809. const currentTime = this.tech_.currentTime();
  53810. const bufferLowWaterLine = this.bufferLowWaterLine();
  53811. const bufferHighWaterLine = this.bufferHighWaterLine();
  53812. const buffered = this.tech_.buffered();
  53813. return shouldSwitchToMedia({
  53814. buffered,
  53815. currentTime,
  53816. currentPlaylist,
  53817. nextPlaylist,
  53818. bufferLowWaterLine,
  53819. bufferHighWaterLine,
  53820. duration: this.duration(),
  53821. bufferBasedABR: this.bufferBasedABR,
  53822. log: this.logger_
  53823. });
  53824. }
  53825. /**
  53826. * Register event handlers on the segment loaders. A helper function
  53827. * for construction time.
  53828. *
  53829. * @private
  53830. */
  53831. setupSegmentLoaderListeners_() {
  53832. this.mainSegmentLoader_.on('bandwidthupdate', () => {
  53833. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  53834. // useful to check to see if a rendition switch should be made.
  53835. this.checkABR_('bandwidthupdate');
  53836. this.tech_.trigger('bandwidthupdate');
  53837. });
  53838. this.mainSegmentLoader_.on('timeout', () => {
  53839. if (this.bufferBasedABR) {
  53840. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  53841. // Here the only consideration is that for buffer based ABR there's no guarantee
  53842. // of an immediate switch (since the bandwidth is averaged with a timeout
  53843. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  53844. this.mainSegmentLoader_.load();
  53845. }
  53846. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  53847. // based ABR.
  53848. if (!this.bufferBasedABR) {
  53849. this.mainSegmentLoader_.on('progress', () => {
  53850. this.trigger('progress');
  53851. });
  53852. }
  53853. this.mainSegmentLoader_.on('error', () => {
  53854. const error = this.mainSegmentLoader_.error();
  53855. this.excludePlaylist({
  53856. playlistToExclude: error.playlist,
  53857. error
  53858. });
  53859. });
  53860. this.mainSegmentLoader_.on('appenderror', () => {
  53861. this.error = this.mainSegmentLoader_.error_;
  53862. this.trigger('error');
  53863. });
  53864. this.mainSegmentLoader_.on('syncinfoupdate', () => {
  53865. this.onSyncInfoUpdate_();
  53866. });
  53867. this.mainSegmentLoader_.on('timestampoffset', () => {
  53868. this.tech_.trigger({
  53869. type: 'usage',
  53870. name: 'vhs-timestamp-offset'
  53871. });
  53872. });
  53873. this.audioSegmentLoader_.on('syncinfoupdate', () => {
  53874. this.onSyncInfoUpdate_();
  53875. });
  53876. this.audioSegmentLoader_.on('appenderror', () => {
  53877. this.error = this.audioSegmentLoader_.error_;
  53878. this.trigger('error');
  53879. });
  53880. this.mainSegmentLoader_.on('ended', () => {
  53881. this.logger_('main segment loader ended');
  53882. this.onEndOfStream();
  53883. });
  53884. this.mainSegmentLoader_.on('earlyabort', event => {
  53885. // never try to early abort with the new ABR algorithm
  53886. if (this.bufferBasedABR) {
  53887. return;
  53888. }
  53889. this.delegateLoaders_('all', ['abort']);
  53890. this.excludePlaylist({
  53891. error: {
  53892. message: 'Aborted early because there isn\'t enough bandwidth to complete ' + 'the request without rebuffering.'
  53893. },
  53894. playlistExclusionDuration: ABORT_EARLY_EXCLUSION_SECONDS
  53895. });
  53896. });
  53897. const updateCodecs = () => {
  53898. if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {
  53899. return this.tryToCreateSourceBuffers_();
  53900. }
  53901. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  53902. if (!codecs) {
  53903. return;
  53904. }
  53905. this.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  53906. };
  53907. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  53908. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  53909. this.mainSegmentLoader_.on('fmp4', () => {
  53910. if (!this.triggeredFmp4Usage) {
  53911. this.tech_.trigger({
  53912. type: 'usage',
  53913. name: 'vhs-fmp4'
  53914. });
  53915. this.triggeredFmp4Usage = true;
  53916. }
  53917. });
  53918. this.audioSegmentLoader_.on('fmp4', () => {
  53919. if (!this.triggeredFmp4Usage) {
  53920. this.tech_.trigger({
  53921. type: 'usage',
  53922. name: 'vhs-fmp4'
  53923. });
  53924. this.triggeredFmp4Usage = true;
  53925. }
  53926. });
  53927. this.audioSegmentLoader_.on('ended', () => {
  53928. this.logger_('audioSegmentLoader ended');
  53929. this.onEndOfStream();
  53930. });
  53931. }
  53932. mediaSecondsLoaded_() {
  53933. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  53934. }
  53935. /**
  53936. * Call load on our SegmentLoaders
  53937. */
  53938. load() {
  53939. this.mainSegmentLoader_.load();
  53940. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  53941. this.audioSegmentLoader_.load();
  53942. }
  53943. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  53944. this.subtitleSegmentLoader_.load();
  53945. }
  53946. }
  53947. /**
  53948. * Re-tune playback quality level for the current player
  53949. * conditions. This method will perform destructive actions like removing
  53950. * already buffered content in order to readjust the currently active
  53951. * playlist quickly. This is good for manual quality changes
  53952. *
  53953. * @private
  53954. */
  53955. fastQualityChange_(media = this.selectPlaylist()) {
  53956. if (media === this.mainPlaylistLoader_.media()) {
  53957. this.logger_('skipping fastQualityChange because new media is same as old');
  53958. return;
  53959. }
  53960. this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
  53961. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  53962. // ahead is roughly the minimum that will accomplish this across a variety of content
  53963. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  53964. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  53965. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  53966. this.mainSegmentLoader_.resetEverything(() => {
  53967. // Since this is not a typical seek, we avoid the seekTo method which can cause segments
  53968. // from the previously enabled rendition to load before the new playlist has finished loading
  53969. if (videojs.browser.IE_VERSION || videojs.browser.IS_EDGE) {
  53970. this.tech_.setCurrentTime(this.tech_.currentTime() + 0.04);
  53971. } else {
  53972. this.tech_.setCurrentTime(this.tech_.currentTime());
  53973. }
  53974. }); // don't need to reset audio as it is reset when media changes
  53975. }
  53976. /**
  53977. * Begin playback.
  53978. */
  53979. play() {
  53980. if (this.setupFirstPlay()) {
  53981. return;
  53982. }
  53983. if (this.tech_.ended()) {
  53984. this.tech_.setCurrentTime(0);
  53985. }
  53986. if (this.hasPlayed_) {
  53987. this.load();
  53988. }
  53989. const seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  53990. // seek forward to the live point
  53991. if (this.tech_.duration() === Infinity) {
  53992. if (this.tech_.currentTime() < seekable.start(0)) {
  53993. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  53994. }
  53995. }
  53996. }
  53997. /**
  53998. * Seek to the latest media position if this is a live video and the
  53999. * player and video are loaded and initialized.
  54000. */
  54001. setupFirstPlay() {
  54002. const media = this.mainPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  54003. // If 1) there is no active media
  54004. // 2) the player is paused
  54005. // 3) the first play has already been setup
  54006. // then exit early
  54007. if (!media || this.tech_.paused() || this.hasPlayed_) {
  54008. return false;
  54009. } // when the video is a live stream
  54010. if (!media.endList) {
  54011. const seekable = this.seekable();
  54012. if (!seekable.length) {
  54013. // without a seekable range, the player cannot seek to begin buffering at the live
  54014. // point
  54015. return false;
  54016. }
  54017. if (videojs.browser.IE_VERSION && this.tech_.readyState() === 0) {
  54018. // IE11 throws an InvalidStateError if you try to set currentTime while the
  54019. // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
  54020. this.tech_.one('loadedmetadata', () => {
  54021. this.trigger('firstplay');
  54022. this.tech_.setCurrentTime(seekable.end(0));
  54023. this.hasPlayed_ = true;
  54024. });
  54025. return false;
  54026. } // trigger firstplay to inform the source handler to ignore the next seek event
  54027. this.trigger('firstplay'); // seek to the live point
  54028. this.tech_.setCurrentTime(seekable.end(0));
  54029. }
  54030. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  54031. this.load();
  54032. return true;
  54033. }
  54034. /**
  54035. * handle the sourceopen event on the MediaSource
  54036. *
  54037. * @private
  54038. */
  54039. handleSourceOpen_() {
  54040. // Only attempt to create the source buffer if none already exist.
  54041. // handleSourceOpen is also called when we are "re-opening" a source buffer
  54042. // after `endOfStream` has been called (in response to a seek for instance)
  54043. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  54044. // code in video.js but is required because play() must be invoked
  54045. // *after* the media source has opened.
  54046. if (this.tech_.autoplay()) {
  54047. const playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  54048. // on browsers which return a promise
  54049. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  54050. playPromise.then(null, e => {});
  54051. }
  54052. }
  54053. this.trigger('sourceopen');
  54054. }
  54055. /**
  54056. * handle the sourceended event on the MediaSource
  54057. *
  54058. * @private
  54059. */
  54060. handleSourceEnded_() {
  54061. if (!this.inbandTextTracks_.metadataTrack_) {
  54062. return;
  54063. }
  54064. const cues = this.inbandTextTracks_.metadataTrack_.cues;
  54065. if (!cues || !cues.length) {
  54066. return;
  54067. }
  54068. const duration = this.duration();
  54069. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  54070. }
  54071. /**
  54072. * handle the durationchange event on the MediaSource
  54073. *
  54074. * @private
  54075. */
  54076. handleDurationChange_() {
  54077. this.tech_.trigger('durationchange');
  54078. }
  54079. /**
  54080. * Calls endOfStream on the media source when all active stream types have called
  54081. * endOfStream
  54082. *
  54083. * @param {string} streamType
  54084. * Stream type of the segment loader that called endOfStream
  54085. * @private
  54086. */
  54087. onEndOfStream() {
  54088. let isEndOfStream = this.mainSegmentLoader_.ended_;
  54089. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  54090. const mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  54091. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  54092. // if we do not know if the main segment loader contains video yet or if we
  54093. // definitively know the main segment loader contains video, then we need to wait
  54094. // for both main and audio segment loaders to call endOfStream
  54095. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  54096. } else {
  54097. // otherwise just rely on the audio loader
  54098. isEndOfStream = this.audioSegmentLoader_.ended_;
  54099. }
  54100. }
  54101. if (!isEndOfStream) {
  54102. return;
  54103. }
  54104. this.stopABRTimer_();
  54105. this.sourceUpdater_.endOfStream();
  54106. }
  54107. /**
  54108. * Check if a playlist has stopped being updated
  54109. *
  54110. * @param {Object} playlist the media playlist object
  54111. * @return {boolean} whether the playlist has stopped being updated or not
  54112. */
  54113. stuckAtPlaylistEnd_(playlist) {
  54114. const seekable = this.seekable();
  54115. if (!seekable.length) {
  54116. // playlist doesn't have enough information to determine whether we are stuck
  54117. return false;
  54118. }
  54119. const expired = this.syncController_.getExpiredTime(playlist, this.duration());
  54120. if (expired === null) {
  54121. return false;
  54122. } // does not use the safe live end to calculate playlist end, since we
  54123. // don't want to say we are stuck while there is still content
  54124. const absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  54125. const currentTime = this.tech_.currentTime();
  54126. const buffered = this.tech_.buffered();
  54127. if (!buffered.length) {
  54128. // return true if the playhead reached the absolute end of the playlist
  54129. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  54130. }
  54131. const bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  54132. // end of playlist
  54133. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  54134. }
  54135. /**
  54136. * Exclude a playlist for a set amount of time, making it unavailable for selection by
  54137. * the rendition selection algorithm, then force a new playlist (rendition) selection.
  54138. *
  54139. * @param {Object=} playlistToExclude
  54140. * the playlist to exclude, defaults to the currently selected playlist
  54141. * @param {Object=} error
  54142. * an optional error
  54143. * @param {number=} playlistExclusionDuration
  54144. * an optional number of seconds to exclude the playlist
  54145. */
  54146. excludePlaylist({
  54147. playlistToExclude = this.mainPlaylistLoader_.media(),
  54148. error = {},
  54149. playlistExclusionDuration
  54150. }) {
  54151. // If the `error` was generated by the playlist loader, it will contain
  54152. // the playlist we were trying to load (but failed) and that should be
  54153. // excluded instead of the currently selected playlist which is likely
  54154. // out-of-date in this scenario
  54155. playlistToExclude = playlistToExclude || this.mainPlaylistLoader_.media();
  54156. playlistExclusionDuration = playlistExclusionDuration || error.playlistExclusionDuration || this.playlistExclusionDuration; // If there is no current playlist, then an error occurred while we were
  54157. // trying to load the main OR while we were disposing of the tech
  54158. if (!playlistToExclude) {
  54159. this.error = error;
  54160. if (this.mediaSource.readyState !== 'open') {
  54161. this.trigger('error');
  54162. } else {
  54163. this.sourceUpdater_.endOfStream('network');
  54164. }
  54165. return;
  54166. }
  54167. playlistToExclude.playlistErrors_++;
  54168. const playlists = this.mainPlaylistLoader_.main.playlists;
  54169. const enabledPlaylists = playlists.filter(isEnabled);
  54170. const isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === playlistToExclude; // Don't exclude the only playlist unless it was excluded
  54171. // forever
  54172. if (playlists.length === 1 && playlistExclusionDuration !== Infinity) {
  54173. videojs.log.warn(`Problem encountered with playlist ${playlistToExclude.id}. ` + 'Trying again since it is the only playlist.');
  54174. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  54175. return this.mainPlaylistLoader_.load(isFinalRendition);
  54176. }
  54177. if (isFinalRendition) {
  54178. // Since we're on the final non-excluded playlist, and we're about to exclude
  54179. // it, instead of erring the player or retrying this playlist, clear out the current
  54180. // exclusion list. This allows other playlists to be attempted in case any have been
  54181. // fixed.
  54182. let reincluded = false;
  54183. playlists.forEach(playlist => {
  54184. // skip current playlist which is about to be excluded
  54185. if (playlist === playlistToExclude) {
  54186. return;
  54187. }
  54188. const excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  54189. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  54190. reincluded = true;
  54191. delete playlist.excludeUntil;
  54192. }
  54193. });
  54194. if (reincluded) {
  54195. 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
  54196. // playlist. This is needed for users relying on the retryplaylist event to catch a
  54197. // case where the player might be stuck and looping through "dead" playlists.
  54198. this.tech_.trigger('retryplaylist');
  54199. }
  54200. } // Exclude this playlist
  54201. let excludeUntil;
  54202. if (playlistToExclude.playlistErrors_ > this.maxPlaylistRetries) {
  54203. excludeUntil = Infinity;
  54204. } else {
  54205. excludeUntil = Date.now() + playlistExclusionDuration * 1000;
  54206. }
  54207. playlistToExclude.excludeUntil = excludeUntil;
  54208. if (error.reason) {
  54209. playlistToExclude.lastExcludeReason_ = error.reason;
  54210. }
  54211. this.tech_.trigger('excludeplaylist');
  54212. this.tech_.trigger({
  54213. type: 'usage',
  54214. name: 'vhs-rendition-excluded'
  54215. }); // TODO: only load a new playlist if we're excluding the current playlist
  54216. // If this function was called with a playlist that's not the current active playlist
  54217. // (e.g., media().id !== playlistToExclude.id),
  54218. // then a new playlist should not be selected and loaded, as there's nothing wrong with the current playlist.
  54219. const nextPlaylist = this.selectPlaylist();
  54220. if (!nextPlaylist) {
  54221. this.error = 'Playback cannot continue. No available working or supported playlists.';
  54222. this.trigger('error');
  54223. return;
  54224. }
  54225. const logFn = error.internal ? this.logger_ : videojs.log.warn;
  54226. const errorMessage = error.message ? ' ' + error.message : '';
  54227. logFn(`${error.internal ? 'Internal problem' : 'Problem'} encountered with playlist ${playlistToExclude.id}.` + `${errorMessage} Switching to playlist ${nextPlaylist.id}.`); // if audio group changed reset audio loaders
  54228. if (nextPlaylist.attributes.AUDIO !== playlistToExclude.attributes.AUDIO) {
  54229. this.delegateLoaders_('audio', ['abort', 'pause']);
  54230. } // if subtitle group changed reset subtitle loaders
  54231. if (nextPlaylist.attributes.SUBTITLES !== playlistToExclude.attributes.SUBTITLES) {
  54232. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  54233. }
  54234. this.delegateLoaders_('main', ['abort', 'pause']);
  54235. const delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  54236. 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
  54237. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  54238. }
  54239. /**
  54240. * Pause all segment/playlist loaders
  54241. */
  54242. pauseLoading() {
  54243. this.delegateLoaders_('all', ['abort', 'pause']);
  54244. this.stopABRTimer_();
  54245. }
  54246. /**
  54247. * Call a set of functions in order on playlist loaders, segment loaders,
  54248. * or both types of loaders.
  54249. *
  54250. * @param {string} filter
  54251. * Filter loaders that should call fnNames using a string. Can be:
  54252. * * all - run on all loaders
  54253. * * audio - run on all audio loaders
  54254. * * subtitle - run on all subtitle loaders
  54255. * * main - run on the main loaders
  54256. *
  54257. * @param {Array|string} fnNames
  54258. * A string or array of function names to call.
  54259. */
  54260. delegateLoaders_(filter, fnNames) {
  54261. const loaders = [];
  54262. const dontFilterPlaylist = filter === 'all';
  54263. if (dontFilterPlaylist || filter === 'main') {
  54264. loaders.push(this.mainPlaylistLoader_);
  54265. }
  54266. const mediaTypes = [];
  54267. if (dontFilterPlaylist || filter === 'audio') {
  54268. mediaTypes.push('AUDIO');
  54269. }
  54270. if (dontFilterPlaylist || filter === 'subtitle') {
  54271. mediaTypes.push('CLOSED-CAPTIONS');
  54272. mediaTypes.push('SUBTITLES');
  54273. }
  54274. mediaTypes.forEach(mediaType => {
  54275. const loader = this.mediaTypes_[mediaType] && this.mediaTypes_[mediaType].activePlaylistLoader;
  54276. if (loader) {
  54277. loaders.push(loader);
  54278. }
  54279. });
  54280. ['main', 'audio', 'subtitle'].forEach(name => {
  54281. const loader = this[`${name}SegmentLoader_`];
  54282. if (loader && (filter === name || filter === 'all')) {
  54283. loaders.push(loader);
  54284. }
  54285. });
  54286. loaders.forEach(loader => fnNames.forEach(fnName => {
  54287. if (typeof loader[fnName] === 'function') {
  54288. loader[fnName]();
  54289. }
  54290. }));
  54291. }
  54292. /**
  54293. * set the current time on all segment loaders
  54294. *
  54295. * @param {TimeRange} currentTime the current time to set
  54296. * @return {TimeRange} the current time
  54297. */
  54298. setCurrentTime(currentTime) {
  54299. const buffered = findRange(this.tech_.buffered(), currentTime);
  54300. if (!(this.mainPlaylistLoader_ && this.mainPlaylistLoader_.media())) {
  54301. // return immediately if the metadata is not ready yet
  54302. return 0;
  54303. } // it's clearly an edge-case but don't thrown an error if asked to
  54304. // seek within an empty playlist
  54305. if (!this.mainPlaylistLoader_.media().segments) {
  54306. return 0;
  54307. } // if the seek location is already buffered, continue buffering as usual
  54308. if (buffered && buffered.length) {
  54309. return currentTime;
  54310. } // cancel outstanding requests so we begin buffering at the new
  54311. // location
  54312. this.mainSegmentLoader_.resetEverything();
  54313. this.mainSegmentLoader_.abort();
  54314. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  54315. this.audioSegmentLoader_.resetEverything();
  54316. this.audioSegmentLoader_.abort();
  54317. }
  54318. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  54319. this.subtitleSegmentLoader_.resetEverything();
  54320. this.subtitleSegmentLoader_.abort();
  54321. } // start segment loader loading in case they are paused
  54322. this.load();
  54323. }
  54324. /**
  54325. * get the current duration
  54326. *
  54327. * @return {TimeRange} the duration
  54328. */
  54329. duration() {
  54330. if (!this.mainPlaylistLoader_) {
  54331. return 0;
  54332. }
  54333. const media = this.mainPlaylistLoader_.media();
  54334. if (!media) {
  54335. // no playlists loaded yet, so can't determine a duration
  54336. return 0;
  54337. } // Don't rely on the media source for duration in the case of a live playlist since
  54338. // setting the native MediaSource's duration to infinity ends up with consequences to
  54339. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  54340. //
  54341. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  54342. // however, few browsers have support for setLiveSeekableRange()
  54343. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  54344. //
  54345. // Until a time when the duration of the media source can be set to infinity, and a
  54346. // seekable range specified across browsers, just return Infinity.
  54347. if (!media.endList) {
  54348. return Infinity;
  54349. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  54350. // available). If it's not available, fall back to a playlist-calculated estimate.
  54351. if (this.mediaSource) {
  54352. return this.mediaSource.duration;
  54353. }
  54354. return Vhs$1.Playlist.duration(media);
  54355. }
  54356. /**
  54357. * check the seekable range
  54358. *
  54359. * @return {TimeRange} the seekable range
  54360. */
  54361. seekable() {
  54362. return this.seekable_;
  54363. }
  54364. onSyncInfoUpdate_() {
  54365. let audioSeekable; // TODO check for creation of both source buffers before updating seekable
  54366. //
  54367. // A fix was made to this function where a check for
  54368. // this.sourceUpdater_.hasCreatedSourceBuffers
  54369. // was added to ensure that both source buffers were created before seekable was
  54370. // updated. However, it originally had a bug where it was checking for a true and
  54371. // returning early instead of checking for false. Setting it to check for false to
  54372. // return early though created other issues. A call to play() would check for seekable
  54373. // end without verifying that a seekable range was present. In addition, even checking
  54374. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  54375. // due to a media update calling load on the segment loaders, skipping a seek to live,
  54376. // thereby starting live streams at the beginning of the stream rather than at the end.
  54377. //
  54378. // This conditional should be fixed to wait for the creation of two source buffers at
  54379. // the same time as the other sections of code are fixed to properly seek to live and
  54380. // not throw an error due to checking for a seekable end when no seekable range exists.
  54381. //
  54382. // For now, fall back to the older behavior, with the understanding that the seekable
  54383. // range may not be completely correct, leading to a suboptimal initial live point.
  54384. if (!this.mainPlaylistLoader_) {
  54385. return;
  54386. }
  54387. let media = this.mainPlaylistLoader_.media();
  54388. if (!media) {
  54389. return;
  54390. }
  54391. let expired = this.syncController_.getExpiredTime(media, this.duration());
  54392. if (expired === null) {
  54393. // not enough information to update seekable
  54394. return;
  54395. }
  54396. const main = this.mainPlaylistLoader_.main;
  54397. const mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  54398. if (mainSeekable.length === 0) {
  54399. return;
  54400. }
  54401. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  54402. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  54403. expired = this.syncController_.getExpiredTime(media, this.duration());
  54404. if (expired === null) {
  54405. return;
  54406. }
  54407. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  54408. if (audioSeekable.length === 0) {
  54409. return;
  54410. }
  54411. }
  54412. let oldEnd;
  54413. let oldStart;
  54414. if (this.seekable_ && this.seekable_.length) {
  54415. oldEnd = this.seekable_.end(0);
  54416. oldStart = this.seekable_.start(0);
  54417. }
  54418. if (!audioSeekable) {
  54419. // seekable has been calculated based on buffering video data so it
  54420. // can be returned directly
  54421. this.seekable_ = mainSeekable;
  54422. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  54423. // seekables are pretty far off, rely on main
  54424. this.seekable_ = mainSeekable;
  54425. } else {
  54426. 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)]]);
  54427. } // seekable is the same as last time
  54428. if (this.seekable_ && this.seekable_.length) {
  54429. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  54430. return;
  54431. }
  54432. }
  54433. this.logger_(`seekable updated [${printableRange(this.seekable_)}]`);
  54434. this.tech_.trigger('seekablechanged');
  54435. }
  54436. /**
  54437. * Update the player duration
  54438. */
  54439. updateDuration(isLive) {
  54440. if (this.updateDuration_) {
  54441. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  54442. this.updateDuration_ = null;
  54443. }
  54444. if (this.mediaSource.readyState !== 'open') {
  54445. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  54446. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  54447. return;
  54448. }
  54449. if (isLive) {
  54450. const seekable = this.seekable();
  54451. if (!seekable.length) {
  54452. return;
  54453. } // Even in the case of a live playlist, the native MediaSource's duration should not
  54454. // be set to Infinity (even though this would be expected for a live playlist), since
  54455. // setting the native MediaSource's duration to infinity ends up with consequences to
  54456. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  54457. //
  54458. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  54459. // however, few browsers have support for setLiveSeekableRange()
  54460. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  54461. //
  54462. // Until a time when the duration of the media source can be set to infinity, and a
  54463. // seekable range specified across browsers, the duration should be greater than or
  54464. // equal to the last possible seekable value.
  54465. // MediaSource duration starts as NaN
  54466. // It is possible (and probable) that this case will never be reached for many
  54467. // sources, since the MediaSource reports duration as the highest value without
  54468. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  54469. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  54470. // time will be between 0 and 100, the native media source may report the duration
  54471. // as 200. However, since we report duration separate from the media source (as
  54472. // Infinity), and as long as the native media source duration value is greater than
  54473. // our reported seekable range, seeks will work as expected. The large number as
  54474. // duration for live is actually a strategy used by some players to work around the
  54475. // issue of live seekable ranges cited above.
  54476. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  54477. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  54478. }
  54479. return;
  54480. }
  54481. const buffered = this.tech_.buffered();
  54482. let duration = Vhs$1.Playlist.duration(this.mainPlaylistLoader_.media());
  54483. if (buffered.length > 0) {
  54484. duration = Math.max(duration, buffered.end(buffered.length - 1));
  54485. }
  54486. if (this.mediaSource.duration !== duration) {
  54487. this.sourceUpdater_.setDuration(duration);
  54488. }
  54489. }
  54490. /**
  54491. * dispose of the PlaylistController and everything
  54492. * that it controls
  54493. */
  54494. dispose() {
  54495. this.trigger('dispose');
  54496. this.decrypter_.terminate();
  54497. this.mainPlaylistLoader_.dispose();
  54498. this.mainSegmentLoader_.dispose();
  54499. if (this.loadOnPlay_) {
  54500. this.tech_.off('play', this.loadOnPlay_);
  54501. }
  54502. ['AUDIO', 'SUBTITLES'].forEach(type => {
  54503. const groups = this.mediaTypes_[type].groups;
  54504. for (const id in groups) {
  54505. groups[id].forEach(group => {
  54506. if (group.playlistLoader) {
  54507. group.playlistLoader.dispose();
  54508. }
  54509. });
  54510. }
  54511. });
  54512. this.audioSegmentLoader_.dispose();
  54513. this.subtitleSegmentLoader_.dispose();
  54514. this.sourceUpdater_.dispose();
  54515. this.timelineChangeController_.dispose();
  54516. this.stopABRTimer_();
  54517. if (this.updateDuration_) {
  54518. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  54519. }
  54520. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  54521. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  54522. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  54523. this.off();
  54524. }
  54525. /**
  54526. * return the main playlist object if we have one
  54527. *
  54528. * @return {Object} the main playlist object that we parsed
  54529. */
  54530. main() {
  54531. return this.mainPlaylistLoader_.main;
  54532. }
  54533. /**
  54534. * return the currently selected playlist
  54535. *
  54536. * @return {Object} the currently selected playlist object that we parsed
  54537. */
  54538. media() {
  54539. // playlist loader will not return media if it has not been fully loaded
  54540. return this.mainPlaylistLoader_.media() || this.initialMedia_;
  54541. }
  54542. areMediaTypesKnown_() {
  54543. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  54544. const hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  54545. // otherwise check on the segment loader.
  54546. const hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  54547. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  54548. return false;
  54549. }
  54550. return true;
  54551. }
  54552. getCodecsOrExclude_() {
  54553. const media = {
  54554. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  54555. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  54556. };
  54557. const playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  54558. media.video = media.main;
  54559. const playlistCodecs = codecsForPlaylist(this.main(), playlist);
  54560. const codecs = {};
  54561. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  54562. if (media.main.hasVideo) {
  54563. codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
  54564. }
  54565. if (media.main.isMuxed) {
  54566. codecs.video += `,${playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC}`;
  54567. }
  54568. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  54569. codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
  54570. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  54571. } // no codecs, no playback.
  54572. if (!codecs.audio && !codecs.video) {
  54573. this.excludePlaylist({
  54574. playlistToExclude: playlist,
  54575. error: {
  54576. message: 'Could not determine codecs for playlist.'
  54577. },
  54578. playlistExclusionDuration: Infinity
  54579. });
  54580. return;
  54581. } // fmp4 relies on browser support, while ts relies on muxer support
  54582. const supportFunction = (isFmp4, codec) => isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
  54583. const unsupportedCodecs = {};
  54584. let unsupportedAudio;
  54585. ['video', 'audio'].forEach(function (type) {
  54586. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  54587. const supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  54588. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  54589. unsupportedCodecs[supporter].push(codecs[type]);
  54590. if (type === 'audio') {
  54591. unsupportedAudio = supporter;
  54592. }
  54593. }
  54594. });
  54595. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  54596. const audioGroup = playlist.attributes.AUDIO;
  54597. this.main().playlists.forEach(variant => {
  54598. const variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  54599. if (variantAudioGroup === audioGroup && variant !== playlist) {
  54600. variant.excludeUntil = Infinity;
  54601. }
  54602. });
  54603. this.logger_(`excluding audio group ${audioGroup} as ${unsupportedAudio} does not support codec(s): "${codecs.audio}"`);
  54604. } // if we have any unsupported codecs exclude this playlist.
  54605. if (Object.keys(unsupportedCodecs).length) {
  54606. const message = Object.keys(unsupportedCodecs).reduce((acc, supporter) => {
  54607. if (acc) {
  54608. acc += ', ';
  54609. }
  54610. acc += `${supporter} does not support codec(s): "${unsupportedCodecs[supporter].join(',')}"`;
  54611. return acc;
  54612. }, '') + '.';
  54613. this.excludePlaylist({
  54614. playlistToExclude: playlist,
  54615. error: {
  54616. internal: true,
  54617. message
  54618. },
  54619. playlistExclusionDuration: Infinity
  54620. });
  54621. return;
  54622. } // check if codec switching is happening
  54623. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  54624. const switchMessages = [];
  54625. ['video', 'audio'].forEach(type => {
  54626. const newCodec = (parseCodecs(this.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  54627. const oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
  54628. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  54629. switchMessages.push(`"${this.sourceUpdater_.codecs[type]}" -> "${codecs[type]}"`);
  54630. }
  54631. });
  54632. if (switchMessages.length) {
  54633. this.excludePlaylist({
  54634. playlistToExclude: playlist,
  54635. error: {
  54636. message: `Codec switching not supported: ${switchMessages.join(', ')}.`,
  54637. internal: true
  54638. },
  54639. playlistExclusionDuration: Infinity
  54640. });
  54641. return;
  54642. }
  54643. } // TODO: when using the muxer shouldn't we just return
  54644. // the codecs that the muxer outputs?
  54645. return codecs;
  54646. }
  54647. /**
  54648. * Create source buffers and exlude any incompatible renditions.
  54649. *
  54650. * @private
  54651. */
  54652. tryToCreateSourceBuffers_() {
  54653. // media source is not ready yet or sourceBuffers are already
  54654. // created.
  54655. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  54656. return;
  54657. }
  54658. if (!this.areMediaTypesKnown_()) {
  54659. return;
  54660. }
  54661. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  54662. if (!codecs) {
  54663. return;
  54664. }
  54665. this.sourceUpdater_.createSourceBuffers(codecs);
  54666. const codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  54667. this.excludeIncompatibleVariants_(codecString);
  54668. }
  54669. /**
  54670. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  54671. */
  54672. excludeUnsupportedVariants_() {
  54673. const playlists = this.main().playlists;
  54674. const ids = []; // TODO: why don't we have a property to loop through all
  54675. // playlist? Why did we ever mix indexes and keys?
  54676. Object.keys(playlists).forEach(key => {
  54677. const variant = playlists[key]; // check if we already processed this playlist.
  54678. if (ids.indexOf(variant.id) !== -1) {
  54679. return;
  54680. }
  54681. ids.push(variant.id);
  54682. const codecs = codecsForPlaylist(this.main, variant);
  54683. const unsupported = [];
  54684. if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
  54685. unsupported.push(`audio codec ${codecs.audio}`);
  54686. }
  54687. if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
  54688. unsupported.push(`video codec ${codecs.video}`);
  54689. }
  54690. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  54691. unsupported.push(`text codec ${codecs.text}`);
  54692. }
  54693. if (unsupported.length) {
  54694. variant.excludeUntil = Infinity;
  54695. this.logger_(`excluding ${variant.id} for unsupported: ${unsupported.join(', ')}`);
  54696. }
  54697. });
  54698. }
  54699. /**
  54700. * Exclude playlists that are known to be codec or
  54701. * stream-incompatible with the SourceBuffer configuration. For
  54702. * instance, Media Source Extensions would cause the video element to
  54703. * stall waiting for video data if you switched from a variant with
  54704. * video and audio to an audio-only one.
  54705. *
  54706. * @param {Object} media a media playlist compatible with the current
  54707. * set of SourceBuffers. Variants in the current main playlist that
  54708. * do not appear to have compatible codec or stream configurations
  54709. * will be excluded from the default playlist selection algorithm
  54710. * indefinitely.
  54711. * @private
  54712. */
  54713. excludeIncompatibleVariants_(codecString) {
  54714. const ids = [];
  54715. const playlists = this.main().playlists;
  54716. const codecs = unwrapCodecList(parseCodecs(codecString));
  54717. const codecCount_ = codecCount(codecs);
  54718. const videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
  54719. const audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
  54720. Object.keys(playlists).forEach(key => {
  54721. const variant = playlists[key]; // check if we already processed this playlist.
  54722. // or it if it is already excluded forever.
  54723. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  54724. return;
  54725. }
  54726. ids.push(variant.id);
  54727. const exclusionReasons = []; // get codecs from the playlist for this variant
  54728. const variantCodecs = codecsForPlaylist(this.mainPlaylistLoader_.main, variant);
  54729. const variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  54730. // variant is incompatible. Wait for mux.js to probe
  54731. if (!variantCodecs.audio && !variantCodecs.video) {
  54732. return;
  54733. } // TODO: we can support this by removing the
  54734. // old media source and creating a new one, but it will take some work.
  54735. // The number of streams cannot change
  54736. if (variantCodecCount !== codecCount_) {
  54737. exclusionReasons.push(`codec count "${variantCodecCount}" !== "${codecCount_}"`);
  54738. } // only exclude playlists by codec change, if codecs cannot switch
  54739. // during playback.
  54740. if (!this.sourceUpdater_.canChangeType()) {
  54741. const variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
  54742. const variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  54743. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  54744. exclusionReasons.push(`video codec "${variantVideoDetails.type}" !== "${videoDetails.type}"`);
  54745. } // the audio codec cannot change
  54746. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  54747. exclusionReasons.push(`audio codec "${variantAudioDetails.type}" !== "${audioDetails.type}"`);
  54748. }
  54749. }
  54750. if (exclusionReasons.length) {
  54751. variant.excludeUntil = Infinity;
  54752. this.logger_(`excluding ${variant.id}: ${exclusionReasons.join(' && ')}`);
  54753. }
  54754. });
  54755. }
  54756. updateAdCues_(media) {
  54757. let offset = 0;
  54758. const seekable = this.seekable();
  54759. if (seekable.length) {
  54760. offset = seekable.start(0);
  54761. }
  54762. updateAdCues(media, this.cueTagsTrack_, offset);
  54763. }
  54764. /**
  54765. * Calculates the desired forward buffer length based on current time
  54766. *
  54767. * @return {number} Desired forward buffer length in seconds
  54768. */
  54769. goalBufferLength() {
  54770. const currentTime = this.tech_.currentTime();
  54771. const initial = Config.GOAL_BUFFER_LENGTH;
  54772. const rate = Config.GOAL_BUFFER_LENGTH_RATE;
  54773. const max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  54774. return Math.min(initial + currentTime * rate, max);
  54775. }
  54776. /**
  54777. * Calculates the desired buffer low water line based on current time
  54778. *
  54779. * @return {number} Desired buffer low water line in seconds
  54780. */
  54781. bufferLowWaterLine() {
  54782. const currentTime = this.tech_.currentTime();
  54783. const initial = Config.BUFFER_LOW_WATER_LINE;
  54784. const rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  54785. const max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  54786. const newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  54787. return Math.min(initial + currentTime * rate, this.bufferBasedABR ? newMax : max);
  54788. }
  54789. bufferHighWaterLine() {
  54790. return Config.BUFFER_HIGH_WATER_LINE;
  54791. }
  54792. }
  54793. /**
  54794. * Returns a function that acts as the Enable/disable playlist function.
  54795. *
  54796. * @param {PlaylistLoader} loader - The main playlist loader
  54797. * @param {string} playlistID - id of the playlist
  54798. * @param {Function} changePlaylistFn - A function to be called after a
  54799. * playlist's enabled-state has been changed. Will NOT be called if a
  54800. * playlist's enabled-state is unchanged
  54801. * @param {boolean=} enable - Value to set the playlist enabled-state to
  54802. * or if undefined returns the current enabled-state for the playlist
  54803. * @return {Function} Function for setting/getting enabled
  54804. */
  54805. const enableFunction = (loader, playlistID, changePlaylistFn) => enable => {
  54806. const playlist = loader.main.playlists[playlistID];
  54807. const incompatible = isIncompatible(playlist);
  54808. const currentlyEnabled = isEnabled(playlist);
  54809. if (typeof enable === 'undefined') {
  54810. return currentlyEnabled;
  54811. }
  54812. if (enable) {
  54813. delete playlist.disabled;
  54814. } else {
  54815. playlist.disabled = true;
  54816. }
  54817. if (enable !== currentlyEnabled && !incompatible) {
  54818. // Ensure the outside world knows about our changes
  54819. changePlaylistFn();
  54820. if (enable) {
  54821. loader.trigger('renditionenabled');
  54822. } else {
  54823. loader.trigger('renditiondisabled');
  54824. }
  54825. }
  54826. return enable;
  54827. };
  54828. /**
  54829. * The representation object encapsulates the publicly visible information
  54830. * in a media playlist along with a setter/getter-type function (enabled)
  54831. * for changing the enabled-state of a particular playlist entry
  54832. *
  54833. * @class Representation
  54834. */
  54835. class Representation {
  54836. constructor(vhsHandler, playlist, id) {
  54837. const {
  54838. playlistController_: pc
  54839. } = vhsHandler;
  54840. const qualityChangeFunction = pc.fastQualityChange_.bind(pc); // some playlist attributes are optional
  54841. if (playlist.attributes) {
  54842. const resolution = playlist.attributes.RESOLUTION;
  54843. this.width = resolution && resolution.width;
  54844. this.height = resolution && resolution.height;
  54845. this.bandwidth = playlist.attributes.BANDWIDTH;
  54846. this.frameRate = playlist.attributes['FRAME-RATE'];
  54847. }
  54848. this.codecs = codecsForPlaylist(pc.main(), playlist);
  54849. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  54850. // within the main playlist
  54851. this.id = id; // Partially-apply the enableFunction to create a playlist-
  54852. // specific variant
  54853. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  54854. }
  54855. }
  54856. /**
  54857. * A mixin function that adds the `representations` api to an instance
  54858. * of the VhsHandler class
  54859. *
  54860. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  54861. * representation API into
  54862. */
  54863. const renditionSelectionMixin = function (vhsHandler) {
  54864. // Add a single API-specific function to the VhsHandler instance
  54865. vhsHandler.representations = () => {
  54866. const main = vhsHandler.playlistController_.main();
  54867. const playlists = isAudioOnly(main) ? vhsHandler.playlistController_.getAudioTrackPlaylists_() : main.playlists;
  54868. if (!playlists) {
  54869. return [];
  54870. }
  54871. return playlists.filter(media => !isIncompatible(media)).map((e, i) => new Representation(vhsHandler, e, e.id));
  54872. };
  54873. };
  54874. /**
  54875. * @file playback-watcher.js
  54876. *
  54877. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  54878. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  54879. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  54880. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  54881. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  54882. */
  54883. const timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  54884. /**
  54885. * @class PlaybackWatcher
  54886. */
  54887. class PlaybackWatcher {
  54888. /**
  54889. * Represents an PlaybackWatcher object.
  54890. *
  54891. * @class
  54892. * @param {Object} options an object that includes the tech and settings
  54893. */
  54894. constructor(options) {
  54895. this.playlistController_ = options.playlistController;
  54896. this.tech_ = options.tech;
  54897. this.seekable = options.seekable;
  54898. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  54899. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  54900. this.media = options.media;
  54901. this.consecutiveUpdates = 0;
  54902. this.lastRecordedTime = null;
  54903. this.checkCurrentTimeTimeout_ = null;
  54904. this.logger_ = logger('PlaybackWatcher');
  54905. this.logger_('initialize');
  54906. const playHandler = () => this.monitorCurrentTime_();
  54907. const canPlayHandler = () => this.monitorCurrentTime_();
  54908. const waitingHandler = () => this.techWaiting_();
  54909. const cancelTimerHandler = () => this.resetTimeUpdate_();
  54910. const pc = this.playlistController_;
  54911. const loaderTypes = ['main', 'subtitle', 'audio'];
  54912. const loaderChecks = {};
  54913. loaderTypes.forEach(type => {
  54914. loaderChecks[type] = {
  54915. reset: () => this.resetSegmentDownloads_(type),
  54916. updateend: () => this.checkSegmentDownloads_(type)
  54917. };
  54918. pc[`${type}SegmentLoader_`].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  54919. // isn't changing we want to reset. We cannot assume that the new rendition
  54920. // will also be stalled, until after new appends.
  54921. pc[`${type}SegmentLoader_`].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  54922. // This prevents one segment playlists (single vtt or single segment content)
  54923. // from being detected as stalling. As the buffer will not change in those cases, since
  54924. // the buffer is the entire video duration.
  54925. this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  54926. });
  54927. /**
  54928. * We check if a seek was into a gap through the following steps:
  54929. * 1. We get a seeking event and we do not get a seeked event. This means that
  54930. * a seek was attempted but not completed.
  54931. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  54932. * removed everything from our buffer and appended a segment, and should be ready
  54933. * to check for gaps.
  54934. */
  54935. const setSeekingHandlers = fn => {
  54936. ['main', 'audio'].forEach(type => {
  54937. pc[`${type}SegmentLoader_`][fn]('appended', this.seekingAppendCheck_);
  54938. });
  54939. };
  54940. this.seekingAppendCheck_ = () => {
  54941. if (this.fixesBadSeeks_()) {
  54942. this.consecutiveUpdates = 0;
  54943. this.lastRecordedTime = this.tech_.currentTime();
  54944. setSeekingHandlers('off');
  54945. }
  54946. };
  54947. this.clearSeekingAppendCheck_ = () => setSeekingHandlers('off');
  54948. this.watchForBadSeeking_ = () => {
  54949. this.clearSeekingAppendCheck_();
  54950. setSeekingHandlers('on');
  54951. };
  54952. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  54953. this.tech_.on('seeking', this.watchForBadSeeking_);
  54954. this.tech_.on('waiting', waitingHandler);
  54955. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  54956. this.tech_.on('canplay', canPlayHandler);
  54957. /*
  54958. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  54959. is surfaced in one of two ways:
  54960. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  54961. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  54962. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  54963. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  54964. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  54965. even if the player is in a playing state
  54966. */
  54967. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  54968. this.dispose = () => {
  54969. this.clearSeekingAppendCheck_();
  54970. this.logger_('dispose');
  54971. this.tech_.off('waiting', waitingHandler);
  54972. this.tech_.off(timerCancelEvents, cancelTimerHandler);
  54973. this.tech_.off('canplay', canPlayHandler);
  54974. this.tech_.off('play', playHandler);
  54975. this.tech_.off('seeking', this.watchForBadSeeking_);
  54976. this.tech_.off('seeked', this.clearSeekingAppendCheck_);
  54977. loaderTypes.forEach(type => {
  54978. pc[`${type}SegmentLoader_`].off('appendsdone', loaderChecks[type].updateend);
  54979. pc[`${type}SegmentLoader_`].off('playlistupdate', loaderChecks[type].reset);
  54980. this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  54981. });
  54982. if (this.checkCurrentTimeTimeout_) {
  54983. window.clearTimeout(this.checkCurrentTimeTimeout_);
  54984. }
  54985. this.resetTimeUpdate_();
  54986. };
  54987. }
  54988. /**
  54989. * Periodically check current time to see if playback stopped
  54990. *
  54991. * @private
  54992. */
  54993. monitorCurrentTime_() {
  54994. this.checkCurrentTime_();
  54995. if (this.checkCurrentTimeTimeout_) {
  54996. window.clearTimeout(this.checkCurrentTimeTimeout_);
  54997. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  54998. this.checkCurrentTimeTimeout_ = window.setTimeout(this.monitorCurrentTime_.bind(this), 250);
  54999. }
  55000. /**
  55001. * Reset stalled download stats for a specific type of loader
  55002. *
  55003. * @param {string} type
  55004. * The segment loader type to check.
  55005. *
  55006. * @listens SegmentLoader#playlistupdate
  55007. * @listens Tech#seeking
  55008. * @listens Tech#seeked
  55009. */
  55010. resetSegmentDownloads_(type) {
  55011. const loader = this.playlistController_[`${type}SegmentLoader_`];
  55012. if (this[`${type}StalledDownloads_`] > 0) {
  55013. this.logger_(`resetting possible stalled download count for ${type} loader`);
  55014. }
  55015. this[`${type}StalledDownloads_`] = 0;
  55016. this[`${type}Buffered_`] = loader.buffered_();
  55017. }
  55018. /**
  55019. * Checks on every segment `appendsdone` to see
  55020. * if segment appends are making progress. If they are not
  55021. * and we are still downloading bytes. We exclude the playlist.
  55022. *
  55023. * @param {string} type
  55024. * The segment loader type to check.
  55025. *
  55026. * @listens SegmentLoader#appendsdone
  55027. */
  55028. checkSegmentDownloads_(type) {
  55029. const pc = this.playlistController_;
  55030. const loader = pc[`${type}SegmentLoader_`];
  55031. const buffered = loader.buffered_();
  55032. const isBufferedDifferent = isRangeDifferent(this[`${type}Buffered_`], buffered);
  55033. this[`${type}Buffered_`] = buffered; // if another watcher is going to fix the issue or
  55034. // the buffered value for this loader changed
  55035. // appends are working
  55036. if (isBufferedDifferent) {
  55037. this.resetSegmentDownloads_(type);
  55038. return;
  55039. }
  55040. this[`${type}StalledDownloads_`]++;
  55041. this.logger_(`found #${this[`${type}StalledDownloads_`]} ${type} appends that did not increase buffer (possible stalled download)`, {
  55042. playlistId: loader.playlist_ && loader.playlist_.id,
  55043. buffered: timeRangesToArray(buffered)
  55044. }); // after 10 possibly stalled appends with no reset, exclude
  55045. if (this[`${type}StalledDownloads_`] < 10) {
  55046. return;
  55047. }
  55048. this.logger_(`${type} loader stalled download exclusion`);
  55049. this.resetSegmentDownloads_(type);
  55050. this.tech_.trigger({
  55051. type: 'usage',
  55052. name: `vhs-${type}-download-exclusion`
  55053. });
  55054. if (type === 'subtitle') {
  55055. return;
  55056. } // TODO: should we exclude audio tracks rather than main tracks
  55057. // when type is audio?
  55058. pc.excludePlaylist({
  55059. error: {
  55060. message: `Excessive ${type} segment downloading detected.`
  55061. },
  55062. playlistExclusionDuration: Infinity
  55063. });
  55064. }
  55065. /**
  55066. * The purpose of this function is to emulate the "waiting" event on
  55067. * browsers that do not emit it when they are waiting for more
  55068. * data to continue playback
  55069. *
  55070. * @private
  55071. */
  55072. checkCurrentTime_() {
  55073. if (this.tech_.paused() || this.tech_.seeking()) {
  55074. return;
  55075. }
  55076. const currentTime = this.tech_.currentTime();
  55077. const buffered = this.tech_.buffered();
  55078. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  55079. // If current time is at the end of the final buffered region, then any playback
  55080. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  55081. // should fire a `waiting` event in this scenario, but due to browser and tech
  55082. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  55083. // responding to a native `waiting` event when the tech fails to emit one.
  55084. return this.techWaiting_();
  55085. }
  55086. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  55087. this.consecutiveUpdates++;
  55088. this.waiting_();
  55089. } else if (currentTime === this.lastRecordedTime) {
  55090. this.consecutiveUpdates++;
  55091. } else {
  55092. this.consecutiveUpdates = 0;
  55093. this.lastRecordedTime = currentTime;
  55094. }
  55095. }
  55096. /**
  55097. * Resets the 'timeupdate' mechanism designed to detect that we are stalled
  55098. *
  55099. * @private
  55100. */
  55101. resetTimeUpdate_() {
  55102. this.consecutiveUpdates = 0;
  55103. }
  55104. /**
  55105. * Fixes situations where there's a bad seek
  55106. *
  55107. * @return {boolean} whether an action was taken to fix the seek
  55108. * @private
  55109. */
  55110. fixesBadSeeks_() {
  55111. const seeking = this.tech_.seeking();
  55112. if (!seeking) {
  55113. return false;
  55114. } // TODO: It's possible that these seekable checks should be moved out of this function
  55115. // and into a function that runs on seekablechange. It's also possible that we only need
  55116. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  55117. // seekable range.
  55118. const seekable = this.seekable();
  55119. const currentTime = this.tech_.currentTime();
  55120. const isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  55121. let seekTo;
  55122. if (isAfterSeekableRange) {
  55123. const seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  55124. seekTo = seekableEnd;
  55125. }
  55126. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  55127. const seekableStart = seekable.start(0); // sync to the beginning of the live window
  55128. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  55129. seekTo = seekableStart + (
  55130. // if the playlist is too short and the seekable range is an exact time (can
  55131. // happen in live with a 3 segment playlist), then don't use a time delta
  55132. seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
  55133. }
  55134. if (typeof seekTo !== 'undefined') {
  55135. this.logger_(`Trying to seek outside of seekable at time ${currentTime} with ` + `seekable range ${printableRange(seekable)}. Seeking to ` + `${seekTo}.`);
  55136. this.tech_.setCurrentTime(seekTo);
  55137. return true;
  55138. }
  55139. const sourceUpdater = this.playlistController_.sourceUpdater_;
  55140. const buffered = this.tech_.buffered();
  55141. const audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  55142. const videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  55143. const media = this.media(); // verify that at least two segment durations or one part duration have been
  55144. // appended before checking for a gap.
  55145. const minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been
  55146. // appended before checking for a gap.
  55147. const bufferedToCheck = [audioBuffered, videoBuffered];
  55148. for (let i = 0; i < bufferedToCheck.length; i++) {
  55149. // skip null buffered
  55150. if (!bufferedToCheck[i]) {
  55151. continue;
  55152. }
  55153. const timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part
  55154. // duration behind we haven't appended enough to call this a bad seek.
  55155. if (timeAhead < minAppendedDuration) {
  55156. return false;
  55157. }
  55158. }
  55159. const nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered
  55160. // to seek over the gap
  55161. if (nextRange.length === 0) {
  55162. return false;
  55163. }
  55164. seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
  55165. this.logger_(`Buffered region starts (${nextRange.start(0)}) ` + ` just beyond seek point (${currentTime}). Seeking to ${seekTo}.`);
  55166. this.tech_.setCurrentTime(seekTo);
  55167. return true;
  55168. }
  55169. /**
  55170. * Handler for situations when we determine the player is waiting.
  55171. *
  55172. * @private
  55173. */
  55174. waiting_() {
  55175. if (this.techWaiting_()) {
  55176. return;
  55177. } // All tech waiting checks failed. Use last resort correction
  55178. const currentTime = this.tech_.currentTime();
  55179. const buffered = this.tech_.buffered();
  55180. const currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  55181. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  55182. // currentTime is usually enough to kickstart the player. This checks that the player
  55183. // is currently within a buffered region before attempting a corrective seek.
  55184. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  55185. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  55186. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  55187. // to avoid triggering an `unknownwaiting` event when the network is slow.
  55188. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  55189. this.resetTimeUpdate_();
  55190. this.tech_.setCurrentTime(currentTime);
  55191. 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
  55192. this.tech_.trigger({
  55193. type: 'usage',
  55194. name: 'vhs-unknown-waiting'
  55195. });
  55196. return;
  55197. }
  55198. }
  55199. /**
  55200. * Handler for situations when the tech fires a `waiting` event
  55201. *
  55202. * @return {boolean}
  55203. * True if an action (or none) was needed to correct the waiting. False if no
  55204. * checks passed
  55205. * @private
  55206. */
  55207. techWaiting_() {
  55208. const seekable = this.seekable();
  55209. const currentTime = this.tech_.currentTime();
  55210. if (this.tech_.seeking()) {
  55211. // Tech is seeking or already waiting on another action, no action needed
  55212. return true;
  55213. }
  55214. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  55215. const livePoint = seekable.end(seekable.length - 1);
  55216. this.logger_(`Fell out of live window at time ${currentTime}. Seeking to ` + `live point (seekable end) ${livePoint}`);
  55217. this.resetTimeUpdate_();
  55218. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  55219. this.tech_.trigger({
  55220. type: 'usage',
  55221. name: 'vhs-live-resync'
  55222. });
  55223. return true;
  55224. }
  55225. const sourceUpdater = this.tech_.vhs.playlistController_.sourceUpdater_;
  55226. const buffered = this.tech_.buffered();
  55227. const videoUnderflow = this.videoUnderflow_({
  55228. audioBuffered: sourceUpdater.audioBuffered(),
  55229. videoBuffered: sourceUpdater.videoBuffered(),
  55230. currentTime
  55231. });
  55232. if (videoUnderflow) {
  55233. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  55234. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  55235. // allows the video to catch up to the audio position without losing any audio
  55236. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  55237. this.resetTimeUpdate_();
  55238. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  55239. this.tech_.trigger({
  55240. type: 'usage',
  55241. name: 'vhs-video-underflow'
  55242. });
  55243. return true;
  55244. }
  55245. const nextRange = findNextRange(buffered, currentTime); // check for gap
  55246. if (nextRange.length > 0) {
  55247. this.logger_(`Stopped at ${currentTime} and seeking to ${nextRange.start(0)}`);
  55248. this.resetTimeUpdate_();
  55249. this.skipTheGap_(currentTime);
  55250. return true;
  55251. } // All checks failed. Returning false to indicate failure to correct waiting
  55252. return false;
  55253. }
  55254. afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow = false) {
  55255. if (!seekable.length) {
  55256. // we can't make a solid case if there's no seekable, default to false
  55257. return false;
  55258. }
  55259. let allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  55260. const isLive = !playlist.endList;
  55261. if (isLive && allowSeeksWithinUnsafeLiveWindow) {
  55262. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  55263. }
  55264. if (currentTime > allowedEnd) {
  55265. return true;
  55266. }
  55267. return false;
  55268. }
  55269. beforeSeekableWindow_(seekable, currentTime) {
  55270. if (seekable.length &&
  55271. // can't fall before 0 and 0 seekable start identifies VOD stream
  55272. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  55273. return true;
  55274. }
  55275. return false;
  55276. }
  55277. videoUnderflow_({
  55278. videoBuffered,
  55279. audioBuffered,
  55280. currentTime
  55281. }) {
  55282. // audio only content will not have video underflow :)
  55283. if (!videoBuffered) {
  55284. return;
  55285. }
  55286. let gap; // find a gap in demuxed content.
  55287. if (videoBuffered.length && audioBuffered.length) {
  55288. // in Chrome audio will continue to play for ~3s when we run out of video
  55289. // so we have to check that the video buffer did have some buffer in the
  55290. // past.
  55291. const lastVideoRange = findRange(videoBuffered, currentTime - 3);
  55292. const videoRange = findRange(videoBuffered, currentTime);
  55293. const audioRange = findRange(audioBuffered, currentTime);
  55294. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  55295. gap = {
  55296. start: lastVideoRange.end(0),
  55297. end: audioRange.end(0)
  55298. };
  55299. } // find a gap in muxed content.
  55300. } else {
  55301. const nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  55302. // stuck in a gap due to video underflow.
  55303. if (!nextRange.length) {
  55304. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  55305. }
  55306. }
  55307. if (gap) {
  55308. this.logger_(`Encountered a gap in video from ${gap.start} to ${gap.end}. ` + `Seeking to current time ${currentTime}`);
  55309. return true;
  55310. }
  55311. return false;
  55312. }
  55313. /**
  55314. * Timer callback. If playback still has not proceeded, then we seek
  55315. * to the start of the next buffered region.
  55316. *
  55317. * @private
  55318. */
  55319. skipTheGap_(scheduledCurrentTime) {
  55320. const buffered = this.tech_.buffered();
  55321. const currentTime = this.tech_.currentTime();
  55322. const nextRange = findNextRange(buffered, currentTime);
  55323. this.resetTimeUpdate_();
  55324. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  55325. return;
  55326. }
  55327. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  55328. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  55329. this.tech_.trigger({
  55330. type: 'usage',
  55331. name: 'vhs-gap-skip'
  55332. });
  55333. }
  55334. gapFromVideoUnderflow_(buffered, currentTime) {
  55335. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  55336. // playing for ~3 seconds after the video gap starts. This is done to account for
  55337. // video buffer underflow/underrun (note that this is not done when there is audio
  55338. // buffer underflow/underrun -- in that case the video will stop as soon as it
  55339. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  55340. // video stalls). The player's time will reflect the playthrough of audio, so the
  55341. // time will appear as if we are in a buffered region, even if we are stuck in a
  55342. // "gap."
  55343. //
  55344. // Example:
  55345. // video buffer: 0 => 10.1, 10.2 => 20
  55346. // audio buffer: 0 => 20
  55347. // overall buffer: 0 => 10.1, 10.2 => 20
  55348. // current time: 13
  55349. //
  55350. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  55351. // however, the audio continued playing until it reached ~3 seconds past the gap
  55352. // (13 seconds), at which point it stops as well. Since current time is past the
  55353. // gap, findNextRange will return no ranges.
  55354. //
  55355. // To check for this issue, we see if there is a gap that starts somewhere within
  55356. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  55357. const gaps = findGaps(buffered);
  55358. for (let i = 0; i < gaps.length; i++) {
  55359. const start = gaps.start(i);
  55360. const end = gaps.end(i); // gap is starts no more than 4 seconds back
  55361. if (currentTime - start < 4 && currentTime - start > 2) {
  55362. return {
  55363. start,
  55364. end
  55365. };
  55366. }
  55367. }
  55368. return null;
  55369. }
  55370. }
  55371. const defaultOptions = {
  55372. errorInterval: 30,
  55373. getSource(next) {
  55374. const tech = this.tech({
  55375. IWillNotUseThisInPlugins: true
  55376. });
  55377. const sourceObj = tech.currentSource_ || this.currentSource();
  55378. return next(sourceObj);
  55379. }
  55380. };
  55381. /**
  55382. * Main entry point for the plugin
  55383. *
  55384. * @param {Player} player a reference to a videojs Player instance
  55385. * @param {Object} [options] an object with plugin options
  55386. * @private
  55387. */
  55388. const initPlugin = function (player, options) {
  55389. let lastCalled = 0;
  55390. let seekTo = 0;
  55391. const localOptions = merge(defaultOptions, options);
  55392. player.ready(() => {
  55393. player.trigger({
  55394. type: 'usage',
  55395. name: 'vhs-error-reload-initialized'
  55396. });
  55397. });
  55398. /**
  55399. * Player modifications to perform that must wait until `loadedmetadata`
  55400. * has been triggered
  55401. *
  55402. * @private
  55403. */
  55404. const loadedMetadataHandler = function () {
  55405. if (seekTo) {
  55406. player.currentTime(seekTo);
  55407. }
  55408. };
  55409. /**
  55410. * Set the source on the player element, play, and seek if necessary
  55411. *
  55412. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  55413. * @private
  55414. */
  55415. const setSource = function (sourceObj) {
  55416. if (sourceObj === null || sourceObj === undefined) {
  55417. return;
  55418. }
  55419. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  55420. player.one('loadedmetadata', loadedMetadataHandler);
  55421. player.src(sourceObj);
  55422. player.trigger({
  55423. type: 'usage',
  55424. name: 'vhs-error-reload'
  55425. });
  55426. player.play();
  55427. };
  55428. /**
  55429. * Attempt to get a source from either the built-in getSource function
  55430. * or a custom function provided via the options
  55431. *
  55432. * @private
  55433. */
  55434. const errorHandler = function () {
  55435. // Do not attempt to reload the source if a source-reload occurred before
  55436. // 'errorInterval' time has elapsed since the last source-reload
  55437. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  55438. player.trigger({
  55439. type: 'usage',
  55440. name: 'vhs-error-reload-canceled'
  55441. });
  55442. return;
  55443. }
  55444. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  55445. videojs.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  55446. return;
  55447. }
  55448. lastCalled = Date.now();
  55449. return localOptions.getSource.call(player, setSource);
  55450. };
  55451. /**
  55452. * Unbind any event handlers that were bound by the plugin
  55453. *
  55454. * @private
  55455. */
  55456. const cleanupEvents = function () {
  55457. player.off('loadedmetadata', loadedMetadataHandler);
  55458. player.off('error', errorHandler);
  55459. player.off('dispose', cleanupEvents);
  55460. };
  55461. /**
  55462. * Cleanup before re-initializing the plugin
  55463. *
  55464. * @param {Object} [newOptions] an object with plugin options
  55465. * @private
  55466. */
  55467. const reinitPlugin = function (newOptions) {
  55468. cleanupEvents();
  55469. initPlugin(player, newOptions);
  55470. };
  55471. player.on('error', errorHandler);
  55472. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  55473. // initializing the plugin
  55474. player.reloadSourceOnError = reinitPlugin;
  55475. };
  55476. /**
  55477. * Reload the source when an error is detected as long as there
  55478. * wasn't an error previously within the last 30 seconds
  55479. *
  55480. * @param {Object} [options] an object with plugin options
  55481. */
  55482. const reloadSourceOnError = function (options) {
  55483. initPlugin(this, options);
  55484. };
  55485. var version$4 = "3.0.2";
  55486. var version$3 = "6.3.0";
  55487. var version$2 = "1.0.1";
  55488. var version$1 = "6.0.0";
  55489. var version = "4.0.1";
  55490. /**
  55491. * @file videojs-http-streaming.js
  55492. *
  55493. * The main file for the VHS project.
  55494. * License: https://github.com/videojs/videojs-http-streaming/blob/main/LICENSE
  55495. */
  55496. const Vhs = {
  55497. PlaylistLoader,
  55498. Playlist,
  55499. utils,
  55500. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  55501. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  55502. lastBandwidthSelector,
  55503. movingAverageBandwidthSelector,
  55504. comparePlaylistBandwidth,
  55505. comparePlaylistResolution,
  55506. xhr: xhrFactory()
  55507. }; // Define getter/setters for config properties
  55508. Object.keys(Config).forEach(prop => {
  55509. Object.defineProperty(Vhs, prop, {
  55510. get() {
  55511. videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  55512. return Config[prop];
  55513. },
  55514. set(value) {
  55515. videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  55516. if (typeof value !== 'number' || value < 0) {
  55517. videojs.log.warn(`value of Vhs.${prop} must be greater than or equal to 0`);
  55518. return;
  55519. }
  55520. Config[prop] = value;
  55521. }
  55522. });
  55523. });
  55524. const LOCAL_STORAGE_KEY = 'videojs-vhs';
  55525. /**
  55526. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  55527. *
  55528. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  55529. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  55530. * @function handleVhsMediaChange
  55531. */
  55532. const handleVhsMediaChange = function (qualityLevels, playlistLoader) {
  55533. const newPlaylist = playlistLoader.media();
  55534. let selectedIndex = -1;
  55535. for (let i = 0; i < qualityLevels.length; i++) {
  55536. if (qualityLevels[i].id === newPlaylist.id) {
  55537. selectedIndex = i;
  55538. break;
  55539. }
  55540. }
  55541. qualityLevels.selectedIndex_ = selectedIndex;
  55542. qualityLevels.trigger({
  55543. selectedIndex,
  55544. type: 'change'
  55545. });
  55546. };
  55547. /**
  55548. * Adds quality levels to list once playlist metadata is available
  55549. *
  55550. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  55551. * @param {Object} vhs Vhs object to listen to for media events.
  55552. * @function handleVhsLoadedMetadata
  55553. */
  55554. const handleVhsLoadedMetadata = function (qualityLevels, vhs) {
  55555. vhs.representations().forEach(rep => {
  55556. qualityLevels.addQualityLevel(rep);
  55557. });
  55558. handleVhsMediaChange(qualityLevels, vhs.playlists);
  55559. }; // VHS is a source handler, not a tech. Make sure attempts to use it
  55560. // as one do not cause exceptions.
  55561. Vhs.canPlaySource = function () {
  55562. return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  55563. };
  55564. const emeKeySystems = (keySystemOptions, mainPlaylist, audioPlaylist) => {
  55565. if (!keySystemOptions) {
  55566. return keySystemOptions;
  55567. }
  55568. let codecs = {};
  55569. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  55570. codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
  55571. }
  55572. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  55573. codecs.audio = audioPlaylist.attributes.CODECS;
  55574. }
  55575. const videoContentType = getMimeForCodec(codecs.video);
  55576. const audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  55577. const keySystemContentTypes = {};
  55578. for (const keySystem in keySystemOptions) {
  55579. keySystemContentTypes[keySystem] = {};
  55580. if (audioContentType) {
  55581. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  55582. }
  55583. if (videoContentType) {
  55584. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  55585. } // Default to using the video playlist's PSSH even though they may be different, as
  55586. // videojs-contrib-eme will only accept one in the options.
  55587. //
  55588. // This shouldn't be an issue for most cases as early intialization will handle all
  55589. // unique PSSH values, and if they aren't, then encrypted events should have the
  55590. // specific information needed for the unique license.
  55591. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  55592. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  55593. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  55594. // so we need to prevent overwriting the URL entirely
  55595. if (typeof keySystemOptions[keySystem] === 'string') {
  55596. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  55597. }
  55598. }
  55599. return merge(keySystemOptions, keySystemContentTypes);
  55600. };
  55601. /**
  55602. * @typedef {Object} KeySystems
  55603. *
  55604. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  55605. * Note: not all options are listed here.
  55606. *
  55607. * @property {Uint8Array} [pssh]
  55608. * Protection System Specific Header
  55609. */
  55610. /**
  55611. * Goes through all the playlists and collects an array of KeySystems options objects
  55612. * containing each playlist's keySystems and their pssh values, if available.
  55613. *
  55614. * @param {Object[]} playlists
  55615. * The playlists to look through
  55616. * @param {string[]} keySystems
  55617. * The keySystems to collect pssh values for
  55618. *
  55619. * @return {KeySystems[]}
  55620. * An array of KeySystems objects containing available key systems and their
  55621. * pssh values
  55622. */
  55623. const getAllPsshKeySystemsOptions = (playlists, keySystems) => {
  55624. return playlists.reduce((keySystemsArr, playlist) => {
  55625. if (!playlist.contentProtection) {
  55626. return keySystemsArr;
  55627. }
  55628. const keySystemsOptions = keySystems.reduce((keySystemsObj, keySystem) => {
  55629. const keySystemOptions = playlist.contentProtection[keySystem];
  55630. if (keySystemOptions && keySystemOptions.pssh) {
  55631. keySystemsObj[keySystem] = {
  55632. pssh: keySystemOptions.pssh
  55633. };
  55634. }
  55635. return keySystemsObj;
  55636. }, {});
  55637. if (Object.keys(keySystemsOptions).length) {
  55638. keySystemsArr.push(keySystemsOptions);
  55639. }
  55640. return keySystemsArr;
  55641. }, []);
  55642. };
  55643. /**
  55644. * Returns a promise that waits for the
  55645. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  55646. *
  55647. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  55648. * browsers.
  55649. *
  55650. * As per the above ticket, this is particularly important for Chrome, where, if
  55651. * unencrypted content is appended before encrypted content and the key session has not
  55652. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  55653. * during playback.
  55654. *
  55655. * @param {Object} player
  55656. * The player instance
  55657. * @param {Object[]} sourceKeySystems
  55658. * The key systems options from the player source
  55659. * @param {Object} [audioMedia]
  55660. * The active audio media playlist (optional)
  55661. * @param {Object[]} mainPlaylists
  55662. * The playlists found on the main playlist object
  55663. *
  55664. * @return {Object}
  55665. * Promise that resolves when the key session has been created
  55666. */
  55667. const waitForKeySessionCreation = ({
  55668. player,
  55669. sourceKeySystems,
  55670. audioMedia,
  55671. mainPlaylists
  55672. }) => {
  55673. if (!player.eme.initializeMediaKeys) {
  55674. return Promise.resolve();
  55675. } // TODO should all audio PSSH values be initialized for DRM?
  55676. //
  55677. // All unique video rendition pssh values are initialized for DRM, but here only
  55678. // the initial audio playlist license is initialized. In theory, an encrypted
  55679. // event should be fired if the user switches to an alternative audio playlist
  55680. // where a license is required, but this case hasn't yet been tested. In addition, there
  55681. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  55682. // languages).
  55683. const playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  55684. const keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  55685. const initializationFinishedPromises = [];
  55686. const keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  55687. // only place where it should not be deduped is for ms-prefixed APIs, but the early
  55688. // return for IE11 above, and the existence of modern EME APIs in addition to
  55689. // ms-prefixed APIs on Edge should prevent this from being a concern.
  55690. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  55691. keySystemsOptionsArr.forEach(keySystemsOptions => {
  55692. keySessionCreatedPromises.push(new Promise((resolve, reject) => {
  55693. player.tech_.one('keysessioncreated', resolve);
  55694. }));
  55695. initializationFinishedPromises.push(new Promise((resolve, reject) => {
  55696. player.eme.initializeMediaKeys({
  55697. keySystems: keySystemsOptions
  55698. }, err => {
  55699. if (err) {
  55700. reject(err);
  55701. return;
  55702. }
  55703. resolve();
  55704. });
  55705. }));
  55706. }); // The reasons Promise.race is chosen over Promise.any:
  55707. //
  55708. // * Promise.any is only available in Safari 14+.
  55709. // * None of these promises are expected to reject. If they do reject, it might be
  55710. // better here for the race to surface the rejection, rather than mask it by using
  55711. // Promise.any.
  55712. return Promise.race([
  55713. // If a session was previously created, these will all finish resolving without
  55714. // creating a new session, otherwise it will take until the end of all license
  55715. // requests, which is why the key session check is used (to make setup much faster).
  55716. Promise.all(initializationFinishedPromises),
  55717. // Once a single session is created, the browser knows DRM will be used.
  55718. Promise.race(keySessionCreatedPromises)]);
  55719. };
  55720. /**
  55721. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  55722. * there are keySystems on the source, sets up source options to prepare the source for
  55723. * eme.
  55724. *
  55725. * @param {Object} player
  55726. * The player instance
  55727. * @param {Object[]} sourceKeySystems
  55728. * The key systems options from the player source
  55729. * @param {Object} media
  55730. * The active media playlist
  55731. * @param {Object} [audioMedia]
  55732. * The active audio media playlist (optional)
  55733. *
  55734. * @return {boolean}
  55735. * Whether or not options were configured and EME is available
  55736. */
  55737. const setupEmeOptions = ({
  55738. player,
  55739. sourceKeySystems,
  55740. media,
  55741. audioMedia
  55742. }) => {
  55743. const sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  55744. if (!sourceOptions) {
  55745. return false;
  55746. }
  55747. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  55748. // do nothing.
  55749. if (sourceOptions && !player.eme) {
  55750. videojs.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  55751. return false;
  55752. }
  55753. return true;
  55754. };
  55755. const getVhsLocalStorage = () => {
  55756. if (!window.localStorage) {
  55757. return null;
  55758. }
  55759. const storedObject = window.localStorage.getItem(LOCAL_STORAGE_KEY);
  55760. if (!storedObject) {
  55761. return null;
  55762. }
  55763. try {
  55764. return JSON.parse(storedObject);
  55765. } catch (e) {
  55766. // someone may have tampered with the value
  55767. return null;
  55768. }
  55769. };
  55770. const updateVhsLocalStorage = options => {
  55771. if (!window.localStorage) {
  55772. return false;
  55773. }
  55774. let objectToStore = getVhsLocalStorage();
  55775. objectToStore = objectToStore ? merge(objectToStore, options) : options;
  55776. try {
  55777. window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  55778. } catch (e) {
  55779. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  55780. // storage is set to 0).
  55781. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  55782. // No need to perform any operation.
  55783. return false;
  55784. }
  55785. return objectToStore;
  55786. };
  55787. /**
  55788. * Parses VHS-supported media types from data URIs. See
  55789. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  55790. * for information on data URIs.
  55791. *
  55792. * @param {string} dataUri
  55793. * The data URI
  55794. *
  55795. * @return {string|Object}
  55796. * The parsed object/string, or the original string if no supported media type
  55797. * was found
  55798. */
  55799. const expandDataUri = dataUri => {
  55800. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  55801. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  55802. } // no known case for this data URI, return the string as-is
  55803. return dataUri;
  55804. };
  55805. /**
  55806. * Whether the browser has built-in HLS support.
  55807. */
  55808. Vhs.supportsNativeHls = function () {
  55809. if (!document || !document.createElement) {
  55810. return false;
  55811. }
  55812. const video = document.createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  55813. if (!videojs.getTech('Html5').isSupported()) {
  55814. return false;
  55815. } // HLS manifests can go by many mime-types
  55816. const canPlay = [
  55817. // Apple santioned
  55818. 'application/vnd.apple.mpegurl',
  55819. // Apple sanctioned for backwards compatibility
  55820. 'audio/mpegurl',
  55821. // Very common
  55822. 'audio/x-mpegurl',
  55823. // Very common
  55824. 'application/x-mpegurl',
  55825. // Included for completeness
  55826. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  55827. return canPlay.some(function (canItPlay) {
  55828. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  55829. });
  55830. }();
  55831. Vhs.supportsNativeDash = function () {
  55832. if (!document || !document.createElement || !videojs.getTech('Html5').isSupported()) {
  55833. return false;
  55834. }
  55835. return /maybe|probably/i.test(document.createElement('video').canPlayType('application/dash+xml'));
  55836. }();
  55837. Vhs.supportsTypeNatively = type => {
  55838. if (type === 'hls') {
  55839. return Vhs.supportsNativeHls;
  55840. }
  55841. if (type === 'dash') {
  55842. return Vhs.supportsNativeDash;
  55843. }
  55844. return false;
  55845. };
  55846. /**
  55847. * VHS is a source handler, not a tech. Make sure attempts to use it
  55848. * as one do not cause exceptions.
  55849. */
  55850. Vhs.isSupported = function () {
  55851. return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  55852. };
  55853. const Component = videojs.getComponent('Component');
  55854. /**
  55855. * The Vhs Handler object, where we orchestrate all of the parts
  55856. * of VHS to interact with video.js
  55857. *
  55858. * @class VhsHandler
  55859. * @extends videojs.Component
  55860. * @param {Object} source the soruce object
  55861. * @param {Tech} tech the parent tech object
  55862. * @param {Object} options optional and required options
  55863. */
  55864. class VhsHandler extends Component {
  55865. constructor(source, tech, options) {
  55866. super(tech, options.vhs); // if a tech level `initialBandwidth` option was passed
  55867. // use that over the VHS level `bandwidth` option
  55868. if (typeof options.initialBandwidth === 'number') {
  55869. this.options_.bandwidth = options.initialBandwidth;
  55870. }
  55871. this.logger_ = logger('VhsHandler'); // we need access to the player in some cases,
  55872. // so, get it from Video.js via the `playerId`
  55873. if (tech.options_ && tech.options_.playerId) {
  55874. const _player = videojs.getPlayer(tech.options_.playerId);
  55875. this.player_ = _player;
  55876. }
  55877. this.tech_ = tech;
  55878. this.source_ = source;
  55879. this.stats = {};
  55880. this.ignoreNextSeekingEvent_ = false;
  55881. this.setOptions_();
  55882. if (this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  55883. tech.overrideNativeAudioTracks(true);
  55884. tech.overrideNativeVideoTracks(true);
  55885. } else if (this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  55886. // overriding native VHS only works if audio tracks have been emulated
  55887. // error early if we're misconfigured
  55888. throw new Error('Overriding native VHS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  55889. } // listen for fullscreenchange events for this player so that we
  55890. // can adjust our quality selection quickly
  55891. this.on(document, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], event => {
  55892. const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  55893. if (fullscreenElement && fullscreenElement.contains(this.tech_.el())) {
  55894. this.playlistController_.fastQualityChange_();
  55895. } else {
  55896. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  55897. // than full screen, see if there should be a rendition switch down to preserve
  55898. // bandwidth.
  55899. this.playlistController_.checkABR_();
  55900. }
  55901. });
  55902. this.on(this.tech_, 'seeking', function () {
  55903. if (this.ignoreNextSeekingEvent_) {
  55904. this.ignoreNextSeekingEvent_ = false;
  55905. return;
  55906. }
  55907. this.setCurrentTime(this.tech_.currentTime());
  55908. });
  55909. this.on(this.tech_, 'error', function () {
  55910. // verify that the error was real and we are loaded
  55911. // enough to have pc loaded.
  55912. if (this.tech_.error() && this.playlistController_) {
  55913. this.playlistController_.pauseLoading();
  55914. }
  55915. });
  55916. this.on(this.tech_, 'play', this.play);
  55917. }
  55918. setOptions_() {
  55919. // defaults
  55920. this.options_.withCredentials = this.options_.withCredentials || false;
  55921. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  55922. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  55923. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  55924. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  55925. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  55926. this.options_.customTagParsers = this.options_.customTagParsers || [];
  55927. this.options_.customTagMappers = this.options_.customTagMappers || [];
  55928. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  55929. this.options_.llhls = this.options_.llhls === false ? false : true;
  55930. this.options_.bufferBasedABR = this.options_.bufferBasedABR || false;
  55931. if (typeof this.options_.playlistExclusionDuration !== 'number') {
  55932. this.options_.playlistExclusionDuration = 5 * 60;
  55933. }
  55934. if (typeof this.options_.bandwidth !== 'number') {
  55935. if (this.options_.useBandwidthFromLocalStorage) {
  55936. const storedObject = getVhsLocalStorage();
  55937. if (storedObject && storedObject.bandwidth) {
  55938. this.options_.bandwidth = storedObject.bandwidth;
  55939. this.tech_.trigger({
  55940. type: 'usage',
  55941. name: 'vhs-bandwidth-from-local-storage'
  55942. });
  55943. }
  55944. if (storedObject && storedObject.throughput) {
  55945. this.options_.throughput = storedObject.throughput;
  55946. this.tech_.trigger({
  55947. type: 'usage',
  55948. name: 'vhs-throughput-from-local-storage'
  55949. });
  55950. }
  55951. }
  55952. } // if bandwidth was not set by options or pulled from local storage, start playlist
  55953. // selection at a reasonable bandwidth
  55954. if (typeof this.options_.bandwidth !== 'number') {
  55955. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  55956. } // If the bandwidth number is unchanged from the initial setting
  55957. // then this takes precedence over the enableLowInitialPlaylist option
  55958. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  55959. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'customTagParsers', 'customTagMappers', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'bufferBasedABR', 'liveRangeSafeTimeDelta', 'llhls', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'exactManifestTimings', 'leastPixelDiffSelector'].forEach(option => {
  55960. if (typeof this.source_[option] !== 'undefined') {
  55961. this.options_[option] = this.source_[option];
  55962. }
  55963. });
  55964. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  55965. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  55966. }
  55967. /**
  55968. * called when player.src gets called, handle a new source
  55969. *
  55970. * @param {Object} src the source object to handle
  55971. */
  55972. src(src, type) {
  55973. // do nothing if the src is falsey
  55974. if (!src) {
  55975. return;
  55976. }
  55977. this.setOptions_(); // add main playlist controller options
  55978. this.options_.src = expandDataUri(this.source_.src);
  55979. this.options_.tech = this.tech_;
  55980. this.options_.externVhs = Vhs;
  55981. this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  55982. this.options_.seekTo = time => {
  55983. this.tech_.setCurrentTime(time);
  55984. };
  55985. this.playlistController_ = new PlaylistController(this.options_);
  55986. const playbackWatcherOptions = merge({
  55987. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  55988. }, this.options_, {
  55989. seekable: () => this.seekable(),
  55990. media: () => this.playlistController_.media(),
  55991. playlistController: this.playlistController_
  55992. });
  55993. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  55994. this.playlistController_.on('error', () => {
  55995. const player = videojs.players[this.tech_.options_.playerId];
  55996. let error = this.playlistController_.error;
  55997. if (typeof error === 'object' && !error.code) {
  55998. error.code = 3;
  55999. } else if (typeof error === 'string') {
  56000. error = {
  56001. message: error,
  56002. code: 3
  56003. };
  56004. }
  56005. player.error(error);
  56006. });
  56007. const defaultSelector = this.options_.bufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  56008. // compatibility with < v2
  56009. this.playlistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  56010. this.playlistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  56011. this.playlists = this.playlistController_.mainPlaylistLoader_;
  56012. this.mediaSource = this.playlistController_.mediaSource; // Proxy assignment of some properties to the main playlist
  56013. // controller. Using a custom property for backwards compatibility
  56014. // with < v2
  56015. Object.defineProperties(this, {
  56016. selectPlaylist: {
  56017. get() {
  56018. return this.playlistController_.selectPlaylist;
  56019. },
  56020. set(selectPlaylist) {
  56021. this.playlistController_.selectPlaylist = selectPlaylist.bind(this);
  56022. }
  56023. },
  56024. throughput: {
  56025. get() {
  56026. return this.playlistController_.mainSegmentLoader_.throughput.rate;
  56027. },
  56028. set(throughput) {
  56029. this.playlistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  56030. // for the cumulative average
  56031. this.playlistController_.mainSegmentLoader_.throughput.count = 1;
  56032. }
  56033. },
  56034. bandwidth: {
  56035. get() {
  56036. let playerBandwidthEst = this.playlistController_.mainSegmentLoader_.bandwidth;
  56037. const networkInformation = window.navigator.connection || window.navigator.mozConnection || window.navigator.webkitConnection;
  56038. const tenMbpsAsBitsPerSecond = 10e6;
  56039. if (this.options_.useNetworkInformationApi && networkInformation) {
  56040. // downlink returns Mbps
  56041. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  56042. const networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  56043. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  56044. // high quality streams are not filtered out.
  56045. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  56046. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  56047. } else {
  56048. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  56049. }
  56050. }
  56051. return playerBandwidthEst;
  56052. },
  56053. set(bandwidth) {
  56054. this.playlistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  56055. // `count` is set to zero that current value of `rate` isn't included
  56056. // in the cumulative average
  56057. this.playlistController_.mainSegmentLoader_.throughput = {
  56058. rate: 0,
  56059. count: 0
  56060. };
  56061. }
  56062. },
  56063. /**
  56064. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  56065. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  56066. * the entire process after that - decryption, transmuxing, and appending - provided
  56067. * by `throughput`.
  56068. *
  56069. * Since the two process are serial, the overall system bandwidth is given by:
  56070. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  56071. */
  56072. systemBandwidth: {
  56073. get() {
  56074. const invBandwidth = 1 / (this.bandwidth || 1);
  56075. let invThroughput;
  56076. if (this.throughput > 0) {
  56077. invThroughput = 1 / this.throughput;
  56078. } else {
  56079. invThroughput = 0;
  56080. }
  56081. const systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  56082. return systemBitrate;
  56083. },
  56084. set() {
  56085. videojs.log.error('The "systemBandwidth" property is read-only');
  56086. }
  56087. }
  56088. });
  56089. if (this.options_.bandwidth) {
  56090. this.bandwidth = this.options_.bandwidth;
  56091. }
  56092. if (this.options_.throughput) {
  56093. this.throughput = this.options_.throughput;
  56094. }
  56095. Object.defineProperties(this.stats, {
  56096. bandwidth: {
  56097. get: () => this.bandwidth || 0,
  56098. enumerable: true
  56099. },
  56100. mediaRequests: {
  56101. get: () => this.playlistController_.mediaRequests_() || 0,
  56102. enumerable: true
  56103. },
  56104. mediaRequestsAborted: {
  56105. get: () => this.playlistController_.mediaRequestsAborted_() || 0,
  56106. enumerable: true
  56107. },
  56108. mediaRequestsTimedout: {
  56109. get: () => this.playlistController_.mediaRequestsTimedout_() || 0,
  56110. enumerable: true
  56111. },
  56112. mediaRequestsErrored: {
  56113. get: () => this.playlistController_.mediaRequestsErrored_() || 0,
  56114. enumerable: true
  56115. },
  56116. mediaTransferDuration: {
  56117. get: () => this.playlistController_.mediaTransferDuration_() || 0,
  56118. enumerable: true
  56119. },
  56120. mediaBytesTransferred: {
  56121. get: () => this.playlistController_.mediaBytesTransferred_() || 0,
  56122. enumerable: true
  56123. },
  56124. mediaSecondsLoaded: {
  56125. get: () => this.playlistController_.mediaSecondsLoaded_() || 0,
  56126. enumerable: true
  56127. },
  56128. mediaAppends: {
  56129. get: () => this.playlistController_.mediaAppends_() || 0,
  56130. enumerable: true
  56131. },
  56132. mainAppendsToLoadedData: {
  56133. get: () => this.playlistController_.mainAppendsToLoadedData_() || 0,
  56134. enumerable: true
  56135. },
  56136. audioAppendsToLoadedData: {
  56137. get: () => this.playlistController_.audioAppendsToLoadedData_() || 0,
  56138. enumerable: true
  56139. },
  56140. appendsToLoadedData: {
  56141. get: () => this.playlistController_.appendsToLoadedData_() || 0,
  56142. enumerable: true
  56143. },
  56144. timeToLoadedData: {
  56145. get: () => this.playlistController_.timeToLoadedData_() || 0,
  56146. enumerable: true
  56147. },
  56148. buffered: {
  56149. get: () => timeRangesToArray(this.tech_.buffered()),
  56150. enumerable: true
  56151. },
  56152. currentTime: {
  56153. get: () => this.tech_.currentTime(),
  56154. enumerable: true
  56155. },
  56156. currentSource: {
  56157. get: () => this.tech_.currentSource_,
  56158. enumerable: true
  56159. },
  56160. currentTech: {
  56161. get: () => this.tech_.name_,
  56162. enumerable: true
  56163. },
  56164. duration: {
  56165. get: () => this.tech_.duration(),
  56166. enumerable: true
  56167. },
  56168. main: {
  56169. get: () => this.playlists.main,
  56170. enumerable: true
  56171. },
  56172. playerDimensions: {
  56173. get: () => this.tech_.currentDimensions(),
  56174. enumerable: true
  56175. },
  56176. seekable: {
  56177. get: () => timeRangesToArray(this.tech_.seekable()),
  56178. enumerable: true
  56179. },
  56180. timestamp: {
  56181. get: () => Date.now(),
  56182. enumerable: true
  56183. },
  56184. videoPlaybackQuality: {
  56185. get: () => this.tech_.getVideoPlaybackQuality(),
  56186. enumerable: true
  56187. }
  56188. });
  56189. this.tech_.one('canplay', this.playlistController_.setupFirstPlay.bind(this.playlistController_));
  56190. this.tech_.on('bandwidthupdate', () => {
  56191. if (this.options_.useBandwidthFromLocalStorage) {
  56192. updateVhsLocalStorage({
  56193. bandwidth: this.bandwidth,
  56194. throughput: Math.round(this.throughput)
  56195. });
  56196. }
  56197. });
  56198. this.playlistController_.on('selectedinitialmedia', () => {
  56199. // Add the manual rendition mix-in to VhsHandler
  56200. renditionSelectionMixin(this);
  56201. });
  56202. this.playlistController_.sourceUpdater_.on('createdsourcebuffers', () => {
  56203. this.setupEme_();
  56204. }); // the bandwidth of the primary segment loader is our best
  56205. // estimate of overall bandwidth
  56206. this.on(this.playlistController_, 'progress', function () {
  56207. this.tech_.trigger('progress');
  56208. }); // In the live case, we need to ignore the very first `seeking` event since
  56209. // that will be the result of the seek-to-live behavior
  56210. this.on(this.playlistController_, 'firstplay', function () {
  56211. this.ignoreNextSeekingEvent_ = true;
  56212. });
  56213. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  56214. // this can occur if someone sets the src in player.ready(), for instance
  56215. if (!this.tech_.el()) {
  56216. return;
  56217. }
  56218. this.mediaSourceUrl_ = window.URL.createObjectURL(this.playlistController_.mediaSource);
  56219. this.tech_.src(this.mediaSourceUrl_);
  56220. }
  56221. createKeySessions_() {
  56222. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  56223. this.logger_('waiting for EME key session creation');
  56224. waitForKeySessionCreation({
  56225. player: this.player_,
  56226. sourceKeySystems: this.source_.keySystems,
  56227. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  56228. mainPlaylists: this.playlists.main.playlists
  56229. }).then(() => {
  56230. this.logger_('created EME key session');
  56231. this.playlistController_.sourceUpdater_.initializedEme();
  56232. }).catch(err => {
  56233. this.logger_('error while creating EME key session', err);
  56234. this.player_.error({
  56235. message: 'Failed to initialize media keys for EME',
  56236. code: 3
  56237. });
  56238. });
  56239. }
  56240. handleWaitingForKey_() {
  56241. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  56242. // the key is in the manifest. While this should've happened on initial source load, it
  56243. // may happen again in live streams where the keys change, and the manifest info
  56244. // reflects the update.
  56245. //
  56246. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  56247. // already requested keys for, we don't have to worry about this generating extraneous
  56248. // requests.
  56249. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  56250. this.createKeySessions_();
  56251. }
  56252. /**
  56253. * If necessary and EME is available, sets up EME options and waits for key session
  56254. * creation.
  56255. *
  56256. * This function also updates the source updater so taht it can be used, as for some
  56257. * browsers, EME must be configured before content is appended (if appending unencrypted
  56258. * content before encrypted content).
  56259. */
  56260. setupEme_() {
  56261. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  56262. const didSetupEmeOptions = setupEmeOptions({
  56263. player: this.player_,
  56264. sourceKeySystems: this.source_.keySystems,
  56265. media: this.playlists.media(),
  56266. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  56267. });
  56268. this.player_.tech_.on('keystatuschange', e => {
  56269. if (e.status !== 'output-restricted') {
  56270. return;
  56271. }
  56272. const mainPlaylist = this.playlistController_.main();
  56273. if (!mainPlaylist || !mainPlaylist.playlists) {
  56274. return;
  56275. }
  56276. const excludedHDPlaylists = []; // Assume all HD streams are unplayable and exclude them from ABR selection
  56277. mainPlaylist.playlists.forEach(playlist => {
  56278. if (playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height >= 720) {
  56279. if (!playlist.excludeUntil || playlist.excludeUntil < Infinity) {
  56280. playlist.excludeUntil = Infinity;
  56281. excludedHDPlaylists.push(playlist);
  56282. }
  56283. }
  56284. });
  56285. if (excludedHDPlaylists.length) {
  56286. 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
  56287. this.playlistController_.fastQualityChange_();
  56288. }
  56289. });
  56290. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  56291. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_); // In IE11 this is too early to initialize media keys, and IE11 does not support
  56292. // promises.
  56293. if (videojs.browser.IE_VERSION === 11 || !didSetupEmeOptions) {
  56294. // If EME options were not set up, we've done all we could to initialize EME.
  56295. this.playlistController_.sourceUpdater_.initializedEme();
  56296. return;
  56297. }
  56298. this.createKeySessions_();
  56299. }
  56300. /**
  56301. * Initializes the quality levels and sets listeners to update them.
  56302. *
  56303. * @method setupQualityLevels_
  56304. * @private
  56305. */
  56306. setupQualityLevels_() {
  56307. const player = videojs.players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  56308. // or qualityLevels_ listeners have already been setup, do nothing.
  56309. if (!player || !player.qualityLevels || this.qualityLevels_) {
  56310. return;
  56311. }
  56312. this.qualityLevels_ = player.qualityLevels();
  56313. this.playlistController_.on('selectedinitialmedia', () => {
  56314. handleVhsLoadedMetadata(this.qualityLevels_, this);
  56315. });
  56316. this.playlists.on('mediachange', () => {
  56317. handleVhsMediaChange(this.qualityLevels_, this.playlists);
  56318. });
  56319. }
  56320. /**
  56321. * return the version
  56322. */
  56323. static version() {
  56324. return {
  56325. '@videojs/http-streaming': version$4,
  56326. 'mux.js': version$3,
  56327. 'mpd-parser': version$2,
  56328. 'm3u8-parser': version$1,
  56329. 'aes-decrypter': version
  56330. };
  56331. }
  56332. /**
  56333. * return the version
  56334. */
  56335. version() {
  56336. return this.constructor.version();
  56337. }
  56338. canChangeType() {
  56339. return SourceUpdater.canChangeType();
  56340. }
  56341. /**
  56342. * Begin playing the video.
  56343. */
  56344. play() {
  56345. this.playlistController_.play();
  56346. }
  56347. /**
  56348. * a wrapper around the function in PlaylistController
  56349. */
  56350. setCurrentTime(currentTime) {
  56351. this.playlistController_.setCurrentTime(currentTime);
  56352. }
  56353. /**
  56354. * a wrapper around the function in PlaylistController
  56355. */
  56356. duration() {
  56357. return this.playlistController_.duration();
  56358. }
  56359. /**
  56360. * a wrapper around the function in PlaylistController
  56361. */
  56362. seekable() {
  56363. return this.playlistController_.seekable();
  56364. }
  56365. /**
  56366. * Abort all outstanding work and cleanup.
  56367. */
  56368. dispose() {
  56369. if (this.playbackWatcher_) {
  56370. this.playbackWatcher_.dispose();
  56371. }
  56372. if (this.playlistController_) {
  56373. this.playlistController_.dispose();
  56374. }
  56375. if (this.qualityLevels_) {
  56376. this.qualityLevels_.dispose();
  56377. }
  56378. if (this.tech_ && this.tech_.vhs) {
  56379. delete this.tech_.vhs;
  56380. }
  56381. if (this.mediaSourceUrl_ && window.URL.revokeObjectURL) {
  56382. window.URL.revokeObjectURL(this.mediaSourceUrl_);
  56383. this.mediaSourceUrl_ = null;
  56384. }
  56385. if (this.tech_) {
  56386. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  56387. }
  56388. super.dispose();
  56389. }
  56390. convertToProgramTime(time, callback) {
  56391. return getProgramTime({
  56392. playlist: this.playlistController_.media(),
  56393. time,
  56394. callback
  56395. });
  56396. } // the player must be playing before calling this
  56397. seekToProgramTime(programTime, callback, pauseAfterSeek = true, retryCount = 2) {
  56398. return seekToProgramTime({
  56399. programTime,
  56400. playlist: this.playlistController_.media(),
  56401. retryCount,
  56402. pauseAfterSeek,
  56403. seekTo: this.options_.seekTo,
  56404. tech: this.options_.tech,
  56405. callback
  56406. });
  56407. }
  56408. }
  56409. /**
  56410. * The Source Handler object, which informs video.js what additional
  56411. * MIME types are supported and sets up playback. It is registered
  56412. * automatically to the appropriate tech based on the capabilities of
  56413. * the browser it is running in. It is not necessary to use or modify
  56414. * this object in normal usage.
  56415. */
  56416. const VhsSourceHandler = {
  56417. name: 'videojs-http-streaming',
  56418. VERSION: version$4,
  56419. canHandleSource(srcObj, options = {}) {
  56420. const localOptions = merge(videojs.options, options);
  56421. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  56422. },
  56423. handleSource(source, tech, options = {}) {
  56424. const localOptions = merge(videojs.options, options);
  56425. tech.vhs = new VhsHandler(source, tech, localOptions);
  56426. tech.vhs.xhr = xhrFactory();
  56427. tech.vhs.src(source.src, source.type);
  56428. return tech.vhs;
  56429. },
  56430. canPlayType(type, options) {
  56431. const simpleType = simpleTypeFromSourceType(type);
  56432. if (!simpleType) {
  56433. return '';
  56434. }
  56435. const overrideNative = VhsSourceHandler.getOverrideNative(options);
  56436. const supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  56437. const canUseMsePlayback = !supportsTypeNatively || overrideNative;
  56438. return canUseMsePlayback ? 'maybe' : '';
  56439. },
  56440. getOverrideNative(options = {}) {
  56441. const {
  56442. vhs = {}
  56443. } = options;
  56444. const defaultOverrideNative = !(videojs.browser.IS_ANY_SAFARI || videojs.browser.IS_IOS);
  56445. const {
  56446. overrideNative = defaultOverrideNative
  56447. } = vhs;
  56448. return overrideNative;
  56449. }
  56450. };
  56451. /**
  56452. * Check to see if the native MediaSource object exists and supports
  56453. * an MP4 container with both H.264 video and AAC-LC audio.
  56454. *
  56455. * @return {boolean} if native media sources are supported
  56456. */
  56457. const supportsNativeMediaSources = () => {
  56458. return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  56459. }; // register source handlers with the appropriate techs
  56460. if (supportsNativeMediaSources()) {
  56461. videojs.getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  56462. }
  56463. videojs.VhsHandler = VhsHandler;
  56464. videojs.VhsSourceHandler = VhsSourceHandler;
  56465. videojs.Vhs = Vhs;
  56466. if (!videojs.use) {
  56467. videojs.registerComponent('Vhs', Vhs);
  56468. }
  56469. videojs.options.vhs = videojs.options.vhs || {};
  56470. if (!videojs.getPlugin || !videojs.getPlugin('reloadSourceOnError')) {
  56471. videojs.registerPlugin('reloadSourceOnError', reloadSourceOnError);
  56472. }
  56473. return videojs;
  56474. }));